wezard 3.0.3 → 3.0.5
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/CLAUDE.md +1 -1
- package/README.md +271 -193
- package/cli/wezard.sh +109 -12
- package/config.example.jsonc +26 -17
- package/dist/cli/audit.js +42 -25
- package/dist/cli/audit.js.map +1 -1
- package/dist/cli/ext.js +1 -1
- package/dist/cli/ext.js.map +1 -1
- package/dist/cli/init.js +4 -1
- package/dist/cli/init.js.map +1 -1
- package/dist/cli/wx.js +3 -0
- package/dist/cli/wx.js.map +1 -1
- package/dist/daemon/approval.js +11 -10
- package/dist/daemon/approval.js.map +1 -1
- package/dist/daemon/audit.js +12 -0
- package/dist/daemon/audit.js.map +1 -1
- package/dist/daemon/bg-tasks.js +74 -0
- package/dist/daemon/bg-tasks.js.map +1 -0
- package/dist/daemon/channel-context.js +2 -2
- package/dist/daemon/channel-context.js.map +1 -1
- package/dist/daemon/channel-newpost.js +88 -0
- package/dist/daemon/channel-newpost.js.map +1 -0
- package/dist/daemon/channel-onboarding.js +27 -31
- package/dist/daemon/channel-onboarding.js.map +1 -1
- package/dist/daemon/channel-posts.js +51 -8
- package/dist/daemon/channel-posts.js.map +1 -1
- package/dist/daemon/channel-rebind.js +4 -5
- package/dist/daemon/channel-rebind.js.map +1 -1
- package/dist/daemon/channel.js +79 -35
- package/dist/daemon/channel.js.map +1 -1
- package/dist/daemon/danger-scrub.js +18 -1
- package/dist/daemon/danger-scrub.js.map +1 -1
- package/dist/daemon/danger-workspace.js +177 -0
- package/dist/daemon/danger-workspace.js.map +1 -0
- package/dist/daemon/danger.js +293 -23
- package/dist/daemon/danger.js.map +1 -1
- package/dist/daemon/detail.js +1 -0
- package/dist/daemon/detail.js.map +1 -1
- package/dist/daemon/handoff.js +27 -10
- package/dist/daemon/handoff.js.map +1 -1
- package/dist/daemon/http.js +15 -3
- package/dist/daemon/http.js.map +1 -1
- package/dist/daemon/inbound.js +36 -7
- package/dist/daemon/inbound.js.map +1 -1
- package/dist/daemon/index.js +584 -343
- package/dist/daemon/index.js.map +1 -1
- package/dist/daemon/loop-lag.js +39 -0
- package/dist/daemon/loop-lag.js.map +1 -0
- package/dist/daemon/mcp-http.js +3 -0
- package/dist/daemon/mcp-http.js.map +1 -1
- package/dist/daemon/mirror-bridge.js +163 -48
- package/dist/daemon/mirror-bridge.js.map +1 -1
- package/dist/daemon/onboarding.js +25 -8
- package/dist/daemon/onboarding.js.map +1 -1
- package/dist/daemon/peers.js +61 -12
- package/dist/daemon/peers.js.map +1 -1
- package/dist/daemon/quota.js +1 -1
- package/dist/daemon/quota.js.map +1 -1
- package/dist/daemon/room-archive.js +189 -0
- package/dist/daemon/room-archive.js.map +1 -0
- package/dist/daemon/room-bind.js +16 -109
- package/dist/daemon/room-bind.js.map +1 -1
- package/dist/daemon/room-facts.js +2 -1
- package/dist/daemon/room-facts.js.map +1 -1
- package/dist/daemon/room-hub.js +65 -10
- package/dist/daemon/room-hub.js.map +1 -1
- package/dist/daemon/room-watchdog.js +4 -0
- package/dist/daemon/room-watchdog.js.map +1 -1
- package/dist/daemon/rooms.js +203 -11
- package/dist/daemon/rooms.js.map +1 -1
- package/dist/daemon/spawn-tmux.js +41 -21
- package/dist/daemon/spawn-tmux.js.map +1 -1
- package/dist/daemon/steward-model.js +19 -4
- package/dist/daemon/steward-model.js.map +1 -1
- package/dist/daemon/steward.js +12 -0
- package/dist/daemon/steward.js.map +1 -1
- package/dist/daemon/store-metrics.js +124 -0
- package/dist/daemon/store-metrics.js.map +1 -0
- package/dist/daemon/tool-latency.js +24 -0
- package/dist/daemon/tool-latency.js.map +1 -0
- package/dist/daemon/wezard-session.js +1 -1
- package/dist/daemon/wezard-session.js.map +1 -1
- package/dist/daemon/wizard.js +4 -4
- package/dist/daemon/wizard.js.map +1 -1
- package/dist/daemon/zombie-panes.js +216 -0
- package/dist/daemon/zombie-panes.js.map +1 -0
- package/dist/mcp/tools.js +20 -17
- package/dist/mcp/tools.js.map +1 -1
- package/dist/shared/chat-http.js +8 -4
- package/dist/shared/chat-http.js.map +1 -1
- package/dist/shared/cli-backends.js +13 -1
- package/dist/shared/cli-backends.js.map +1 -1
- package/dist/shared/config.js +45 -8
- package/dist/shared/config.js.map +1 -1
- package/dist/shared/daemon-client.js +13 -2
- package/dist/shared/daemon-client.js.map +1 -1
- package/dist/shared/external.js +0 -1
- package/dist/shared/external.js.map +1 -1
- package/dist/shared/group-members.js +2 -1
- package/dist/shared/group-members.js.map +1 -1
- package/dist/shared/log.js +76 -5
- package/dist/shared/log.js.map +1 -1
- package/dist/shared/mention-filter.js +63 -0
- package/dist/shared/mention-filter.js.map +1 -0
- package/dist/shared/room-view.js +32 -2
- package/dist/shared/room-view.js.map +1 -1
- package/dist/shared/room.js +12 -3
- package/dist/shared/room.js.map +1 -1
- package/dist/shared/session-hooks.js +1 -1
- package/dist/shared/session-hooks.js.map +1 -1
- package/dist/shared/topic-room.js +23 -0
- package/dist/shared/topic-room.js.map +1 -0
- package/dist/shared/workspace-trust.js +88 -2
- package/dist/shared/workspace-trust.js.map +1 -1
- package/dist/shared/world.js.map +1 -1
- package/dist/svr/index.js +3 -37
- package/dist/svr/index.js.map +1 -1
- package/dist/svr/room-reader.js +140 -0
- package/dist/svr/room-reader.js.map +1 -0
- package/hooks/pre-tool-use.sh +2 -0
- package/package.json +1 -1
- package/web/chat.js +314 -45
package/dist/daemon/index.js
CHANGED
|
@@ -22,17 +22,24 @@ import { bindChatReach } from "./reach.js";
|
|
|
22
22
|
import { kindOf } from "./media.js";
|
|
23
23
|
import { aibotSendMedia, uploadMediaId } from "./aibot-media.js";
|
|
24
24
|
import { startNetWatch } from "./net-watch.js";
|
|
25
|
-
import { startHttp, json, readBody } from "./http.js";
|
|
25
|
+
import { startHttp, json, readBody, inflightRoutes } from "./http.js";
|
|
26
|
+
import { startLoopLagMonitor } from "./loop-lag.js";
|
|
27
|
+
import { bg } from "./bg-tasks.js";
|
|
28
|
+
import { createPaneCensus, fdCount, memo, rssMb, startMetricsSampler, storeSizes } from "./store-metrics.js";
|
|
29
|
+
import { toolLatency } from "./tool-latency.js";
|
|
26
30
|
import { registerMcpHttp } from "./mcp-http.js";
|
|
27
31
|
import { parsePath } from "../shared/config-meta.js";
|
|
28
32
|
import { pickTier, tierOfModel } from "../shared/model-tiers.js";
|
|
29
33
|
import { applyHot, patchedTop, pinChatKeys, configGet, planSet, renderPlan, tierEvidence } from "./config-api.js";
|
|
30
34
|
import { computeUsage, costOf, fmtCost, fmtTokens, sumTotal } from "./usage.js";
|
|
31
35
|
import { humanWakeTail, wakeInjectOpts, wakeTailPorts } from "./wake-tail.js";
|
|
36
|
+
import { newStewardSpec } from "./steward-model.js";
|
|
32
37
|
import { installInboundRouter } from "./inbound.js";
|
|
33
|
-
import { installChannelTransport, installChannelEvents, readChannel, isTopicChat, channelOutboundOf, sendTopicPost, sendTopicReply, sendTopicReplyOrPost } from "./channel.js";
|
|
34
|
-
import {
|
|
35
|
-
import {
|
|
38
|
+
import { installChannelTransport, installChannelEvents, readChannel, isTopicChat, channelOutboundOf, sendTopicPost, sendTopicPostRaw, sendTopicReply, sendTopicReplyOrPost } from "./channel.js";
|
|
39
|
+
import { channelNewPost, createSelfPostLog, newPostSeatOps, newPostTopicOfRef } from "./channel-newpost.js";
|
|
40
|
+
import { channelNameOf, channelNameOfBase, channelOf, channelRefOf, knownChannels, postRefOf, postsOfChannel, topicRoomOf, topicRoomsOf } from "./channel-posts.js";
|
|
41
|
+
import { isTopicRoomId, parseTopicRoomId, topicRoomLabel } from "../shared/topic-room.js";
|
|
42
|
+
import { channelKeyOf, channelMonitorLeaveOps, channelMonitorWanted, channelGuideJoinOps, hostJoinOps, planChannelGuideTurn, topicRoomBirthOps } from "./channel-onboarding.js";
|
|
36
43
|
import { rebindChannel } from "./channel-rebind.js";
|
|
37
44
|
import { loadMirrorStore } from "./mirror-store.js";
|
|
38
45
|
import { startMirror, installMirrorEventListener } from "./mirror-bridge.js";
|
|
@@ -48,10 +55,10 @@ import { makeClaimStartHandler, makeClaimStatusHandler, makeClaimResetHandler, }
|
|
|
48
55
|
import { errText, installResponseTracker } from "./last-response.js";
|
|
49
56
|
import { BindGateClosed, openRoomStore, resolveHashRef } from "./rooms.js";
|
|
50
57
|
import { openShortIdLog } from "./short-id-log.js";
|
|
51
|
-
import { bindCandidates, planBind,
|
|
58
|
+
import { bindCandidates, planBind, planUnbind } from "./room-bind.js";
|
|
52
59
|
import { stewardRoute as resolveSteward } from "./steward.js";
|
|
53
60
|
import { repairStewardInstances, unspawnedStewards } from "./steward-repair.js";
|
|
54
|
-
import { createRoomWatchdog, parsePaneIds } from "./room-watchdog.js";
|
|
61
|
+
import { createRoomWatchdog, parsePaneIds, watchedPaneOf } from "./room-watchdog.js";
|
|
55
62
|
import { pruneLeaveOps, selectRoomPrune } from "./room-prune.js";
|
|
56
63
|
import { createOverdueScan } from "./room-overdue.js";
|
|
57
64
|
import { createRoomHub } from "./room-hub.js";
|
|
@@ -60,11 +67,12 @@ import { extLabel, extNameOf, extReceptionTagOf, extReceptionTargetOf, reception
|
|
|
60
67
|
import { ensureMeRoom, isMeRoom, meChannelSay, meRoomId, meRowMirror, meUserOf, meWorkspaceOf } from "./me-room.js";
|
|
61
68
|
import { autoAdhocTarget } from "./room-auto-adhoc.js";
|
|
62
69
|
import { checkRoomTarget, seatThenAppend } from "./room-spawn.js";
|
|
63
|
-
import { DAEMON, adhocRoomId, bubbleSourceOf, canRename, dmPeers, dmRoomId, expandMsgRefs as sharedExpandRefs, findPairAdhoc, hasMonitor, holderOf, idList, isUid, judgeActivate, judgeNotice, leaveOps, dutiesHeldBy, outboundSourceOf, perceptronCandidates, planDm, planOutbound, quotedRowIds, seatSeenOps, openDuties, roomHost, roomsDirOf, sameWho, whoKey, } from "../shared/room.js";
|
|
70
|
+
import { DAEMON, adhocRoomId, bubbleSourceOf, canRename, dmPeers, dmRoomId, expandMsgRefs as sharedExpandRefs, findPairAdhoc, hasMonitor, holderOf, idList, isUid, judgeActivate, judgeNotice, leaveOps, dutiesHeldBy, outboundSourceOf, perceptronCandidates, planDm, planOutbound, quotedRowIds, seatSeenOps, openDuties, roomHost, roomsArchiveDirOf, roomsDirOf, sameWho, whoKey, } from "../shared/room.js";
|
|
64
71
|
import { CLASS_NAME_MAX, loadClassMerges, loadClassStore, migrateClasses, parseInstanceName, planClasses, renderClassReport, validClassName } from "./classes.js";
|
|
65
72
|
import { addressed, footerTarget, responseFormatPolicy, roomBubble, withBubbleFooter } from "./message-format.js";
|
|
66
|
-
import { procSnapshot, scanClaudeSessions } from "./session-scan.js";
|
|
73
|
+
import { procSnapshot as procSnapshotRaw, scanClaudeSessions as scanClaudeSessionsRaw } from "./session-scan.js";
|
|
67
74
|
import { createLegacyPaneReaper, parsePanePids } from "./legacy-panes.js";
|
|
75
|
+
import { appendReclaimed, createZombiePaneReaper, PANE_FORMAT, parsePaneRows, procStartedAtMs } from "./zombie-panes.js";
|
|
68
76
|
import { removeLegacyMcpFiles } from "../shared/session-mcp.js";
|
|
69
77
|
import { startScheduler, promptWantsFreshWizard, renderTask, sinceOf, } from "./tasks.js";
|
|
70
78
|
import { openTaskRegistry } from "./task-registry.js";
|
|
@@ -74,12 +82,12 @@ import { baseOfKey, bindTagLinker, headed, ownHead, isInternalKey, keyOf, linkTa
|
|
|
74
82
|
import { appendEpisode, clipForCharter, cwdOfMd, episodePath, inboxPath, mdsOf, proposedCwds, memoryPath, memoryRoot, proposeMemory, readMemory } from "./wizard-memory.js";
|
|
75
83
|
import { startSteward, stewardEnvelope, STEWARD_ID, STEWARD_RUN_MS, STEWARD_TARGET } from "./memory-steward.js";
|
|
76
84
|
import { chatBaseOf, chatNameOf, chatPolicyOf, listChatNames, peerAddress } from "./chat-name.js";
|
|
77
|
-
import { appointedSteward, isStewardTarget, localManifestation, markGlobalSteward, STEWARD_KINDS, stewardIdentityOf, stewardRoute, stewardsAt } from "./steward.js";
|
|
85
|
+
import { appointedSteward, coldStartVerdict, isStewardTarget, localManifestation, markGlobalSteward, STEWARD_KINDS, stewardIdentityOf, stewardRoute, stewardsAt } from "./steward.js";
|
|
78
86
|
import { apprenticeOf, ensureApprentice, ensurePatrolTask, handoffLineOf, isApprentice } from "./apprentice.js";
|
|
79
87
|
import { anchorOf, bindWizardStore, loadWizardStore, migrateIdentities, pickName, reconcileKin, wizardStore, settleName, settleAll, backfillBorn, sweepUnborn, BOOT_ID, childrenOf, ancestorsOf, renderCharter, renderLead, renderLeadPlaybook, ROSTER_FRESH_MS, rosterL0, rosterL1, rosterL2, rosterCensus, handoffAt, memoryNudgeAt, MEMORY_NUDGE_FLOOR, MEMORY_MAX, NOTE_MAX, referencedTargets, slotInUse, identityOf as identityOfRec, identityWorkspaceOf, identityEditRefusal, instancesOf, leadSettled, renameNotice, } from "./wizard.js";
|
|
80
88
|
import { faceRefusal } from "./tool-face.js";
|
|
81
89
|
import { activeRows, bindNoticeBox, createNoticeBox, createSeenRing, gcSeen, chatAudience, hears } from "./notices.js";
|
|
82
|
-
import { cacheTouchMs, cacheTtlSec, contextMaterials, firstStamp, lastContextTokens, lastExchange, lastModel,
|
|
90
|
+
import { cacheTouchMs, cacheTtlSec, contextMaterials, firstStamp, lastContextTokens, lastExchange, lastModel, recentAsks } from "./peers.js";
|
|
83
91
|
import { expandHome } from "../shared/paths.js";
|
|
84
92
|
import { expandTask, TemplateError } from "../shared/task-template.js";
|
|
85
93
|
import { loadJsonMap } from "../shared/json-map-store.js";
|
|
@@ -88,11 +96,11 @@ import { registerPlanRoutes } from "./plan-http.js";
|
|
|
88
96
|
import { renderReminder } from "../shared/reminder.js";
|
|
89
97
|
import { busyOf, createHandoffs, handedOff, handingOff } from "./handoff.js";
|
|
90
98
|
import { coldGateOf, wakeCostOf, decide, occupies, rankCandidates, routeDiagnostics, renderCandidates, tierFor } from "./route.js";
|
|
91
|
-
import { parseWhen, planHasOpenDuty, renderRoomRead } from "../shared/room-view.js";
|
|
99
|
+
import { parseWhen, planHasOpenDuty, renderRoomRead, roomKindOf } from "../shared/room-view.js";
|
|
92
100
|
import { memberLabel } from "../shared/room-label.js";
|
|
93
101
|
import { roomFacts, nameTable } from "./room-facts.js";
|
|
94
102
|
import { waitForIdle } from "./wait-idle.js";
|
|
95
|
-
import { applyOnboarding, bindSteward, GUIDE_DESC, guideHandoffOps, guideOf, isGuideManifestation, judgeOnboarding, loadOnboardingStore, needsOnboarding, planOnboardBind, renderGuideOpening, renderGuideRetry, renderOnboardingDone, rewriteStewardBindings } from "./onboarding.js";
|
|
103
|
+
import { applyOnboarding, bindSteward, GUIDE_DESC, guideHandoffOps, guideOf, isGuideManifestation, judgeOnboarding, loadOnboardingStore, needsOnboarding, planOnboardBind, renderGuideOpening, renderGuideRetry, renderOnboardingDone, rewriteStewardBindings, setChannelName } from "./onboarding.js";
|
|
96
104
|
import { reminderToken, startPlanReminders } from "./plan-reminders.js";
|
|
97
105
|
const retiredOrchestrationField = (body) => {
|
|
98
106
|
if (!body || typeof body !== "object" || Array.isArray(body))
|
|
@@ -112,6 +120,9 @@ const unsupportedPeerAddressField = (body) => {
|
|
|
112
120
|
return "tags is unsupported; use names";
|
|
113
121
|
return undefined;
|
|
114
122
|
};
|
|
123
|
+
// 周期 / 后台调用的计时包装 (bg-tasks.ts): session-scan 与 procSnapshot 是 pgrep/lsof/ps 一类的重活。
|
|
124
|
+
const scanClaudeSessions = bg.wrap("session-scan", scanClaudeSessionsRaw);
|
|
125
|
+
const procSnapshot = bg.wrap("proc-snapshot", procSnapshotRaw);
|
|
115
126
|
// pino's file transport is async; without flush, log.fatal before process.exit
|
|
116
127
|
// vanishes. Mirror anything fatal to stderr too so launchd's stderr.log captures it.
|
|
117
128
|
const fatalExit = (msg, extra) => {
|
|
@@ -129,22 +140,27 @@ const main = async () => {
|
|
|
129
140
|
if (stale.length)
|
|
130
141
|
console.warn("[wezard] 配置里还有已废弃的 chatPolicy 旧键 (room 模型已移除, 忽略): " + stale.join(", "));
|
|
131
142
|
}
|
|
143
|
+
// 频道改造 (docs/evolve/channel-topic-rooms.md): rooms.binding.decideTimeoutMin 已随首触接待删除 —— 同样忽略不拒启动, warn 一次。
|
|
144
|
+
if ("decideTimeoutMin" in (cfg.rooms?.binding ?? {}))
|
|
145
|
+
console.warn("[wezard] 配置里还有已废弃的 rooms.binding.decideTimeoutMin (频道帖子每帖一个 room, 没有首触判定, 忽略)");
|
|
132
146
|
const log = makeLogger({
|
|
133
147
|
logFile: cfg.daemon.logFile,
|
|
134
148
|
logLevel: cfg.daemon.logLevel,
|
|
135
149
|
name: "wezard-daemon",
|
|
150
|
+
rotate: { maxBytes: cfg.daemon.logMaxMb * 1048576, keep: cfg.daemon.logKeep },
|
|
136
151
|
});
|
|
137
152
|
log.info({ sourcePath, pid: process.pid }, "daemon start");
|
|
138
153
|
// 定时调度器的 `inject` 真正实现, 赋值在 mirror-mode 的大块里 (要用到那里面的
|
|
139
154
|
// wizards / m / notifyChat), 但 startScheduler 在那块外面接线 —— 见文件尾。
|
|
140
155
|
// 记忆整理者的执行体, 同样只有 mirror 模式给得出 —— 赋值见 scheduledTaskInject 旁边。
|
|
141
156
|
let stopPlanReminders = () => { };
|
|
142
|
-
//
|
|
143
|
-
// (
|
|
157
|
+
// 频道入站的两条接线 (room 块在下面才立起来, 先留引用): 人话落 room / (频道, 帖子, opk?) → 落哪个 topic room
|
|
158
|
+
// (docs/evolve/channel-topic-rooms.md §3.1)。频道自己没有 room, 「首次见到」只记已知频道名单 (channel.ts)。
|
|
144
159
|
let channelIngest;
|
|
145
|
-
let
|
|
146
|
-
|
|
147
|
-
|
|
160
|
+
let channelRoomFor;
|
|
161
|
+
/** 自己刚发的新帖 post_id (最近 N 个): channel.ts 的 topic_event 命中就不当人话落行 (!asker 之外的双保险)。 */
|
|
162
|
+
const selfPosts = createSelfPostLog();
|
|
163
|
+
/** 入站源解析 (§4.1): 群源已绑 / 频道帖子 (原生 @ 帧) 这句话落哪本账、谁是接待人。恒等路径 = undefined。 */
|
|
148
164
|
let sourceRouteHook;
|
|
149
165
|
let stewardRun;
|
|
150
166
|
let stewardWiring = {};
|
|
@@ -169,8 +185,35 @@ const main = async () => {
|
|
|
169
185
|
// Restore auto-approve windows persisted across daemon restarts —
|
|
170
186
|
// otherwise a `wezard reload` silently drops the user's "10min" choice.
|
|
171
187
|
initAutoWindowPersistence(cfg.daemon.stateDir);
|
|
172
|
-
// rolepage 的频道 / 帖子 kind 与归属读时算 (channel-posts),
|
|
173
|
-
|
|
188
|
+
// rolepage 的频道 / 帖子 kind 与归属读时算 (channel-posts), 不落账本; host = 频道绑的身份 (wrc.channel.steward → 类)。
|
|
189
|
+
// 各 room 现任 host 的身份 (账本里 ord 最小的 wizard → 它的类); roomStore 在后面才建, 建好后接线。
|
|
190
|
+
let roomHostsOfChannel = () => [];
|
|
191
|
+
const hostOfChannel = (topic) => {
|
|
192
|
+
const store = wizardStore();
|
|
193
|
+
const named = (identity, fallback) => ({ identity, name: store?.classes?.get(identity)?.name ?? fallback });
|
|
194
|
+
// ① 频道表绑定 (类名 → 类; 不是类就是普通身份名)。
|
|
195
|
+
const bound = ((cfg.wrc.channel.steward ?? {})[topic] ?? "").trim();
|
|
196
|
+
if (bound) {
|
|
197
|
+
const cls = store?.classes?.byName(bound);
|
|
198
|
+
return { identity: cls?.id ?? bound, name: cls?.name ?? bound };
|
|
199
|
+
}
|
|
200
|
+
// ② 接待口径的有效身份 (chatPolicy 老绑定 / 频道键的默认会话) —— 与实际接待同一判据, 框上不再写「未绑」而 room 里明明有人接待。
|
|
201
|
+
const eff = stewardIdentityOf(cfg, store, "chat:" + topic);
|
|
202
|
+
if (eff)
|
|
203
|
+
return named(eff, store?.all().find((w) => identityOfRec(w) === eff)?.name ?? eff);
|
|
204
|
+
// ③ 表空、接待也没有: 看各 room 现任 host 的类 (只在这里推断 —— 表一写上就以表为准, 不会随 host 换人闪烁); 取最多的那个。
|
|
205
|
+
const tally = new Map();
|
|
206
|
+
for (const h of roomHostsOfChannel(topic))
|
|
207
|
+
tally.set(h.identity, { ...h, n: (tally.get(h.identity)?.n ?? 0) + 1 });
|
|
208
|
+
const top = [...tally.values()].sort((a, b) => b.n - a.n || a.identity.localeCompare(b.identity))[0];
|
|
209
|
+
return top ? { identity: top.identity, name: top.name } : undefined;
|
|
210
|
+
};
|
|
211
|
+
const channelRefWithHost = (room) => {
|
|
212
|
+
const r = channelRefOf(cfg, room);
|
|
213
|
+
const host = r ? hostOfChannel(r.channel) : undefined;
|
|
214
|
+
return r ? { ...r, ...(host ? { host } : {}) } : undefined;
|
|
215
|
+
};
|
|
216
|
+
setChannelRef(channelRefWithHost);
|
|
174
217
|
// Replay tool/approval detail records so reload doesn't lose click-to-detail
|
|
175
218
|
// links from messages already on the user's WeCom timeline.
|
|
176
219
|
initDetailPersistence(cfg.daemon.stateDir, log.child({ mod: "detail" }));
|
|
@@ -237,6 +280,8 @@ const main = async () => {
|
|
|
237
280
|
let roomOfHashHook = () => undefined;
|
|
238
281
|
/** room 泵注入成功的 touch (看门狗活动时钟; 同上, room 块里回填)。 */
|
|
239
282
|
let roomActivityTouch = () => undefined;
|
|
283
|
+
/** 泵投递拿到 gone 后的冷启动 (房间块里回填; 见 coldStartSession)。 */
|
|
284
|
+
let coldStartSession;
|
|
240
285
|
/** 新群引导在 room 模型里的两个接线点 (见 inbound.ts InboundOpts): room 块里回填 —— 只有它持有 hub。 */
|
|
241
286
|
let guideInboundHook;
|
|
242
287
|
let guideSettleHook;
|
|
@@ -332,6 +377,7 @@ const main = async () => {
|
|
|
332
377
|
}
|
|
333
378
|
} }, sourcePath, (w, c) => guardCharter(w, c), { onboarding,
|
|
334
379
|
sourceRoute: (base) => sourceRouteHook?.(base),
|
|
380
|
+
channelRoom: (base) => { const r = postRefOf(cfg, base); return r?.post ? channelRoomFor?.(r.channel, r.post, base) : undefined; },
|
|
335
381
|
guideInbound: (a) => (guideInboundHook ? guideInboundHook(a) : Promise.resolve({ ok: false, reason: "room 接线还没就绪" })),
|
|
336
382
|
guideSettle: (base, bound) => (guideSettleHook ? guideSettleHook(base, bound) : false),
|
|
337
383
|
getNotice: (base) => (getNoticeHook ? getNoticeHook(base) : undefined),
|
|
@@ -339,9 +385,9 @@ const main = async () => {
|
|
|
339
385
|
});
|
|
340
386
|
// 频道(topic)事件层:接在 inbound 之后,让频道消息复用同一套 gate / route / mirror。
|
|
341
387
|
installChannelEvents(ws.client, cfg, log.child({ mod: "channel" }), {
|
|
388
|
+
selfPost: (p) => selfPosts.has(p),
|
|
342
389
|
ingest: (e) => (channelIngest ? channelIngest(e) : log.warn({ room: e.room, msgid: e.msgid }, "channel: room wiring not ready, 人话没落账本")),
|
|
343
|
-
|
|
344
|
-
postTouched: (t, b) => channelPostTouched?.(t, b),
|
|
390
|
+
roomFor: (t, p, opk) => (channelRoomFor ? channelRoomFor(t, p, opk) : topicRoomOf({ cfg, topic: t, post: p, ...(opk ? { opk } : {}), roomOfSource: () => undefined, roomExists: () => false })),
|
|
345
391
|
});
|
|
346
392
|
// approval click → finalize 当前 liveStream, 后续 tool/text 落到 standalone。
|
|
347
393
|
// 规则 2: 用户点击授权那一刻就是"上一段对话"的边界, 截断 stream 让授权后的
|
|
@@ -379,7 +425,13 @@ const main = async () => {
|
|
|
379
425
|
if (linksDead(cfg.daemon.detailPublicBase))
|
|
380
426
|
log.warn({ port: cfg.daemon.port }, "no view listener and no detailPublicBase/detailRemoteBase: chat messages go out without rolepage / detail links");
|
|
381
427
|
};
|
|
382
|
-
|
|
428
|
+
// 主线程被同步重活堵住的证据: 超线 warn (带此刻在跑的路由) + /status.eventLoopLagMs。
|
|
429
|
+
// background = 最近跑过的后台周期任务 (bg-tasks.ts): 11-28 之后的卡顿多半不在路由里, 要能指认到任务。
|
|
430
|
+
bg.setLog(log);
|
|
431
|
+
const loopLag = startLoopLagMonitor({ log, inflight: inflightRoutes, background: (ms) => ({ recent: bg.recent(ms).slice(0, 8), running: bg.running() }) });
|
|
432
|
+
// /status 的 store 规模 / 进程资源 / 后台任务: room 块就绪后换成带账本的完整版 (见那里)。
|
|
433
|
+
const statusExtraRef = { get: () => ({ process: { rssMb: rssMb(), fd: fdCount() ?? null }, backgroundTasks: bg.recent(300_000).slice(0, 10) }) };
|
|
434
|
+
const http = startHttp({ cfg, ws, log, sourcePath, roomStatus: roomStatusRef, onView, loopLag, statusExtra: statusExtraRef });
|
|
383
435
|
// 控制面 socket 绑不上 (活 daemon 在听 / 目录不是自己的 / 路径超长) = 起不来: 报原因后 exit 1,
|
|
384
436
|
// systemd / launchd 重试, 对方退出后自然接手。视图 TCP 监听失败不走这里 (只告警)。
|
|
385
437
|
await http.ready.catch((e) => fatalExit(`control socket: ${e.message}`));
|
|
@@ -452,8 +504,11 @@ const main = async () => {
|
|
|
452
504
|
return;
|
|
453
505
|
}
|
|
454
506
|
const spawnLog = log.child({ mod: "mirror", sub: "spawn-init", target });
|
|
455
|
-
const
|
|
456
|
-
const
|
|
507
|
+
const backendName = backendFor(cfg).name;
|
|
508
|
+
const charter = charterFor(target, { cli: backendName });
|
|
509
|
+
// 手动 init 这条也不能把空 model 留给 CLI 默认 (tclaude 的默认会 400)。
|
|
510
|
+
const spec = newStewardSpec(cfg, target, backendName);
|
|
511
|
+
const r = await spawnTmuxClaude({ cfg, log: spawnLog, windowName: target, systemPrompt: charter, ...spec });
|
|
457
512
|
if (!r.ok) {
|
|
458
513
|
json(res, 500, { ok: false, reason: r.reason });
|
|
459
514
|
return;
|
|
@@ -601,8 +656,10 @@ const main = async () => {
|
|
|
601
656
|
: { ok: false, reason: r.reason, target, runningCwd: set.runningCwd, pendingCwd: set.pendingCwd });
|
|
602
657
|
});
|
|
603
658
|
// 频道换绑 (人 2026-11-23: 「绑定工作区为 cc-wecom」): 频道 = 一条类绑定; 换绑 = 建 / 复用
|
|
604
|
-
// 该目录的管家类 + 写 wrc.channel.steward +
|
|
659
|
+
// 该目录的管家类 + 写 wrc.channel.steward + 该频道每个 topic room 坐上新类的**本 room**
|
|
605
660
|
// 实例 (旧 host 不离开: leave 会把它手上没交代的件全 canceled)。只动这一个频道。
|
|
661
|
+
// 2026-11-27: 频道自己没有 room —— 不再要求频道账本存在, 也不再往频道里留一条系统行 (每帖一行
|
|
662
|
+
// 会变成每个帖子下的评论); 谁换的、换成什么在 charterGuard 的通知与日志里。
|
|
606
663
|
http.register("POST /mirror/channel/rebind", async (req, res) => {
|
|
607
664
|
const body = (await readBody(req));
|
|
608
665
|
const self = resolveSelf(body);
|
|
@@ -611,14 +668,10 @@ const main = async () => {
|
|
|
611
668
|
return;
|
|
612
669
|
}
|
|
613
670
|
const topicId = (body.topicId ?? "").trim();
|
|
614
|
-
// 权限: 频道管家表本来就对 wizard 可写 (config_set 那条), 这里不另设身份闸 ——
|
|
615
|
-
//
|
|
616
|
-
if (!roomState("chat:" + topicId)) {
|
|
617
|
-
json(res, 404, { ok: false, reason: "这个频道还没有 room 账本: " + topicId });
|
|
618
|
-
return;
|
|
619
|
-
}
|
|
671
|
+
// 权限: 频道管家表本来就对 wizard 可写 (config_set 那条), 这里不另设身份闸 —— rebindChannel
|
|
672
|
+
// 自己要求这是个已认出的频道 (见过它的事件 / 管家表里有它)。
|
|
620
673
|
const { r: out, note } = guardCharter(() => rebindChannel({
|
|
621
|
-
cfg, sourcePath, store: wizards, stateOf: roomState,
|
|
674
|
+
cfg, sourcePath, store: wizards, stateOf: roomState, roomIds: roomStore.ids,
|
|
622
675
|
write: (room, ops) => { hub.write(room, ops); },
|
|
623
676
|
topicId, workspace: (body.workspace ?? "").toString(), ...(body.name ? { name: body.name.toString() } : {}),
|
|
624
677
|
}), (r) => r.ok ? { what: "频道 " + r.topicId + " 换绑到 ." + r.className, self, byHuman: true } : undefined);
|
|
@@ -626,21 +679,8 @@ const main = async () => {
|
|
|
626
679
|
json(res, 400, out);
|
|
627
680
|
return;
|
|
628
681
|
}
|
|
629
|
-
//
|
|
630
|
-
|
|
631
|
-
const ownSeat = out.rooms.find((f) => f.room === ownRoom)?.seat ?? "";
|
|
632
|
-
const said = hub.append(ownRoom, { author: DAEMON, kind: "system", origin: "daemon", sys: "rebind",
|
|
633
|
-
text: "[wezard] 本频道的管家已换绑为 ." + out.className + (ownSeat ? " (本 room 的实例 ." + displayName(ownSeat) + ")" : "")
|
|
634
|
-
+ " —— 各 room 的 host 换成本 room 的新实例; 旧 host 仍留在群里, 只是不再是 host" });
|
|
635
|
-
if (!said.ok)
|
|
636
|
-
roomLog.warn({ room: ownRoom, reason: said.reason }, "channel: rebind 系统行被拒");
|
|
637
|
-
// §7 换绑后同钩子补拉: 帖子 host 实例本来就是本 room 的实例, 这里只保证它们在频道成员表里
|
|
638
|
-
// (换绑不动它们; 幂等)。
|
|
639
|
-
backfillChannelMembers();
|
|
640
|
-
// 频道 room 的管家会话先起 (与频道落定同一口子); 帖子 room 的实例等第一次唤醒再冷启动。
|
|
641
|
-
const own = out.rooms.find((f) => f.room === "chat:" + out.topicId);
|
|
642
|
-
if (own?.seat)
|
|
643
|
-
spawnStewardPane(own.seat);
|
|
682
|
+
// 帖子 room 的实例只落记录、不预起 pane: 第一次被唤醒时泵会冷启动它 (每帖一个常驻 pane 会顶到上限);
|
|
683
|
+
// 被 stop_wizard 显式结束过的记录 (endedAt) 不重生 —— 那是人的动作, 照旧报没有会话。
|
|
644
684
|
roomLog.info({ ...out }, "channel: rebind");
|
|
645
685
|
json(res, 200, { ...out, charter: await note });
|
|
646
686
|
});
|
|
@@ -743,7 +783,7 @@ const main = async () => {
|
|
|
743
783
|
};
|
|
744
784
|
/** 以 `self` 的名义往 `dest` 群发一条: 头独占一行; 头怎么写 (群默认 wizard 报不报名) 归 ownHead。 */
|
|
745
785
|
const postAs = (self, dest, text) => notifyChat(dest, headed(ownHead(self), text, "\n\n"));
|
|
746
|
-
/** 同 postAs,
|
|
786
|
+
/** 同 postAs, 但去到的是存档频道 room (chat:<topic_id>) —— 一律发新帖 (send_post)。
|
|
747
787
|
* 频道 / 帖子直连 send_post / send_reply, 绕过 tracker, 署名收尾 (withBubbleFooter) 得自己补。 */
|
|
748
788
|
const postAsTopic = (self, dest, text, media) => {
|
|
749
789
|
const topicId = dest.replace(/^chat:/, "");
|
|
@@ -759,7 +799,7 @@ const main = async () => {
|
|
|
759
799
|
return "";
|
|
760
800
|
return "> 回 " + roomNameOf(src.author) + ": " + text.slice(0, 80) + (text.length > 80 ? "…" : "") + "\n\n";
|
|
761
801
|
};
|
|
762
|
-
/**
|
|
802
|
+
/** 存档频道 room 的回话: 评论回原帖 (re 到带 post 的存量行); 被企微拒回退发新帖, 正文带引用标注。 */
|
|
763
803
|
const postAsChannelReply = (self, dest, post, text, quote, media) => {
|
|
764
804
|
const topicId = dest.replace(/^chat:/, "");
|
|
765
805
|
const full = linkTags(dest, withBubbleFooter(headed(ownHead(self), text, "\n\n"), self));
|
|
@@ -894,7 +934,8 @@ const main = async () => {
|
|
|
894
934
|
const token = randomUUID();
|
|
895
935
|
// 新生的记录一律是**自由 wizard** (临时 worker / 分身): 明确清掉从复用的冷记录上
|
|
896
936
|
// 可能带过来的类归属 —— 克隆一个管家出来是独立的人, 不是那个类的实例。
|
|
897
|
-
|
|
937
|
+
// endedAt 清掉: 复用的冷记录可能被人结束过 —— 这一条重生是新的开始。
|
|
938
|
+
wizards.upsert(target, { name: candidate, spawning: BOOT_ID, birthToken: token, identity: target, ordinal: undefined, endedAt: undefined });
|
|
898
939
|
return { ok: true, target, name: candidate, token };
|
|
899
940
|
};
|
|
900
941
|
const clash = asked ? wizards.byName(asked) : undefined;
|
|
@@ -1268,8 +1309,21 @@ const main = async () => {
|
|
|
1268
1309
|
// (daemon/room-hub.ts), 唤醒按 seen 游标重算, 镜像按 §3a 一条规则。旧的路由 /
|
|
1269
1310
|
// 事件表这一步还并行活着 (B/C 节再拆), 这里只把新面接上。
|
|
1270
1311
|
const roomsDir = roomsDirOf(cfg.daemon.stateDir);
|
|
1271
|
-
const roomStore = openRoomStore(roomsDir
|
|
1312
|
+
const roomStore = openRoomStore(roomsDir, {
|
|
1313
|
+
archiveDir: roomsArchiveDirOf(cfg.daemon.stateDir),
|
|
1314
|
+
log: (msg, extra) => log.info({ mod: "room", ...(extra ?? {}) }, "room-archive: " + msg),
|
|
1315
|
+
});
|
|
1272
1316
|
roomOfHashHook = (h) => roomStore.roomByHash(h);
|
|
1317
|
+
roomHostsOfChannel = (topic) => [...new Set([...topicRoomsOf(cfg, topic, roomStore.ids()), ...postsOfChannel(cfg, topic).filter((b) => roomStore.ids().includes(b))])]
|
|
1318
|
+
.flatMap((r) => {
|
|
1319
|
+
const s = roomState(r);
|
|
1320
|
+
const h = s ? roomHost(s) : undefined;
|
|
1321
|
+
const w = h?.kind === "wizard" ? wizards.byUid(h.id) : undefined;
|
|
1322
|
+
if (!w)
|
|
1323
|
+
return [];
|
|
1324
|
+
const identity = identityOfRec(w);
|
|
1325
|
+
return [{ identity, name: wizardStore()?.classes?.get(identity)?.name ?? w.name }];
|
|
1326
|
+
});
|
|
1273
1327
|
/** 损坏的 room 文件 (RoomBroken) 不挡 boot, 也不参与任何判定 —— 只记一行。 */
|
|
1274
1328
|
const roomState = (id) => {
|
|
1275
1329
|
try {
|
|
@@ -1369,6 +1423,10 @@ const main = async () => {
|
|
|
1369
1423
|
}
|
|
1370
1424
|
if (room.startsWith("adhoc:"))
|
|
1371
1425
|
return memberLabel([...(s?.members.values() ?? [])].map((x) => roomNameOf(x.who))) || room;
|
|
1426
|
+
// topic room: 「频道名 · 帖 xxxxxx」(频道名沿用 chat-name 键 chat:<topic_id>; 没起名用 id 前 8 位)。
|
|
1427
|
+
const tr = parseTopicRoomId(room);
|
|
1428
|
+
if (tr)
|
|
1429
|
+
return topicRoomLabel(tr, channelNameOf(cfg, tr.channel));
|
|
1372
1430
|
return chatNameOf(cfg, room) || room;
|
|
1373
1431
|
};
|
|
1374
1432
|
/** 频道 room 判据: 进程内见过的 topic (事件登记) **或** channel-posts 认识且没有根帖的频道。
|
|
@@ -1569,6 +1627,9 @@ const main = async () => {
|
|
|
1569
1627
|
roomActivityTouch(target); // 注入成功 = 该 wizard 有新事件, 看门狗的 stale 窗口重置
|
|
1570
1628
|
return r.ok ? "ok" : r.uncertain ? "uncertain" : r.gone ? "gone" : "failed";
|
|
1571
1629
|
},
|
|
1630
|
+
// 帖子 / 频道 room 的实例、perceptron 只落记录、不预起 pane: 泵第一次唤醒它时报 gone 时
|
|
1631
|
+
// 在这里冷启动 (该不该起由 coldStartSession 判 —— 被 stop_wizard 显式结束过的不许重生)。
|
|
1632
|
+
coldStart: async (uid, target) => (coldStartSession ? coldStartSession(uid, target) : "declined"),
|
|
1572
1633
|
});
|
|
1573
1634
|
// 外部 agent (CoC) 接入: 每个调用方一间 adhoc room, 请求 = 一条 ask 行, 状态从账本现算。
|
|
1574
1635
|
// 路由只挂在控制面 socket (视图口按规则 410); 口令按调用方一个文件, boot / 配置热载时补齐。
|
|
@@ -1684,7 +1745,7 @@ const main = async () => {
|
|
|
1684
1745
|
});
|
|
1685
1746
|
}));
|
|
1686
1747
|
// 投递失败 / 目标正忙的行没有推游标: 泵自身无定时器, 定期重踢直到贴进去。
|
|
1687
|
-
const roomKickTimer = setInterval(() => void hub.kick(), 30_000);
|
|
1748
|
+
const roomKickTimer = setInterval(() => void bg.track("room-kick", () => hub.kick()), 30_000);
|
|
1688
1749
|
roomKickTimer.unref?.();
|
|
1689
1750
|
// 契约 §7 切换约束: 宪章与 MCP schema 都变了, 活会话必须 /new —— 一次性标记文件,
|
|
1690
1751
|
// boot 存在即把每个绑定标为待 /new。m.chatRoster("") 的 targets 就是全部绑定 (live +
|
|
@@ -1751,7 +1812,7 @@ const main = async () => {
|
|
|
1751
1812
|
if (needsNew.size) {
|
|
1752
1813
|
roomLog.info({ panes: needsNew.size }, "room: 切换标记在, 首次唤醒前先 /new (契约 §7)");
|
|
1753
1814
|
void newSweep();
|
|
1754
|
-
const newRetryTimer = setInterval(() => void newSweep
|
|
1815
|
+
const newRetryTimer = setInterval(() => void bg.track("room-new-sweep", newSweep), 30_000);
|
|
1755
1816
|
newRetryTimer.unref?.();
|
|
1756
1817
|
}
|
|
1757
1818
|
// ── /room/* 的公共件 ─────────────────────────────────────────────────
|
|
@@ -1830,6 +1891,13 @@ const main = async () => {
|
|
|
1830
1891
|
]);
|
|
1831
1892
|
return id;
|
|
1832
1893
|
};
|
|
1894
|
+
/** 「找成员恰好是这几位的 adhoc」的候选: 活的 + 归档的轻状态 (契约 §1a) —— 选中归档的那个,
|
|
1895
|
+
* 随后的写入经 store.get 透明恢复它, 而不是另开一个新 room。 */
|
|
1896
|
+
const liveAndArchivedStates = () => {
|
|
1897
|
+
const live = roomStore.ids().map(roomState).filter((x) => !!x);
|
|
1898
|
+
const ids = new Set(live.map((x) => x.id));
|
|
1899
|
+
return [...live, ...roomStore.archivedStates().filter((x) => !ids.has(x.id))];
|
|
1900
|
+
};
|
|
1833
1901
|
/** a 对 b 的两人对话落点: dm 只要还是这两人就用 (有人离开先补回); 已变成多人 room 就不再落进它, 找 / 开一个恰好 {a,b} 的 adhoc。 */
|
|
1834
1902
|
const ensureDmRoom = (a, b) => {
|
|
1835
1903
|
const id = dmRoomId(a, b);
|
|
@@ -1848,7 +1916,7 @@ const main = async () => {
|
|
|
1848
1916
|
hub.write(id, plan.missing.map((u, i) => ({ op: "join", at, room: id, who: { kind: "wizard", id: u }, ord: s.nextOrd + i, via: "invite", by: A })));
|
|
1849
1917
|
}
|
|
1850
1918
|
else if (plan.kind === "pair-adhoc") {
|
|
1851
|
-
return findPairAdhoc(
|
|
1919
|
+
return findPairAdhoc(liveAndArchivedStates(), a, b) ?? openAdhoc(A, [B]);
|
|
1852
1920
|
}
|
|
1853
1921
|
return id;
|
|
1854
1922
|
};
|
|
@@ -1868,7 +1936,7 @@ const main = async () => {
|
|
|
1868
1936
|
// 仅 chat_ask: 多个群外 wizard → 按成员集合复用 / 新开 adhoc (不 invite 进缺省群; interrupt 限权见 room-auto-adhoc.ts)。
|
|
1869
1937
|
if (opts.autoAdhoc && to.length >= 2) {
|
|
1870
1938
|
const r = autoAdhocTarget({
|
|
1871
|
-
states:
|
|
1939
|
+
states: liveAndArchivedStates,
|
|
1872
1940
|
open: (m0, others) => openAdhoc(m0, others),
|
|
1873
1941
|
parentUidOf: (u) => roomWizardOf(u)?.parentUid,
|
|
1874
1942
|
}, me, to, opts.autoAdhoc.interrupt);
|
|
@@ -1899,7 +1967,8 @@ const main = async () => {
|
|
|
1899
1967
|
};
|
|
1900
1968
|
/** 引导化身的发言只许落在本群 room (白名单里的 chat_say / chat_reply)。 */
|
|
1901
1969
|
const guideOutsideRoom = (res, self, room) => {
|
|
1902
|
-
|
|
1970
|
+
// 引导化身 chat:<topic_id>#guide 的「本群」= 该频道的 topic room (2026-11-27: 频道没有 room)。
|
|
1971
|
+
if (!isGuideManifestation(wizards.get(self)) || room === baseOfKey(self) || channelKeyOf(cfg, room) === baseOfKey(self))
|
|
1903
1972
|
return false;
|
|
1904
1973
|
json(res, 403, { ok: false, reason: "引导会话只在 " + baseOfKey(self) + " 里说话" });
|
|
1905
1974
|
return true;
|
|
@@ -1948,6 +2017,50 @@ const main = async () => {
|
|
|
1948
2017
|
json(res, 400, { ok: false, reason: to.error });
|
|
1949
2018
|
return;
|
|
1950
2019
|
}
|
|
2020
|
+
// 频道 id 是「开新帖」的虚地址 (频道自己没有 room; 旧频道 room 只读存档): 先发帖, 再开 topic room 记这句。
|
|
2021
|
+
// 全 id `chat:<T>` 与 #hash8 / 聊天名指到存档频道 room 同一口径 (后者经 roomResolve 还原成 id)。
|
|
2022
|
+
const channelOfRef = (base) => channelOf(cfg, base);
|
|
2023
|
+
const newPostTopic = newPostTopicOfRef(b.room, (ref) => roomResolve(ref).room, channelOfRef);
|
|
2024
|
+
if (newPostTopic) {
|
|
2025
|
+
const archive = "chat:" + newPostTopic;
|
|
2026
|
+
if (refuseReception(res, "POST /room/say", self, { rooms: [archive] }))
|
|
2027
|
+
return;
|
|
2028
|
+
// 硬门由 channelNewPost 在 send_post **之前**判 (先发后判 = 外发收不回): monitor / 引导化身一律拒;
|
|
2029
|
+
// 其余须是频道 host 类实例或存档 room 成员。
|
|
2030
|
+
const rec = wizards.get(self);
|
|
2031
|
+
const hostIdentity = stewardIdentityOf(cfg, wizardStore(), archive) ?? "";
|
|
2032
|
+
const out = await channelNewPost(newPostTopic, {
|
|
2033
|
+
caller: {
|
|
2034
|
+
monitor: rec?.kind === "monitor",
|
|
2035
|
+
guide: isGuideManifestation(rec),
|
|
2036
|
+
hostClass: !!rec && !!hostIdentity && identityOfRec(rec) === hostIdentity,
|
|
2037
|
+
archiveMember: !!roomState(archive)?.members.has(whoKey(me)),
|
|
2038
|
+
},
|
|
2039
|
+
send: () => sendTopicPostRaw(ws.client, log.child({ mod: "channel" }), newPostTopic, linkTags(archive, withBubbleFooter(headed(ownHead(self), text, "\n\n"), self))),
|
|
2040
|
+
remember: (post) => selfPosts.add(post),
|
|
2041
|
+
ensureRoom: (room) => {
|
|
2042
|
+
// founder = 频道 host 身份在**本 room**的实例 (与人话诞生的帖子 room 同口径); 频道没绑才退成调用方。
|
|
2043
|
+
// 调用方作为普通成员入座, 账本行仍记它为作者。
|
|
2044
|
+
const s0 = roomState(room);
|
|
2045
|
+
const ops = newPostSeatOps(s0, room, s0 ? undefined : roomStewardOf(room, archive), me, Date.now());
|
|
2046
|
+
if (ops.length)
|
|
2047
|
+
hub.write(room, ops);
|
|
2048
|
+
seatChannelRoom(room, archive); // 兜底: 频道 host 类的本 room 实例 (已绑才有; 只落记录不起 pane)
|
|
2049
|
+
},
|
|
2050
|
+
record: (room) => hub.append(room, { author: me, kind: "say", text, origin: "tool" }, {}, { noMirror: true }),
|
|
2051
|
+
logShape: (o) => roomLog.info(o, "channel: send_post 回包形状 (确认 post_id 字段用)"),
|
|
2052
|
+
});
|
|
2053
|
+
if (!out.ok) {
|
|
2054
|
+
json(res, out.status, { ok: false, reason: out.reason });
|
|
2055
|
+
return;
|
|
2056
|
+
}
|
|
2057
|
+
if (!("room" in out)) {
|
|
2058
|
+
json(res, 200, { ok: true, warning: out.warning });
|
|
2059
|
+
return;
|
|
2060
|
+
}
|
|
2061
|
+
roomReply(res, out.verdict, { post: out.post, ...(out.warning ? { warning: out.warning } : {}) });
|
|
2062
|
+
return;
|
|
2063
|
+
}
|
|
1951
2064
|
const target = roomTargetOf(me, to?.who, b.room);
|
|
1952
2065
|
if (target.error || !target.room) {
|
|
1953
2066
|
json(res, target.status ?? 400, { ok: false, reason: target.error ?? target.reason });
|
|
@@ -2218,8 +2331,10 @@ const main = async () => {
|
|
|
2218
2331
|
return;
|
|
2219
2332
|
}
|
|
2220
2333
|
const name = (b.name ?? "").toString().trim().replace(/\s+/g, " ");
|
|
2334
|
+
// name 给了 (哪怕是空串) 就算「给了」: 空串 = 清掉 title, 回落到频道名 / 首条人话缩略 / 聊天名。
|
|
2335
|
+
const nameGiven = b.name !== undefined && b.name !== null;
|
|
2221
2336
|
const noticeGiven = b.notice !== undefined && b.notice !== null;
|
|
2222
|
-
if (!
|
|
2337
|
+
if (!nameGiven && !noticeGiven) {
|
|
2223
2338
|
json(res, 400, { ok: false, reason: "name 与 notice 至少给一个" });
|
|
2224
2339
|
return;
|
|
2225
2340
|
}
|
|
@@ -2233,9 +2348,9 @@ const main = async () => {
|
|
|
2233
2348
|
json(res, nt.status, { ok: false, reason: nt.reason });
|
|
2234
2349
|
return;
|
|
2235
2350
|
}
|
|
2236
|
-
if (name)
|
|
2351
|
+
if (nameGiven && (name || s.title))
|
|
2237
2352
|
hub.write(r.room, [{ op: "name", at: Date.now(), room: r.room, title: name, by: me }]);
|
|
2238
|
-
json(res, 200, { ok: true, room: r.room, ...(
|
|
2353
|
+
json(res, 200, { ok: true, room: r.room, ...(nameGiven ? { name, ...(name ? {} : { cleared: true }) } : {}), ...(nt?.ok ? { notice: nt.notice, changed: nt.changed } : {}) });
|
|
2239
2354
|
});
|
|
2240
2355
|
http.register("POST /room/invite", async (req, res) => {
|
|
2241
2356
|
const { self, body } = await readPeerBody(req);
|
|
@@ -2706,50 +2821,7 @@ const main = async () => {
|
|
|
2706
2821
|
}
|
|
2707
2822
|
roomLog.info({ room, source, by: me.id }, "room: 源已解绑 (回落恒等, lazy)");
|
|
2708
2823
|
json(res, 200, { ok: true, room, source,
|
|
2709
|
-
text: "已解绑 " + source + ": 它的消息回落恒等
|
|
2710
|
-
});
|
|
2711
|
-
// §5.1 出口 3 的显式入口 (room_fork): host 判定「这该是新 room」时立即另起, 不必等超时兜底。
|
|
2712
|
-
// 权限 = 该频道 room 的 host; 幂等判据与兜底同一套 (已绑 / 帖子 room 已在 / 引导期都不动)。
|
|
2713
|
-
http.register("POST /room/fork", async (req, res) => {
|
|
2714
|
-
const { self, body } = await readPeerBody(req);
|
|
2715
|
-
if (READ_ROOM_FAIL(res, self))
|
|
2716
|
-
return;
|
|
2717
|
-
if (refuseMonitor(res, self, "room_fork"))
|
|
2718
|
-
return;
|
|
2719
|
-
if (refuseReception(res, "POST /room/fork", self))
|
|
2720
|
-
return;
|
|
2721
|
-
const me = roomSelfOf(self);
|
|
2722
|
-
if (!me) {
|
|
2723
|
-
json(res, 400, { ok: false, reason: "caller 不在名册上, 没有 uid" });
|
|
2724
|
-
return;
|
|
2725
|
-
}
|
|
2726
|
-
const b = body;
|
|
2727
|
-
const target = roomTargetOf(me, undefined, b.room);
|
|
2728
|
-
if (target.error || !target.room) {
|
|
2729
|
-
json(res, target.status ?? 400, { ok: false, reason: target.error ?? target.reason ?? "room required" });
|
|
2730
|
-
return;
|
|
2731
|
-
}
|
|
2732
|
-
const source = (b.source ?? "").toString().trim() || latestSrcOf(target.room);
|
|
2733
|
-
const v = planFork({ cfg, source, actor: me, stateOf: roomState, roomOfSource: (s) => roomStore.roomOfSource(s) });
|
|
2734
|
-
if (!v.ok) {
|
|
2735
|
-
json(res, v.status, { ok: false, reason: v.reason });
|
|
2736
|
-
return;
|
|
2737
|
-
}
|
|
2738
|
-
let born = false;
|
|
2739
|
-
try {
|
|
2740
|
-
born = birthPostRoom(v.topicId, source, me);
|
|
2741
|
-
}
|
|
2742
|
-
catch (e) {
|
|
2743
|
-
json(res, 500, { ok: false, reason: errText(e) });
|
|
2744
|
-
return;
|
|
2745
|
-
}
|
|
2746
|
-
if (!born) {
|
|
2747
|
-
json(res, 409, { ok: false, reason: "没能另起 (频道还在引导期 / 帖子 room 已在) —— 先完成频道绑定" });
|
|
2748
|
-
return;
|
|
2749
|
-
}
|
|
2750
|
-
roomLog.info({ channel: v.channelRoom, post: source, by: me.id }, "room: 显式另起 (room_fork)");
|
|
2751
|
-
json(res, 200, { ok: true, room: source, channel: v.channelRoom,
|
|
2752
|
-
text: "已另起帖子 room " + source + ": 这个帖子之后的话落它自己的 room, 新 host 已作为普通成员拉进频道 room (频道 host 身份不变)。" });
|
|
2824
|
+
text: "已解绑 " + source + ": 它的消息回落恒等 —— 群源落回它自己的群 room; 频道帖子源下一条消息起按 (频道, 帖子) 落 `topic:<频道>/<帖子>` room (没有就在那一刻诞生, 由该频道 host 身份在本 room 的实例接待)。" });
|
|
2753
2825
|
});
|
|
2754
2826
|
// ── 新群引导的受控绑定 (onboard_bind): 只有引导化身能调 ────────────────
|
|
2755
2827
|
// 引导的唯一动作面: 校验 (create 只建最后一级 / 父目录必须已在 / 必须在 $HOME 下) 与落盘都在
|
|
@@ -2771,10 +2843,12 @@ const main = async () => {
|
|
|
2771
2843
|
return;
|
|
2772
2844
|
}
|
|
2773
2845
|
const { verdict } = plan;
|
|
2774
|
-
const bound = applyOnboarding(wizards, onboarding, base, verdict, (name) => guardCharter(() => bindSteward(cfg, sourcePath, base, name), () => ({ what: verdict.kind === "bind-new" ? "新群引导新建管家 " + name + " (工作区 " + verdict.workspace + ") 并绑到 " + base : "新群引导把 " + name + " 绑为 " + base + " 的管家", byHuman: true })), (t) => identityWorkspaceOf(wizards, t) || ((c) => c.runningCwd || c.defaultCwd)(m.getCwd(t)), plan.name
|
|
2846
|
+
const bound = applyOnboarding(wizards, onboarding, base, verdict, (name) => guardCharter(() => bindSteward(cfg, sourcePath, base, name), () => ({ what: verdict.kind === "bind-new" ? "新群引导新建管家 " + name + " (工作区 " + verdict.workspace + ") 并绑到 " + base : "新群引导把 " + name + " 绑为 " + base + " 的管家", byHuman: true })), (t) => identityWorkspaceOf(wizards, t) || ((c) => c.runningCwd || c.defaultCwd)(m.getCwd(t)), plan.name,
|
|
2847
|
+
// 频道: 座位 = 引导所在的 topic room (频道键不是 room); 群 = base 本身。
|
|
2848
|
+
((g) => (g ? guideRoomsOf(base, g).find((r) => !!postRefOf(cfg, r)?.post) : undefined))(roomSelfOf(self)) ?? base);
|
|
2775
2849
|
roomLog.info({ room: base, ...bound, roomName: plan.roomName ?? "" }, "onboarding: steward bound (guide tool)");
|
|
2776
2850
|
const handed = guideSettleRoom(base, bound, plan.roomName);
|
|
2777
|
-
settleBoundChannel(base
|
|
2851
|
+
settleBoundChannel(base);
|
|
2778
2852
|
if (!handed)
|
|
2779
2853
|
notifyChat(base, renderOnboardingDone(bound)); // 引导不在 room 里 (老流程): 至少回报一句
|
|
2780
2854
|
void reapGuideAfterTurn(self); // 先回成功: 这一轮的话还要说完, 收尸在轮终之后 (或 60s)
|
|
@@ -2856,7 +2930,7 @@ const main = async () => {
|
|
|
2856
2930
|
catch { /* 目录还没有 = 0 字节 */ }
|
|
2857
2931
|
};
|
|
2858
2932
|
roomsGuard();
|
|
2859
|
-
const roomsGuardTimer = setInterval(roomsGuard, 24 * 3600_000);
|
|
2933
|
+
const roomsGuardTimer = setInterval(bg.wrap("rooms-guard", roomsGuard), 24 * 3600_000);
|
|
2860
2934
|
roomsGuardTimer.unref?.();
|
|
2861
2935
|
// ── B: 接入 (人话 / trigger / 轮界 / 卡片) ────────────────────────────
|
|
2862
2936
|
/** 绑定 room 不存在时开出来 (契约 §4): 本聊天的管家作 founder; 解析不出管家
|
|
@@ -2865,7 +2939,7 @@ const main = async () => {
|
|
|
2865
2939
|
if (roomState(room))
|
|
2866
2940
|
return room;
|
|
2867
2941
|
const at = Date.now();
|
|
2868
|
-
const kind = room.startsWith("user:") ? "wecom-dm" : room.startsWith("chat:wx") ? "wx" : "wecom-group";
|
|
2942
|
+
const kind = isTopicRoomId(room) ? "topic-post" : room.startsWith("user:") ? "wecom-dm" : room.startsWith("chat:wx") ? "wx" : "wecom-group";
|
|
2869
2943
|
const ops = [{ op: "open", at, room, kind, by: DAEMON }];
|
|
2870
2944
|
let founder;
|
|
2871
2945
|
try {
|
|
@@ -2912,17 +2986,20 @@ const main = async () => {
|
|
|
2912
2986
|
return;
|
|
2913
2987
|
if (needsOnboarding(cfg, wizardStore(), room))
|
|
2914
2988
|
return;
|
|
2915
|
-
const
|
|
2916
|
-
if (
|
|
2989
|
+
const channelKey = channelKeyOf(cfg, room);
|
|
2990
|
+
if (channelKey && !channelMonitorWanted(cfg, wizardStore(), channelKey))
|
|
2917
2991
|
return;
|
|
2918
2992
|
if (!perceptronCandidates(st0).length)
|
|
2919
2993
|
return;
|
|
2920
|
-
|
|
2994
|
+
// 粒度 (docs/evolve/channel-topic-rooms.md §4 / §9-① A): 频道帖子 room 共用**一个频道一个** perceptron
|
|
2995
|
+
// (`chat:<topic_id>#monitor`, 入座该频道每个 topic room) —— 身份数与冷启动数不随帖子线性涨; 其余 room 仍各一个。
|
|
2996
|
+
// room_activate 按 re 的消息 id 定 room, 共用一个身份不串账。
|
|
2997
|
+
const target = keyOf(channelKey || baseOfKey(room), "monitor");
|
|
2921
2998
|
const rec = wizards.get(target);
|
|
2922
2999
|
wizards.upsert(target, {
|
|
2923
3000
|
kind: "monitor",
|
|
2924
3001
|
...(rec ? {} : { bornAt: Date.now(), identity: target }),
|
|
2925
|
-
description: "本 room 的 perceptron: 读账本, 结合成员职责判断最后一条人话该由谁回应 (room_activate)",
|
|
3002
|
+
description: channelKey ? "频道的 perceptron: 坐在该频道每个帖子 room 里, 读账本, 结合成员职责判断各 room 最后一条人话该由谁回应 (room_activate)" : "本 room 的 perceptron: 读账本, 结合成员职责判断最后一条人话该由谁回应 (room_activate)",
|
|
2926
3003
|
parent: undefined,
|
|
2927
3004
|
lead: undefined,
|
|
2928
3005
|
leadOf: undefined,
|
|
@@ -2935,50 +3012,50 @@ const main = async () => {
|
|
|
2935
3012
|
hub.write(room, [{ op: "join", at: Date.now(), room, who: { kind: "wizard", id: uid }, ord: st.nextOrd, via: "invite", by: DAEMON, role: "monitor" }]);
|
|
2936
3013
|
roomLog.info({ target, room }, "perceptron: 建 room perceptron (懒建, 首次唤醒冷启动)");
|
|
2937
3014
|
};
|
|
2938
|
-
/**
|
|
2939
|
-
*
|
|
2940
|
-
*
|
|
2941
|
-
const
|
|
2942
|
-
const
|
|
2943
|
-
|
|
2944
|
-
|
|
2945
|
-
|
|
2946
|
-
const
|
|
2947
|
-
|
|
2948
|
-
|
|
2949
|
-
|
|
2950
|
-
const uid = stw.fresh ? undefined : wizards.get(stw.target)?.uid;
|
|
2951
|
-
if (uid)
|
|
2952
|
-
ops.push({ op: "join", at, room, who: { kind: "wizard", id: uid }, ord: 1, via: "founder", by: DAEMON });
|
|
2953
|
-
}
|
|
2954
|
-
catch { /* 没绑定: 空频道 room, 引导 (或绑定后的管家) 会进来 */ }
|
|
2955
|
-
hub.write(room, ops);
|
|
3015
|
+
/** topic room 不存在就开一个 (docs/evolve/channel-topic-rooms.md §3.1): 频道已绑 host 身份就让它在
|
|
3016
|
+
* **本 room** 的实例作 founder (只落记录, 不起 pane —— 首次唤醒由泵冷启动); 没绑 (引导期) 只开 room,
|
|
3017
|
+
* 人话交引导, 落定时补 host。已存在的 room 里没有 host 而频道已绑 → 顺手补座 (自愈), 幂等。 */
|
|
3018
|
+
const ensureTopicRoom = (room) => {
|
|
3019
|
+
const key = channelKeyOf(cfg, room);
|
|
3020
|
+
const wanted = !!key && channelMonitorWanted(cfg, wizardStore(), key);
|
|
3021
|
+
const s = roomState(room);
|
|
3022
|
+
if (!s) {
|
|
3023
|
+
const founder = wanted ? roomStewardOf(room, key) : undefined;
|
|
3024
|
+
hub.write(room, topicRoomBirthOps(room, founder, Date.now()));
|
|
3025
|
+
roomLog.info({ room, channel: key, founder: founder?.id ?? "" }, "channel: topic room 诞生");
|
|
3026
|
+
return;
|
|
2956
3027
|
}
|
|
2957
|
-
|
|
3028
|
+
if (wanted && !roomHost(s))
|
|
3029
|
+
seatChannelRoom(room, key);
|
|
2958
3030
|
};
|
|
2959
|
-
/**
|
|
2960
|
-
|
|
2961
|
-
|
|
3031
|
+
/** 事件 → 落哪个 topic room (§3.1): 索引 / 账本现取, 纯函数在 channel-posts.ts。 */
|
|
3032
|
+
channelRoomFor = (topicId, postId, opk) => topicRoomOf({
|
|
3033
|
+
cfg, topic: topicId, post: postId, ...(opk ? { opk } : {}),
|
|
3034
|
+
roomOfSource: (src) => roomStore.roomOfSource(src), roomExists: (r) => !!roomState(r),
|
|
3035
|
+
roomKind: (r) => { const s = roomState(r); return s ? roomKindOf(s) : undefined; },
|
|
3036
|
+
});
|
|
3037
|
+
/** 频道引导期: 引导化身入座人说话的 topic room 并接住这条人话 (人话落那个 room, 一个频道一条引导可同时
|
|
3038
|
+
* 住多个 topic room)。与群引导的 guideTakeover 同形, 只是没有企微占位气泡 (topic room 的出站是评论)。 */
|
|
2962
3039
|
const takeChannelGuide = (turn) => {
|
|
2963
3040
|
const rec = wizards.get(turn.guide);
|
|
2964
3041
|
if (!rec?.uid)
|
|
2965
3042
|
return { ok: false, reason: "引导会话不在名册上" };
|
|
2966
3043
|
const at = Date.now();
|
|
2967
|
-
const s = roomState(turn.
|
|
2968
|
-
// 旧版本给未绑定频道建过
|
|
3044
|
+
const s = roomState(turn.room);
|
|
3045
|
+
// 旧版本给未绑定频道建过 perceptron: 先请它退场, 否则人话只听它的, 引导接不到 (口径①)。
|
|
2969
3046
|
const evict = s ? channelMonitorLeaveOps(s, at) : [];
|
|
2970
3047
|
if (evict.length) {
|
|
2971
|
-
hub.write(turn.
|
|
2972
|
-
roomLog.info({ room: turn.
|
|
3048
|
+
hub.write(turn.room, evict);
|
|
3049
|
+
roomLog.info({ room: turn.room }, "onboarding: 频道引导期请走 monitor");
|
|
2973
3050
|
}
|
|
2974
|
-
const join = channelGuideJoinOps(roomState(turn.
|
|
3051
|
+
const join = channelGuideJoinOps(roomState(turn.room), turn.room, { kind: "wizard", id: rec.uid }, at);
|
|
2975
3052
|
if (join.length)
|
|
2976
|
-
hub.write(turn.
|
|
2977
|
-
const v = hub.append(turn.
|
|
3053
|
+
hub.write(turn.room, join);
|
|
3054
|
+
const v = hub.append(turn.room, turn.human);
|
|
2978
3055
|
return v.ok ? { ok: true } : { ok: false, reason: v.reason };
|
|
2979
3056
|
};
|
|
2980
3057
|
const channelGuideSpawning = new Set();
|
|
2981
|
-
/** 未绑定频道的人话: 起 (或续) 引导化身,
|
|
3058
|
+
/** 未绑定频道的人话: 起 (或续) 引导化身, 人话落它说话的 topic room 交给它。会话冷启动在后台做 ——
|
|
2982
3059
|
* 人话先落账 (起 pane 慢不能丢话); 出生窗口里贴不进去 (还没绑定), 泵会退成可重试,
|
|
2983
3060
|
* 起来后这里踢一脚泵立刻投, 不会写成「没有会话 (已被结束)」。 */
|
|
2984
3061
|
const channelGuideTurn = (turn) => {
|
|
@@ -2987,7 +3064,7 @@ const main = async () => {
|
|
|
2987
3064
|
return;
|
|
2988
3065
|
if (!store.get(turn.guide)) {
|
|
2989
3066
|
store.upsert(turn.guide, { identity: turn.guide, kind: "worker", description: GUIDE_DESC, workspace: expandHome(cfg.wrc.cwd) });
|
|
2990
|
-
roomLog.info({ room: turn.
|
|
3067
|
+
roomLog.info({ room: turn.room, guide: turn.guide }, "onboarding: 频道引导化身落记录");
|
|
2991
3068
|
}
|
|
2992
3069
|
if (!m.hasMirrorTarget(turn.guide) && !channelGuideSpawning.has(turn.guide)) {
|
|
2993
3070
|
channelGuideSpawning.add(turn.guide);
|
|
@@ -3006,18 +3083,19 @@ const main = async () => {
|
|
|
3006
3083
|
}
|
|
3007
3084
|
const r = takeChannelGuide(turn);
|
|
3008
3085
|
if (!r.ok)
|
|
3009
|
-
roomLog.warn({ room: turn.
|
|
3086
|
+
roomLog.warn({ room: turn.room, guide: turn.guide, reason: r.reason }, "onboarding: 频道引导没接住这条人话");
|
|
3010
3087
|
};
|
|
3011
3088
|
/** 频道已绑定而引导化身还挂着 (人手改 config / 上个进程死在半路): 收尸 —— 与群 guideGate 开头同款。 */
|
|
3012
|
-
const reapStaleChannelGuide = (
|
|
3013
|
-
const guide = guideOf(wizards,
|
|
3089
|
+
const reapStaleChannelGuide = (channelKey) => {
|
|
3090
|
+
const guide = guideOf(wizards, channelKey);
|
|
3014
3091
|
if (!guide)
|
|
3015
3092
|
return;
|
|
3016
|
-
roomLog.info({ room:
|
|
3093
|
+
roomLog.info({ room: channelKey, guide }, "onboarding: 频道已绑定, 收掉遗留的引导化身");
|
|
3017
3094
|
void m.killPane(guide).catch(() => undefined).then(() => { wizardStore()?.drop(guide); });
|
|
3018
3095
|
};
|
|
3019
|
-
/** 人话落 room:
|
|
3020
|
-
* 未绑定频道先过引导 (
|
|
3096
|
+
/** 人话落 room: 事件已经由 channel.ts 的 topicRoomOf 定好落点 (e.room), 这里保证 room 存在再落行。
|
|
3097
|
+
* 未绑定频道先过引导 (口径②): 引导接一切人话, 绑定后才轮到 perceptron / host。行不带 post / src
|
|
3098
|
+
* —— room 自己就是那个帖子。 */
|
|
3021
3099
|
channelIngest = (e) => {
|
|
3022
3100
|
// 帖 / 评论带的图与文件: 与群聊一个口径 —— 图片以 `@path` 随行 (pane 里 CLI 直接 Read),
|
|
3023
3101
|
// 文件给一行路径; 账本行同时记 files (rolepage 显示 📎, room_read 可查)。
|
|
@@ -3044,46 +3122,40 @@ const main = async () => {
|
|
|
3044
3122
|
void m.newSession(target, settleName(store, chatNameOf(cfg, target), target) || target, { silent: true, ...(cwd ? { cwd } : {}) })
|
|
3045
3123
|
.catch(() => undefined);
|
|
3046
3124
|
},
|
|
3047
|
-
}, { author: e.author, text, files: mediaFiles, src: e.room
|
|
3125
|
+
}, { author: e.author, text, files: mediaFiles, src: e.room });
|
|
3048
3126
|
if (me) {
|
|
3049
3127
|
if (!me.ok)
|
|
3050
3128
|
roomLog.warn({ room: meRoomId(e.author), src: e.room, msgid: e.msgid, reason: me.reason }, "channel: .me 人话落行被拒");
|
|
3051
3129
|
return;
|
|
3052
3130
|
}
|
|
3053
|
-
|
|
3054
|
-
|
|
3055
|
-
|
|
3056
|
-
|
|
3057
|
-
if (turn) {
|
|
3058
|
-
channelGuideTurn(turn);
|
|
3059
|
-
return;
|
|
3060
|
-
}
|
|
3131
|
+
const turn = planChannelGuideTurn({ cfg, store: wizardStore(), onboarding, room: e.room }, e);
|
|
3132
|
+
if (turn) {
|
|
3133
|
+
channelGuideTurn(turn);
|
|
3134
|
+
return;
|
|
3061
3135
|
}
|
|
3062
|
-
const
|
|
3063
|
-
if (
|
|
3064
|
-
onboarding.finish(
|
|
3065
|
-
reapStaleChannelGuide(
|
|
3136
|
+
const key = channelKeyOf(cfg, e.room);
|
|
3137
|
+
if (key) {
|
|
3138
|
+
onboarding.finish(key);
|
|
3139
|
+
reapStaleChannelGuide(key);
|
|
3066
3140
|
}
|
|
3067
|
-
|
|
3068
|
-
|
|
3069
|
-
|
|
3070
|
-
|
|
3071
|
-
if (!roomState(room)) {
|
|
3072
|
-
roomLog.warn({ room, src: e.room, msgid: e.msgid }, "channel: room 不存在, 人话没落账本 (自愈: 下一条事件重建)");
|
|
3141
|
+
if (isTopicRoomId(e.room))
|
|
3142
|
+
ensureTopicRoom(e.room);
|
|
3143
|
+
if (!roomState(e.room)) {
|
|
3144
|
+
roomLog.warn({ room: e.room, msgid: e.msgid }, "channel: room 不存在, 人话没落账本 (自愈: 下一条事件重建)");
|
|
3073
3145
|
return;
|
|
3074
3146
|
}
|
|
3075
|
-
const v = hub.append(room, {
|
|
3147
|
+
const v = hub.append(e.room, {
|
|
3076
3148
|
author: { kind: "human", id: e.author }, kind: "say", text, origin: "inbound",
|
|
3077
|
-
...(e.
|
|
3078
|
-
...(src ? { src } : {}), ...(mediaFiles.length ? { files: mediaFiles } : {}),
|
|
3149
|
+
...(e.mention ? { mention: e.mention } : {}), ...(mediaFiles.length ? { files: mediaFiles } : {}),
|
|
3079
3150
|
});
|
|
3080
3151
|
if (!v.ok)
|
|
3081
|
-
roomLog.warn({ room
|
|
3152
|
+
roomLog.warn({ room: e.room, msgid: e.msgid, reason: v.reason }, "channel: 人话落行被拒");
|
|
3082
3153
|
};
|
|
3083
|
-
/** §4.1 入站源解析 (inbound 的 resolve / send 用): base 是入站发生地 (群 / 帖子群
|
|
3084
|
-
* -
|
|
3085
|
-
*
|
|
3086
|
-
*
|
|
3154
|
+
/** §4.1 入站源解析 (inbound 的 resolve / send 用): base 是入站发生地 (群 / 帖子群)。
|
|
3155
|
+
* - 频道帖子的原生 @ 帧 (base = 帖子自己的 chat:opk…, 配上对了): 落 topicRoomOf 定的 topic room
|
|
3156
|
+
* (room 不在就开), 接待 = 该 room 的 host; 行不带 src / post。频道还在引导期 → undefined,
|
|
3157
|
+
* 交 inbound 的频道引导 (guideGate);
|
|
3158
|
+
* - 源已绑进 room R (群源, 或存量的帖子源 bind) → 落 R, 接待 = R 的 host (不是源自己的类绑定化身);
|
|
3087
3159
|
* - 普通群 / 恒等路径 → undefined (现行为, stewardReception)。
|
|
3088
3160
|
* host 必须是 wizard 且还在名册上; 解析不出就回落恒等 (主流程不因绑定出错)。 */
|
|
3089
3161
|
sourceRouteHook = (base) => {
|
|
@@ -3091,26 +3163,27 @@ const main = async () => {
|
|
|
3091
3163
|
return undefined;
|
|
3092
3164
|
const bound = roomStore.roomOfSource(base);
|
|
3093
3165
|
const ref = postRefOf(cfg, base);
|
|
3094
|
-
const
|
|
3095
|
-
|
|
3096
|
-
|
|
3097
|
-
|
|
3098
|
-
|
|
3099
|
-
|
|
3100
|
-
|
|
3101
|
-
|
|
3102
|
-
|
|
3166
|
+
const hostTarget = (room) => {
|
|
3167
|
+
const st = roomState(room);
|
|
3168
|
+
const host = st ? roomHost(st) : undefined;
|
|
3169
|
+
return host?.kind === "wizard" ? roomWizardOf(host.id)?.target : undefined;
|
|
3170
|
+
};
|
|
3171
|
+
if (bound) {
|
|
3172
|
+
const target = hostTarget(bound);
|
|
3173
|
+
if (!target)
|
|
3174
|
+
return undefined;
|
|
3175
|
+
return { room: bound, target, ...(bound !== base ? { src: base } : {}), ...(ref?.post ? { post: ref.post } : {}) };
|
|
3176
|
+
}
|
|
3177
|
+
if (!ref?.post)
|
|
3103
3178
|
return undefined;
|
|
3104
|
-
const
|
|
3105
|
-
|
|
3106
|
-
|
|
3107
|
-
|
|
3108
|
-
|
|
3109
|
-
|
|
3110
|
-
|
|
3111
|
-
|
|
3112
|
-
const channelRoom = ensureChannelRoom(topicId);
|
|
3113
|
-
roomLog.info({ room: postBase, channel: channelRoom }, "channel: 帖子源首触 (落频道 room 交 host 判定, 不建帖子 room)");
|
|
3179
|
+
const key = "chat:" + ref.channel;
|
|
3180
|
+
if (!channelMonitorWanted(cfg, wizardStore(), key))
|
|
3181
|
+
return undefined; // 引导期: 人话归引导
|
|
3182
|
+
const room = channelRoomFor(ref.channel, ref.post, base);
|
|
3183
|
+
if (isTopicRoomId(room))
|
|
3184
|
+
ensureTopicRoom(room);
|
|
3185
|
+
const target = hostTarget(room);
|
|
3186
|
+
return target ? { room, target } : undefined;
|
|
3114
3187
|
};
|
|
3115
3188
|
/** 定时任务 / plan 提醒的一枪 (cutmap G-1/G-2): kind:"trigger" 行 —— 不镜像, 只唤醒 owner。 */
|
|
3116
3189
|
const fireTaskTrigger = (target, text, ext) => {
|
|
@@ -3138,7 +3211,8 @@ const main = async () => {
|
|
|
3138
3211
|
},
|
|
3139
3212
|
wizardOf: (uid) => {
|
|
3140
3213
|
const w = roomWizardOf(uid);
|
|
3141
|
-
|
|
3214
|
+
// 只在有活 attach 时交出 pane id: reap / sleep 后 store 里的旧 id 不是「意外消失」, 是睡着 (冷)。
|
|
3215
|
+
return w ? { target: w.target, name: w.name, paneId: watchedPaneOf(m.hasAttach(w.target), m.sessionInfo(w.target)?.tmuxPane) } : undefined;
|
|
3142
3216
|
},
|
|
3143
3217
|
isBusy: (target) => m.isBusy(target),
|
|
3144
3218
|
rooms: roomStore.ids,
|
|
@@ -3172,9 +3246,114 @@ const main = async () => {
|
|
|
3172
3246
|
}, 0),
|
|
3173
3247
|
watchdog: roomWatchdog.status(),
|
|
3174
3248
|
});
|
|
3249
|
+
// /status 的 store 规模 + 进程资源 + 后台任务耗时, 与每 5 分钟一行的趋势 (<stateDir>/metrics.jsonl) 同一份读数。
|
|
3250
|
+
// 账本 / 文件大小只在 10s 缓存里重算; tmux pane 数由后台任务每分钟异步取一次 —— /status 里绝不同步 spawn tmux。
|
|
3251
|
+
const stateDirAbs = expandHome(cfg.daemon.stateDir);
|
|
3252
|
+
const paneCensus = createPaneCensus(() => runTmux(["list-panes", "-a", "-F", "#{pane_current_command}"]));
|
|
3253
|
+
const sizesNow = memo(10_000, () => storeSizes({
|
|
3254
|
+
roomsDir,
|
|
3255
|
+
archived: () => roomStore.archived().values(),
|
|
3256
|
+
wizards: () => new Set(wizards.all().map((w) => w.identity || w.target)).size,
|
|
3257
|
+
files: {
|
|
3258
|
+
"details.jsonl": join(stateDirAbs, "details.jsonl"),
|
|
3259
|
+
"mirror-attachments.json": expandHome(cfg.wrc.mirror.attachmentsFile),
|
|
3260
|
+
"wizards.json": expandHome(cfg.wrc.mirror.wizardsFile),
|
|
3261
|
+
"daemon.log": expandHome(cfg.daemon.logFile),
|
|
3262
|
+
},
|
|
3263
|
+
}));
|
|
3264
|
+
statusExtraRef.get = () => ({
|
|
3265
|
+
process: { rssMb: rssMb(), fd: fdCount() ?? null, pid: process.pid },
|
|
3266
|
+
store: sizesNow(),
|
|
3267
|
+
panes: paneCensus.get() ?? null,
|
|
3268
|
+
backgroundTasks: bg.recent(300_000).slice(0, 10),
|
|
3269
|
+
});
|
|
3270
|
+
const paneCensusTimer = setInterval(() => void bg.track("pane-census", () => paneCensus.refresh()), 60_000);
|
|
3271
|
+
paneCensusTimer.unref?.();
|
|
3272
|
+
startMetricsSampler({
|
|
3273
|
+
file: join(stateDirAbs, "metrics.jsonl"),
|
|
3274
|
+
loopLag, sizes: sizesNow, census: paneCensus, latency: toolLatency, bg,
|
|
3275
|
+
warn: (f, msg) => log.warn(f, msg),
|
|
3276
|
+
});
|
|
3175
3277
|
// pump 的注入也算「最后一次事件」: 正在投递的 wizard 不进 stale 名单 (paste 端口的 touch 见 hub ports)。
|
|
3176
|
-
const watchdogTimer = setInterval(() => void roomWatchdog.scan(), (cfg.rooms?.watchdog?.intervalSec ?? 60) * 1000);
|
|
3278
|
+
const watchdogTimer = setInterval(() => void bg.track("room-watchdog", () => roomWatchdog.scan()), (cfg.rooms?.watchdog?.intervalSec ?? 60) * 1000);
|
|
3177
3279
|
watchdogTimer.unref?.();
|
|
3280
|
+
// ── 冷 room 归档 (契约 §1a): 搭看门狗节拍, 每 scanMin 分钟至多一轮, 每轮 ≤ perScan 个, 逐个 await ──
|
|
3281
|
+
// 判定 (同步、只读内存 + stat) 很便宜; 读 / 压 / 写 gz 都是异步的, 一个 room 一个 room 来, 不堵事件循环。
|
|
3282
|
+
const archiveLog = log.child({ mod: "room-archive" });
|
|
3283
|
+
let archiveRunning = false;
|
|
3284
|
+
let archiveLastAt = Date.now(); // boot 后先等满一个 scanMin: 刚起来的 daemon 不急着动盘
|
|
3285
|
+
const archiveIdleMs = (days) => Math.max(0, (days ?? cfg.rooms?.archive?.idleDays ?? 30)) * 86_400_000;
|
|
3286
|
+
const archiveRun = async (o = {}) => {
|
|
3287
|
+
const idleMs = archiveIdleMs(o.idleDays);
|
|
3288
|
+
if (idleMs <= 0)
|
|
3289
|
+
return { ok: true, off: true, candidates: 0, bytes: 0, archived: [], skipped: [], list: [] };
|
|
3290
|
+
const all = roomStore.archiveCandidates({ idleMs });
|
|
3291
|
+
const cands = o.ids?.length ? all.filter((c) => o.ids.includes(c.id)) : all;
|
|
3292
|
+
const list = cands.map((c) => ({ id: c.id, size: c.size, lastWriteAt: new Date(c.lastWriteAt).toISOString() }));
|
|
3293
|
+
const bytes = cands.reduce((n, c) => n + c.size, 0);
|
|
3294
|
+
const archived = [];
|
|
3295
|
+
const skipped = [];
|
|
3296
|
+
if (!o.dryRun) {
|
|
3297
|
+
if (archiveRunning)
|
|
3298
|
+
return { ok: false, reason: "上一轮归档还没跑完" };
|
|
3299
|
+
archiveRunning = true;
|
|
3300
|
+
try {
|
|
3301
|
+
for (const c of cands.slice(0, Math.max(1, o.limit ?? cfg.rooms?.archive?.perScan ?? 20))) {
|
|
3302
|
+
const r = await roomStore.archive(c.id, { idleMs });
|
|
3303
|
+
if (r.ok)
|
|
3304
|
+
archived.push(c.id);
|
|
3305
|
+
else
|
|
3306
|
+
skipped.push({ id: c.id, reason: r.reason + (r.detail ? ": " + r.detail : "") });
|
|
3307
|
+
}
|
|
3308
|
+
}
|
|
3309
|
+
finally {
|
|
3310
|
+
archiveRunning = false;
|
|
3311
|
+
}
|
|
3312
|
+
if (archived.length || skipped.length)
|
|
3313
|
+
archiveLog.info({ archived: archived.length, skipped, total: roomStore.archived().size }, "room-archive: 本轮归档");
|
|
3314
|
+
}
|
|
3315
|
+
return { ok: true, off: false, candidates: cands.length, bytes, archived, skipped, list };
|
|
3316
|
+
};
|
|
3317
|
+
const archiveTimer = setInterval(() => {
|
|
3318
|
+
if (archiveRunning || Date.now() - archiveLastAt < (cfg.rooms?.archive?.scanMin ?? 10) * 60_000)
|
|
3319
|
+
return;
|
|
3320
|
+
archiveLastAt = Date.now();
|
|
3321
|
+
void bg.track("room-archive", archiveRun).catch((e) => archiveLog.warn({ err: errText(e) }, "room-archive: 扫描失败 (下轮再试)"));
|
|
3322
|
+
}, (cfg.rooms?.watchdog?.intervalSec ?? 60) * 1000);
|
|
3323
|
+
archiveTimer.unref?.();
|
|
3324
|
+
// 管理入口 (要 daemon 口令; CLI: wezard rooms archive|restore|list)。archive 缺省 dryRun —— 只列不动。
|
|
3325
|
+
http.register("GET /rooms/archive", guarded(async (_req, res) => {
|
|
3326
|
+
const rows = [...roomStore.archived().values()].sort((a, b) => b.archivedAt - a.archivedAt);
|
|
3327
|
+
json(res, 200, {
|
|
3328
|
+
ok: true, count: rows.length, size: rows.reduce((n, e) => n + e.size, 0), gzSize: rows.reduce((n, e) => n + e.gzSize, 0),
|
|
3329
|
+
rooms: rows.map((e) => ({ id: e.id, title: e.title ?? "", members: e.members.map((m) => roomNameOf(m.who)), lines: e.lines, size: e.size, gzSize: e.gzSize,
|
|
3330
|
+
lastWriteAt: new Date(e.lastWriteAt).toISOString(), archivedAt: new Date(e.archivedAt).toISOString() })),
|
|
3331
|
+
});
|
|
3332
|
+
}));
|
|
3333
|
+
http.register("POST /rooms/archive", guarded(async (req, res) => {
|
|
3334
|
+
const b = ((await readBody(req)) ?? {});
|
|
3335
|
+
const num = (x) => (typeof x === "number" && Number.isFinite(x) ? x : typeof x === "string" && x.trim() && Number.isFinite(Number(x)) ? Number(x) : undefined);
|
|
3336
|
+
const ids = idList(b.ids);
|
|
3337
|
+
const r = await archiveRun({ dryRun: b.dryRun !== false, limit: num(b.limit), idleDays: num(b.idleDays), ...(ids.length ? { ids } : {}) });
|
|
3338
|
+
json(res, r.ok ? 200 : 409, { ...r, dryRun: b.dryRun !== false });
|
|
3339
|
+
}));
|
|
3340
|
+
http.register("POST /rooms/restore", guarded(async (req, res) => {
|
|
3341
|
+
const b = ((await readBody(req)) ?? {});
|
|
3342
|
+
const ids = idList(b.ids ?? b.id);
|
|
3343
|
+
if (!ids.length) {
|
|
3344
|
+
json(res, 400, { ok: false, reason: "给 id (或 ids)" });
|
|
3345
|
+
return;
|
|
3346
|
+
}
|
|
3347
|
+
const out = ids.map((id) => {
|
|
3348
|
+
try {
|
|
3349
|
+
return { id, restored: roomStore.restore(id) };
|
|
3350
|
+
}
|
|
3351
|
+
catch (e) {
|
|
3352
|
+
return { id, restored: false, error: errText(e) };
|
|
3353
|
+
}
|
|
3354
|
+
});
|
|
3355
|
+
json(res, 200, { ok: out.every((x) => !("error" in x)), rooms: out });
|
|
3356
|
+
}));
|
|
3178
3357
|
// 起于旧控制面 (TCP) 的 pane: 它们的 MCP 只会得到 410 —— 与看门狗同节拍, 空闲的就地 sleepPane
|
|
3179
3358
|
// (绑定与身份保留, 下一条注入 --resume 用新启动行重起); 忙的等下一拍。argv 里没有旧痕迹的不碰。
|
|
3180
3359
|
const legacyReaper = createLegacyPaneReaper({
|
|
@@ -3189,8 +3368,45 @@ const main = async () => {
|
|
|
3189
3368
|
isBusy: (target) => m.isBusy(target),
|
|
3190
3369
|
sleepPane: (target) => m.sleepPane(target),
|
|
3191
3370
|
});
|
|
3192
|
-
const legacyTimer = setInterval(() => void legacyReaper.scan().catch((e) => log.warn({ err: e.message }, "legacy-panes scan failed")), (cfg.rooms?.watchdog?.intervalSec ?? 60) * 1000);
|
|
3371
|
+
const legacyTimer = setInterval(() => void bg.track("legacy-panes", () => legacyReaper.scan()).catch((e) => log.warn({ err: e.message }, "legacy-panes scan failed")), (cfg.rooms?.watchdog?.intervalSec ?? 60) * 1000);
|
|
3193
3372
|
legacyTimer.unref?.();
|
|
3373
|
+
// 僵尸 pane: earlyoom 杀掉 claude 后留下的、没有任何绑定认领的裸 bash 壳 —— 同节拍, 判据与「宁漏勿错杀」的理由见
|
|
3374
|
+
// daemon/zombie-panes.ts。回收前先追加 <stateDir>/reclaimed-panes.jsonl (可找回索引); 绑定 / 身份 / mirror-bridge 一概不碰。
|
|
3375
|
+
const reclaimedFile = join(expandHome(cfg.daemon.stateDir), "reclaimed-panes.jsonl");
|
|
3376
|
+
const zombieReaper = createZombiePaneReaper({
|
|
3377
|
+
log: log.child({ mod: "zombie-panes" }),
|
|
3378
|
+
mainSession: () => cfg.wrc.tmuxPrefix,
|
|
3379
|
+
idleMs: () => (cfg.rooms?.zombiePanes?.idleMin ?? 360) * 60_000,
|
|
3380
|
+
perScan: () => cfg.rooms?.zombiePanes?.perScan ?? 10,
|
|
3381
|
+
listPanes: async () => {
|
|
3382
|
+
const r = await runTmux(["list-panes", "-a", "-F", PANE_FORMAT]);
|
|
3383
|
+
return r.ok ? { ok: true, panes: parsePaneRows(r.stdout) } : { ok: false, error: r.stderr.slice(0, 200) };
|
|
3384
|
+
},
|
|
3385
|
+
probe: async (pane) => {
|
|
3386
|
+
const r = await runTmux(["display-message", "-p", "-t", pane, PANE_FORMAT]);
|
|
3387
|
+
return r.ok ? parsePaneRows(r.stdout)[0] : undefined;
|
|
3388
|
+
},
|
|
3389
|
+
procs: async () => new Map([...(await procSnapshot())].map(([pid, e]) => [pid, { ppid: e.ppid, cmd: e.cmd }])),
|
|
3390
|
+
// 宁多勿少: 持久绑定 (含内部 key) ∪ 活 attach 此刻的 pane。
|
|
3391
|
+
bindings: () => {
|
|
3392
|
+
const persisted = Object.entries(mirrorStore.all()).map(([target, a]) => ({
|
|
3393
|
+
target, sessionId: a.sessionId, pane: a.tmuxPane, window: a.tmuxWindow, pid: a.tmuxPid, cliPid: a.cliPid,
|
|
3394
|
+
}));
|
|
3395
|
+
const live = m.chatRoster("").flatMap((c) => c.targets).flatMap((target) => {
|
|
3396
|
+
const info = m.sessionInfo(target);
|
|
3397
|
+
return info?.tmuxPane ? [{ target, sessionId: info.sessionId, pane: info.tmuxPane }] : [];
|
|
3398
|
+
});
|
|
3399
|
+
return [...persisted, ...live];
|
|
3400
|
+
},
|
|
3401
|
+
startedAt: procStartedAtMs,
|
|
3402
|
+
record: (r) => appendReclaimed(reclaimedFile, r),
|
|
3403
|
+
killPane: async (pane) => {
|
|
3404
|
+
const r = await runTmux(["kill-pane", "-t", pane]);
|
|
3405
|
+
return r.ok ? { ok: true } : { ok: false, reason: (r.stderr || String(r.code)).slice(0, 200) };
|
|
3406
|
+
},
|
|
3407
|
+
});
|
|
3408
|
+
const zombieTimer = setInterval(() => void bg.track("zombie-panes", () => zombieReaper.scan()).catch((e) => log.warn({ err: e.message }, "zombie-panes scan failed")), (cfg.rooms?.watchdog?.intervalSec ?? 60) * 1000);
|
|
3409
|
+
zombieTimer.unref?.();
|
|
3194
3410
|
// duty 逾期两级提醒: 与看门狗同节拍, 阈值每轮现读 (hot)。处理人忙 (跑着这一轮 / 停在审批框上)
|
|
3195
3411
|
// 就这一轮不催; 下游还有未关 duty 时只催下游 (递归式, 见 shared/room-overdue)。
|
|
3196
3412
|
const overdue = createOverdueScan({
|
|
@@ -3210,7 +3426,7 @@ const main = async () => {
|
|
|
3210
3426
|
},
|
|
3211
3427
|
});
|
|
3212
3428
|
const overdueScan = () => {
|
|
3213
|
-
overdue.scan().catch((e) => roomLog.warn({ err: e.message }, "overdue: 扫描失败"));
|
|
3429
|
+
bg.track("room-overdue", () => overdue.scan()).catch((e) => roomLog.warn({ err: e.message }, "overdue: 扫描失败"));
|
|
3214
3430
|
};
|
|
3215
3431
|
const overdueTimer = setInterval(overdueScan, (cfg.rooms?.watchdog?.intervalSec ?? 60) * 1000);
|
|
3216
3432
|
overdueTimer.unref?.();
|
|
@@ -3223,12 +3439,13 @@ const main = async () => {
|
|
|
3223
3439
|
if (!rec?.uid)
|
|
3224
3440
|
return { ok: false, reason: "引导会话不在名册上" };
|
|
3225
3441
|
const guide = { kind: "wizard", id: rec.uid };
|
|
3226
|
-
|
|
3442
|
+
// 频道原生 @ 帧的引导: 人话落帖子自己的 topic room (a.room), 群引导落群 room (= 引导 key 的 base)。
|
|
3443
|
+
const room = a.room || baseOfKey(a.guide);
|
|
3227
3444
|
const at = Date.now();
|
|
3228
3445
|
const s = roomState(room);
|
|
3229
3446
|
if (!s)
|
|
3230
3447
|
hub.write(room, [
|
|
3231
|
-
{ op: "open", at, room, kind: "wecom-group", by: DAEMON },
|
|
3448
|
+
{ op: "open", at, room, kind: isTopicRoomId(room) ? "topic-post" : "wecom-group", by: DAEMON },
|
|
3232
3449
|
{ op: "join", at, room, who: guide, ord: 1, via: "founder", by: DAEMON },
|
|
3233
3450
|
]);
|
|
3234
3451
|
else if (!s.members.has(whoKey(guide)))
|
|
@@ -3247,11 +3464,32 @@ const main = async () => {
|
|
|
3247
3464
|
roomLog.info({ room, guide: a.guide, msgId: v.row.id }, "onboarding: 人话进了引导 room");
|
|
3248
3465
|
return { ok: true };
|
|
3249
3466
|
};
|
|
3250
|
-
/**
|
|
3251
|
-
*
|
|
3252
|
-
*
|
|
3253
|
-
* 的来源: monitor 唤醒时探活 gone (人 2026-11-23 现场)。 */
|
|
3467
|
+
/** 管家实例的会话: 记录在、绑定没有就起一个 (newSession 返回 = 绑定已落)。返回 false = 已经有
|
|
3468
|
+
* 绑定 / 正在起 (出生窗口), 不重复 spawn。群落定 (guideSettleRoom)、频道落定、boot 兜底与
|
|
3469
|
+
* 泵的首次唤醒冷启动 (coldStartSession) 共用这一个口子。 */
|
|
3254
3470
|
const stewardSpawning = new Set();
|
|
3471
|
+
const ensureStewardSession = async (target) => {
|
|
3472
|
+
if (!target)
|
|
3473
|
+
return false;
|
|
3474
|
+
if (m.hasMirrorTarget(target))
|
|
3475
|
+
return true;
|
|
3476
|
+
if (stewardSpawning.has(target) || channelGuideSpawning.has(target))
|
|
3477
|
+
return false;
|
|
3478
|
+
stewardSpawning.add(target);
|
|
3479
|
+
const name = settleName(wizards, chatNameOf(cfg, target), target) || target;
|
|
3480
|
+
try {
|
|
3481
|
+
const r = await m.newSession(target, name, { silent: true });
|
|
3482
|
+
if (!r.ok) {
|
|
3483
|
+
roomLog.warn({ target, reason: r.reason }, "room: 管家会话起不来");
|
|
3484
|
+
return false;
|
|
3485
|
+
}
|
|
3486
|
+
return true;
|
|
3487
|
+
}
|
|
3488
|
+
finally {
|
|
3489
|
+
stewardSpawning.delete(target);
|
|
3490
|
+
}
|
|
3491
|
+
};
|
|
3492
|
+
/** 落定路径的起 pane: 起上了踢一脚泵 (否则要等 30s 重踢)。 */
|
|
3255
3493
|
const spawnStewardPane = (target) => {
|
|
3256
3494
|
if (!target)
|
|
3257
3495
|
return;
|
|
@@ -3261,132 +3499,118 @@ const main = async () => {
|
|
|
3261
3499
|
}
|
|
3262
3500
|
if (stewardSpawning.has(target) || channelGuideSpawning.has(target))
|
|
3263
3501
|
return;
|
|
3264
|
-
|
|
3265
|
-
|
|
3266
|
-
|
|
3267
|
-
.
|
|
3268
|
-
.catch((e) => roomLog.warn({ target, err: errText(e) }, "room: 管家 pane 起不来 (有唤醒时泵会再试)"))
|
|
3269
|
-
.finally(() => stewardSpawning.delete(target));
|
|
3502
|
+
void ensureStewardSession(target)
|
|
3503
|
+
.then((ok) => { if (ok)
|
|
3504
|
+
hub.kick(); })
|
|
3505
|
+
.catch((e) => roomLog.warn({ target, err: errText(e) }, "room: 管家 pane 起不来 (有唤醒时泵会再试)"));
|
|
3270
3506
|
};
|
|
3271
|
-
/**
|
|
3272
|
-
*
|
|
3273
|
-
|
|
3274
|
-
|
|
3275
|
-
|
|
3276
|
-
|
|
3277
|
-
|
|
3278
|
-
|
|
3279
|
-
|
|
3280
|
-
|
|
3281
|
-
|
|
3282
|
-
|
|
3283
|
-
|
|
3284
|
-
|
|
3285
|
-
|
|
3286
|
-
|
|
3287
|
-
|
|
3288
|
-
|
|
3289
|
-
|
|
3507
|
+
/** 泵投递拿到 gone 后的冷启动 (room-hub 的 coldStart 口子; 帖子 / 频道 room 的实例与 perceptron
|
|
3508
|
+
* 只落记录、不预起 pane, 第一次被唤醒时在这里起会话)。
|
|
3509
|
+
* 只对「**从没**有过会话」的记录做 —— 记录形同一律, 判据只看「有没有过会话的证据」
|
|
3510
|
+
* (见 steward.coldStartVerdict): endedAt (被显式结束) / parent·clonedFrom·forkOf·tier (当年是
|
|
3511
|
+
* spawn 出来的) / 在任何 room 里发过言 / 现在已有绑定, 任一条成立就不替它重生。判据不齐时宁可
|
|
3512
|
+
* 不重生 (误重生 = 白花一次 spawn 并复活一个被人收掉的会话; 漏判只是这一条晚点到, 系统行照旧
|
|
3513
|
+
* 提示人 spawn / 改派)。老记录若被结束过又没有任何记号 (从来没发过言), 判不出来 —— 这之后所有
|
|
3514
|
+
* stop_wizard end 都会写 endedAt。 */
|
|
3515
|
+
coldStartSession = async (uid, target) => {
|
|
3516
|
+
try {
|
|
3517
|
+
const spoke = roomStore.ids().some((r) => {
|
|
3518
|
+
try {
|
|
3519
|
+
return roomState(r)?.msgs.some((m) => m.author.kind === "wizard" && m.author.id === uid) ?? false;
|
|
3520
|
+
}
|
|
3521
|
+
catch {
|
|
3522
|
+
return false;
|
|
3523
|
+
}
|
|
3524
|
+
});
|
|
3525
|
+
const verdict = coldStartVerdict({
|
|
3526
|
+
rec: wizards.get(target), spoke,
|
|
3527
|
+
hasBinding: m.hasMirrorTarget(target),
|
|
3528
|
+
spawning: stewardSpawning.has(target) || channelGuideSpawning.has(target),
|
|
3529
|
+
});
|
|
3530
|
+
if (verdict !== "yes")
|
|
3531
|
+
return verdict;
|
|
3532
|
+
if (!(await ensureStewardSession(target)))
|
|
3533
|
+
return "declined"; // 起不来 (内存闸 / spawn 失败): 照旧报没有会话
|
|
3534
|
+
roomLog.info({ target, uid }, "room: 首次唤醒冷启动 (记录在、会话没有)");
|
|
3535
|
+
return "started";
|
|
3536
|
+
}
|
|
3537
|
+
catch (e) {
|
|
3538
|
+
roomLog.warn({ target, uid, err: errText(e) }, "room: 冷启动失败 (照旧报没有会话)");
|
|
3539
|
+
return "declined";
|
|
3540
|
+
}
|
|
3541
|
+
};
|
|
3542
|
+
/** 引导所在的 room 们 (引导化身是成员的): 群 = [群 room]; 频道键 = 该频道每个 topic room 里引导在座的
|
|
3543
|
+
* (一个频道一条引导可同时住几个 topic room), 加上旧版留下的存档频道 room (若引导还坐在里面)。 */
|
|
3544
|
+
const guideRoomsOf = (base, guide) => {
|
|
3545
|
+
const topic = base === "chat:" + channelOf(cfg, base) ? channelOf(cfg, base) : "";
|
|
3546
|
+
const cands = topic ? [base, ...topicRoomsOf(cfg, topic, roomStore.ids())] : [base];
|
|
3547
|
+
return cands.filter((r) => roomState(r)?.members.has(whoKey(guide)));
|
|
3290
3548
|
};
|
|
3291
|
-
/**
|
|
3292
|
-
*
|
|
3293
|
-
const seatChannelRoom = (room,
|
|
3549
|
+
/** 一个 room 的 host 座位: host 一律是**本 room 的**实例 (人 2026-11-23: 不同的 room 要用不同的
|
|
3550
|
+
* 实例), 没有就领号新开。幂等 —— 落定与 boot 自愈共用。channelKey = 频道键 (群 / 非频道 room 不走它)。 */
|
|
3551
|
+
const seatChannelRoom = (room, channelKey) => {
|
|
3294
3552
|
const s = roomState(room);
|
|
3295
3553
|
if (!s)
|
|
3296
3554
|
return;
|
|
3297
|
-
const who = roomStewardOf(room,
|
|
3555
|
+
const who = roomStewardOf(room, channelKey);
|
|
3298
3556
|
if (who) {
|
|
3299
3557
|
const ops = hostJoinOps(s, who, Date.now());
|
|
3300
3558
|
if (ops.length)
|
|
3301
3559
|
hub.write(room, ops);
|
|
3302
3560
|
}
|
|
3303
3561
|
};
|
|
3304
|
-
/**
|
|
3305
|
-
*
|
|
3306
|
-
*
|
|
3307
|
-
const
|
|
3308
|
-
const
|
|
3309
|
-
|
|
3310
|
-
|
|
3311
|
-
const rooms = [base, ...postsOfChannel(cfg, topicId)];
|
|
3312
|
-
for (const room of rooms)
|
|
3313
|
-
seatChannelRoom(room, base);
|
|
3314
|
-
// 管家实例的 pane: 群落定 (guideSettleRoom) 一直有这一步, 频道这边原来漏了 —— 记录在、
|
|
3315
|
-
// pane 没有, monitor 唤醒就是 gone, 人看到「已被结束」(人 2026-11-23 现场)。
|
|
3316
|
-
// 帖子 room 的实例不预起 pane: 第一次被唤醒时泵会冷启动它 (每个帖子一个常驻 pane 会顶到上限)。
|
|
3317
|
-
spawnStewardPane(bound.target);
|
|
3318
|
-
roomLog.info({ room: base, topicId, steward: bound.target, rooms: rooms.length }, "onboarding: 频道交出管家 (每 room 一个实例 + monitor)");
|
|
3319
|
-
};
|
|
3320
|
-
/** §5.1 出口 3 (另起 / 兜底): 帖子 room 诞生 + 领号新实例, 并把新 host 拉进频道 room。
|
|
3321
|
-
* by = 判定者 (超时兜底时 DAEMON)。幂等: 帖子 room 已在 / 源已绑 / 频道还在引导期 = 什么都不做。
|
|
3322
|
-
* §7: 频道 host (最早加入序) 身份不动 —— 新成员走普通 join (via spawn, ord = nextOrd, watch 关)。 */
|
|
3323
|
-
const birthPostRoom = (topicId, postBase, by) => {
|
|
3324
|
-
if (roomStore.roomOfSource(postBase))
|
|
3562
|
+
/** 引导落定: 管家进 room → 引导名下 duty 全部转给它并唤醒 → 引导离开 → 完成系统行。对引导所在的
|
|
3563
|
+
* **每个** room 做一遍 (群 = 一个; 频道 = 它住过的每个 topic room, 管家各用本 room 的实例)。
|
|
3564
|
+
* false = 引导不在任何 room 里 (老流程 / 没走过 room), 调用方自己回一句。 */
|
|
3565
|
+
const guideSettleRoom = (base, bound, roomName = "") => {
|
|
3566
|
+
const guideTarget = guideOf(wizards, base);
|
|
3567
|
+
const guide = guideTarget ? roomSelfOf(guideTarget) : undefined;
|
|
3568
|
+
if (!guide)
|
|
3325
3569
|
return false;
|
|
3326
|
-
const
|
|
3327
|
-
|
|
3328
|
-
|
|
3329
|
-
|
|
3330
|
-
|
|
3331
|
-
if (
|
|
3332
|
-
hub.write(postBase, postRoomBirthOps(postBase, founder, at));
|
|
3333
|
-
roomLog.info({ room: postBase, channel: channelRoom, founder, by: by.kind + ":" + by.id }, "channel: 帖子 room 诞生 (另起)");
|
|
3334
|
-
}
|
|
3335
|
-
// 新 host 同步进频道 room: 频道 host 从此在成员表里看得到每个帖子 host。
|
|
3336
|
-
const cs = roomState(channelRoom);
|
|
3337
|
-
if (cs && founder) {
|
|
3338
|
-
const who = founder;
|
|
3339
|
-
if (!cs.members.has(whoKey(who)))
|
|
3340
|
-
hub.write(channelRoom, [{ op: "join", at, room: channelRoom, who, ord: cs.nextOrd, via: "spawn", by }]);
|
|
3341
|
-
}
|
|
3342
|
-
return true;
|
|
3343
|
-
};
|
|
3344
|
-
/** §5.1 兜底扫描: 首触落频道 room、host 在 decideTimeoutMin 内没 bind 也没另起 → 自动走出口 3。
|
|
3345
|
-
* 判据全从账本现算 (room-bind.ts 纯函数), 已绑 / 已诞生下一次自然不再命中; overdue 提醒独立运行。 */
|
|
3346
|
-
const decideOnFirstTouch = () => {
|
|
3347
|
-
const timeoutMs = (cfg.rooms?.binding?.decideTimeoutMin ?? 10) * 60_000;
|
|
3348
|
-
let due = [];
|
|
3349
|
-
try {
|
|
3350
|
-
due = pendingFirstTouches({ cfg, states: roomStore.ids().map(roomState).filter((x) => !!x),
|
|
3351
|
-
roomOfSource: (s) => roomStore.roomOfSource(s), stateOf: roomState, now: Date.now(), timeoutMs });
|
|
3352
|
-
}
|
|
3353
|
-
catch (e) {
|
|
3354
|
-
roomLog.warn({ err: errText(e) }, "binding: 首触兜底扫描失败 (下一轮再来)");
|
|
3355
|
-
return;
|
|
3356
|
-
}
|
|
3357
|
-
for (const d of due) {
|
|
3570
|
+
const channelBase = !!channelOf(cfg, base) && base === "chat:" + channelOf(cfg, base);
|
|
3571
|
+
// roomMirror 给 daemon 的行补 "[wezard] " 前缀, 完成确认自己已经带了一个。
|
|
3572
|
+
const text = renderOnboardingDone(bound).replace(/^\[wezard\]\s*/, "");
|
|
3573
|
+
let handed = false;
|
|
3574
|
+
// 频道没有 room 可起名: 人给的名字落成频道名 (wrc.channel.name.<T>), 频道框标题与各帖子 room 的兜底前缀都跟着它。
|
|
3575
|
+
if (channelBase && roomName) {
|
|
3358
3576
|
try {
|
|
3359
|
-
|
|
3360
|
-
roomLog.info({ room: d.source, channel: d.channelRoom, waitedMin: Math.round((Date.now() - d.at) / 60000) }, "binding: 首触超时, 自动另起帖子 room");
|
|
3577
|
+
setChannelName(cfg, sourcePath, channelOf(cfg, base), roomName);
|
|
3361
3578
|
}
|
|
3362
|
-
catch (
|
|
3363
|
-
roomLog.warn({
|
|
3579
|
+
catch (err) {
|
|
3580
|
+
roomLog.warn({ base, err: errText(err) }, "onboarding: 频道名写盘失败");
|
|
3364
3581
|
}
|
|
3365
3582
|
}
|
|
3366
|
-
|
|
3367
|
-
|
|
3368
|
-
|
|
3369
|
-
|
|
3370
|
-
|
|
3371
|
-
|
|
3372
|
-
|
|
3373
|
-
|
|
3374
|
-
|
|
3375
|
-
roomLog.warn({ err: errText(e) }, "binding: 频道成员补拉扫描失败");
|
|
3376
|
-
return;
|
|
3377
|
-
}
|
|
3378
|
-
for (const seat of seats) {
|
|
3379
|
-
const cs = roomState(seat.channelRoom);
|
|
3380
|
-
if (!cs)
|
|
3583
|
+
for (const room of guideRoomsOf(base, guide)) {
|
|
3584
|
+
const s = roomState(room);
|
|
3585
|
+
// 频道: 管家是**本 room** 的实例 (bound.target 只是频道级锚点, 不属于任何 topic room)。
|
|
3586
|
+
const steward = channelBase ? roomStewardOf(room, base) : roomSelfOf(bound.target);
|
|
3587
|
+
if (!s || !steward)
|
|
3588
|
+
continue;
|
|
3589
|
+
// 频道的 roomName 已在上面写成频道名, 不进帖子 room 的 title —— roomName 只给群。
|
|
3590
|
+
const ops = guideHandoffOps(s, { guide, steward, text, now: Date.now(), ...(roomName && !channelBase ? { roomName } : {}) });
|
|
3591
|
+
if (!ops.length)
|
|
3381
3592
|
continue;
|
|
3382
|
-
hub.write(
|
|
3383
|
-
|
|
3593
|
+
hub.write(room, ops);
|
|
3594
|
+
handed = true;
|
|
3595
|
+
const stewardTarget = channelBase ? roomWizardOf(steward.id)?.target ?? "" : bound.target;
|
|
3596
|
+
roomLog.info({ room, guide: guideTarget, steward: stewardTarget, ops: ops.length }, "onboarding: room 交给管家");
|
|
3597
|
+
// 管家会话还没起: 泵贴不进没绑定的 pane —— 先起一个 (与频道落定 / boot 兜底同一口子)。
|
|
3598
|
+
spawnStewardPane(stewardTarget);
|
|
3384
3599
|
}
|
|
3600
|
+
return handed;
|
|
3601
|
+
};
|
|
3602
|
+
/** 绑定落在**频道**上 (wrc.channel.steward): 该频道每个 topic room 各坐**自己那个**实例当 host
|
|
3603
|
+
* (perceptron 照旧每 room 懒建)。引导期这两样都没建, 这里是唯一的补建点 —— 普通群 (channelOf 认不出)
|
|
3604
|
+
* = 无操作。频道自己没有 room, 不要求有存档频道 room; 实例不预起 pane (首次唤醒由泵冷启动)。 */
|
|
3605
|
+
const settleBoundChannel = (base) => {
|
|
3606
|
+
const topicId = channelOf(cfg, base);
|
|
3607
|
+
if (!topicId)
|
|
3608
|
+
return;
|
|
3609
|
+
const rooms = topicRoomsOf(cfg, topicId, roomStore.ids());
|
|
3610
|
+
for (const room of rooms)
|
|
3611
|
+
seatChannelRoom(room, "chat:" + topicId);
|
|
3612
|
+
roomLog.info({ room: base, topicId, rooms: rooms.length }, "onboarding: 频道交出管家 (每个 topic room 一个实例)");
|
|
3385
3613
|
};
|
|
3386
|
-
// 首触兜底与看门狗同节拍 (阈值每轮现读, hot)。boot 先等启动那一波过去再扫一次。
|
|
3387
|
-
const decideTimer = setInterval(decideOnFirstTouch, (cfg.rooms?.watchdog?.intervalSec ?? 60) * 1000);
|
|
3388
|
-
decideTimer.unref?.();
|
|
3389
|
-
setTimeout(decideOnFirstTouch, 30_000).unref?.();
|
|
3390
3614
|
/** 引导收尸 (绑定后): 工具调用已经回成功, 等它这一轮结束 (或 60s 上限) 再 kill + drop ——
|
|
3391
3615
|
* 半路杀 pane 会把这一轮截断在 CLI 里。它已经 leave 过 room, 所以 drop 不会再产生
|
|
3392
3616
|
* canceled 行 (leaveRooms 对非成员是空操作)。 */
|
|
@@ -3400,16 +3624,15 @@ const main = async () => {
|
|
|
3400
3624
|
roomLog.info({ guide, killed: r.ok, reason: r.reason }, "onboarding: guide reaped after bind");
|
|
3401
3625
|
};
|
|
3402
3626
|
guideInboundHook = guideTakeover;
|
|
3403
|
-
// 群引导的落定也走频道补建: base
|
|
3627
|
+
// 群引导的落定也走频道补建: base 是频道键时, 绑定后每个 topic room 补 host (口径③);
|
|
3404
3628
|
// 普通群 channelOf 认不出, settleBoundChannel 无操作。settleBoundChannel 幂等。
|
|
3405
3629
|
guideSettleHook = (base, bound) => {
|
|
3406
3630
|
const ok = guideSettleRoom(base, bound);
|
|
3407
|
-
|
|
3408
|
-
settleBoundChannel(base, bound);
|
|
3631
|
+
settleBoundChannel(base);
|
|
3409
3632
|
return ok;
|
|
3410
3633
|
};
|
|
3411
3634
|
// rolepage 的 room 历史路由 (room-ui 的第 4 个接线点): 坏账本按「没有这个 room」处理。
|
|
3412
|
-
setRoomReader({ ids: roomStore.ids, get: (id) => roomState(id) });
|
|
3635
|
+
setRoomReader({ ids: roomStore.ids, get: (id) => roomState(id), archived: roomStore.archivedStates });
|
|
3413
3636
|
// 回填外层引用 (入站包装在 mirror 块之外)。
|
|
3414
3637
|
roomHub = hub;
|
|
3415
3638
|
roomStateOf = roomState;
|
|
@@ -3489,27 +3712,20 @@ const main = async () => {
|
|
|
3489
3712
|
spawnStewardPane(target);
|
|
3490
3713
|
if (spawn.length)
|
|
3491
3714
|
classLog.info({ spawn }, "steward panes spawned at boot (记录在, pane 没有)");
|
|
3492
|
-
// 已绑定频道的 room 一个 host 都没有 (绑完就崩 / 老数据): 补本 room
|
|
3715
|
+
// 已绑定频道的 topic room 一个 host 都没有 (绑完就崩 / 老数据): 补本 room 的实例。存档频道
|
|
3716
|
+
// room (chat:<topic_id>, 不再收入站) 不补座。
|
|
3493
3717
|
for (const room of roomStore.ids()) {
|
|
3494
|
-
const
|
|
3495
|
-
if (!
|
|
3718
|
+
const ref = postRefOf(cfg, room);
|
|
3719
|
+
if (!ref?.post || !(cfg.wrc.channel.steward ?? {})[ref.channel])
|
|
3496
3720
|
continue;
|
|
3497
3721
|
const s = roomState(room);
|
|
3498
3722
|
if (s && !roomHost(s))
|
|
3499
|
-
seatChannelRoom(room, "chat:" +
|
|
3723
|
+
seatChannelRoom(room, "chat:" + ref.channel);
|
|
3500
3724
|
}
|
|
3501
3725
|
}
|
|
3502
3726
|
catch (e) {
|
|
3503
3727
|
classLog.warn({ err: errText(e) }, "steward instance repair failed (不影响启动)");
|
|
3504
3728
|
}
|
|
3505
|
-
// §7 boot 补拉: 存量帖子 room 的 host 进频道 room (与 settleBoundChannel / channel-rebind 同钩子;
|
|
3506
|
-
// 幂等, 已拉过的不重复; 实例不在册 / 引导期频道跳过)。
|
|
3507
|
-
try {
|
|
3508
|
-
backfillChannelMembers();
|
|
3509
|
-
}
|
|
3510
|
-
catch (e) {
|
|
3511
|
-
classLog.warn({ err: errText(e) }, "binding: 频道成员补拉失败 (不影响启动)");
|
|
3512
|
-
}
|
|
3513
3729
|
// v3 §3: 全局管家身份落位 —— home (defaultChat) 的默认会话就是它的锚点化身。
|
|
3514
3730
|
// 新聊天 (还没有任何会话) 的裸消息由它接待 (inbound stewardRoute); 未认领的新装机不造幽灵记录。
|
|
3515
3731
|
const gs = markGlobalSteward(wizards, cfg.defaultChat);
|
|
@@ -3784,7 +4000,11 @@ const main = async () => {
|
|
|
3784
4000
|
file: x.file,
|
|
3785
4001
|
};
|
|
3786
4002
|
}),
|
|
3787
|
-
chatNames:
|
|
4003
|
+
chatNames: {
|
|
4004
|
+
...Object.fromEntries(listChatNames(cfg).map((c) => [c.base, c.name])),
|
|
4005
|
+
// 频道名表 (wrc.channel.name) 盖过旧标签: 前端 channelName 先读 chatNames['chat:<T>'], svr 也靠它。
|
|
4006
|
+
...Object.fromEntries(Object.entries(cfg.wrc.channel.name ?? {}).filter(([, n]) => n.trim()).map(([t, n]) => [`chat:${t}`, n.trim()])),
|
|
4007
|
+
},
|
|
3788
4008
|
// 微信用户的发话人 id 就是它那个群的 chatId: 名字跟着群名走。
|
|
3789
4009
|
humanNames: Object.fromEntries(wx.list().map((a) => [`human:${a.chatId}`, chatNameOf(cfg, `chat:${a.chatId}`)]).filter(([, n]) => n)),
|
|
3790
4010
|
weixin: wx.list().map((a) => ({
|
|
@@ -3794,11 +4014,13 @@ const main = async () => {
|
|
|
3794
4014
|
// room 账本快照 + 名字表: rolepage 关系图 / room 视图的唯一来源 (room-ui)。
|
|
3795
4015
|
// 坏账本跳过并留日志 —— 一个坏文件不该让整张图消失。
|
|
3796
4016
|
rooms: roomFacts(roomStore, wizards.all(), {
|
|
3797
|
-
chatName: (base) => chatNameOf(cfg, base),
|
|
3798
|
-
channelOf:
|
|
4017
|
+
chatName: (base) => { const tr = parseTopicRoomId(base); return tr ? topicRoomLabel(tr, channelNameOf(cfg, tr.channel)) : channelNameOfBase(cfg, base) || chatNameOf(cfg, base); },
|
|
4018
|
+
channelOf: channelRefWithHost,
|
|
3799
4019
|
onBroken: (room, err) => log.warn({ mod: "room", room, err: errText(err) }, "room-facts: 坏账本跳过"),
|
|
3800
4020
|
}),
|
|
3801
4021
|
names: nameTable(wizards.all()),
|
|
4022
|
+
// 已知频道 (没有 room 的绑定频道也要有一个框): 种子, /api/world 再并上 rooms 里归并出的。
|
|
4023
|
+
channels: knownChannels(cfg).map((id) => ({ id, name: channelNameOf(cfg, id) || "chat:" + id, ...((h) => (h ? { host: h } : {}))(hostOfChannel(id)) })),
|
|
3802
4024
|
classes: classes.all().map((c) => ({ id: c.id, name: c.name, role: c.role, workspace: c.workspace })),
|
|
3803
4025
|
};
|
|
3804
4026
|
};
|
|
@@ -3935,7 +4157,7 @@ const main = async () => {
|
|
|
3935
4157
|
});
|
|
3936
4158
|
// 宪章记录是后来才有的: 已经在跑的 wizard 拿 spawn 落盘的那份 (state/charters/<sid>.md) 补上,
|
|
3937
4159
|
// 否则要等它下次重生, rolepage 的「宪章」入口才出现。与自动命名同一个延迟: 等附着表恢复完。
|
|
3938
|
-
setTimeout(() => {
|
|
4160
|
+
setTimeout(bg.wrap("charter-backfill", () => {
|
|
3939
4161
|
const dir = join(expandHome(cfg.daemon.stateDir), "charters");
|
|
3940
4162
|
wizards.all().forEach((w) => {
|
|
3941
4163
|
const sid = m.sessionInfo(w.target)?.sessionId;
|
|
@@ -3957,7 +4179,7 @@ const main = async () => {
|
|
|
3957
4179
|
}
|
|
3958
4180
|
catch { /* 补不上就等它重生 */ }
|
|
3959
4181
|
});
|
|
3960
|
-
}, 15_000).unref();
|
|
4182
|
+
}), 15_000).unref();
|
|
3961
4183
|
// 家谱只列与观察者同机器人的 (跨机器人的分身生不出来, 这是给老数据 / 手改注册表兜的底)。
|
|
3962
4184
|
const kinOf = (self, all, target) => ({
|
|
3963
4185
|
// v3: 身份/种类随行 —— roster 金字塔的普查按 identity 去重, L0 永远收学徒。
|
|
@@ -4011,7 +4233,9 @@ const main = async () => {
|
|
|
4011
4233
|
alive: p.paneAlive,
|
|
4012
4234
|
self: p.self,
|
|
4013
4235
|
lastActivity: p.lastActivity,
|
|
4014
|
-
|
|
4236
|
+
// 名册一律在 enrich 里换成 lastExchange (按行惰性取), 这里不碰 p.summary: 它会触发
|
|
4237
|
+
// summarizeTail, 而那份摘要在名册里从来用不上。
|
|
4238
|
+
summary: "",
|
|
4015
4239
|
...kinOf(self, all, p.target),
|
|
4016
4240
|
};
|
|
4017
4241
|
});
|
|
@@ -4221,13 +4445,23 @@ const main = async () => {
|
|
|
4221
4445
|
return "";
|
|
4222
4446
|
return heldDuties({ kind: "wizard", id: uid }).map(dutyLine).join(" · ");
|
|
4223
4447
|
};
|
|
4224
|
-
|
|
4225
|
-
|
|
4226
|
-
|
|
4227
|
-
|
|
4228
|
-
|
|
4229
|
-
|
|
4230
|
-
|
|
4448
|
+
// 惰性: 这几项都要读 transcript 尾巴 (同步), 而渲染只会碰最终列出来的那几行 —— L0 最多 10 行且不带摘要,
|
|
4449
|
+
// L2 一个都不碰, L1 至多 40 行。以前对全机几百行各读一遍 (本机 3.4s 堵死事件循环)。getter 只在
|
|
4450
|
+
// 被读到时算一次; 读过的文件还有 peers.ts 的 stat 缓存兜着。
|
|
4451
|
+
const once = (f) => { let done = false; let v; return () => (done ? v : ((done = true), (v = f()))); };
|
|
4452
|
+
const enrich = (r) => {
|
|
4453
|
+
const duty = once(() => dutiesOf(r.target));
|
|
4454
|
+
const model = once(() => r.model || (r.jsonlPath ? lastModel(r.jsonlPath) : ""));
|
|
4455
|
+
const summary = once(() => (r.jsonlPath ? lastExchange(r.jsonlPath, 80) : ""));
|
|
4456
|
+
const contextTokens = once(() => (r.jsonlPath ? lastContextTokens(r.jsonlPath) : 0));
|
|
4457
|
+
return {
|
|
4458
|
+
...r,
|
|
4459
|
+
get duty() { return duty(); },
|
|
4460
|
+
get model() { return model(); },
|
|
4461
|
+
get summary() { return summary(); },
|
|
4462
|
+
get contextTokens() { return contextTokens(); },
|
|
4463
|
+
};
|
|
4464
|
+
};
|
|
4231
4465
|
const census = rosterCensus(all);
|
|
4232
4466
|
const now = Date.now();
|
|
4233
4467
|
const layer = degraded ? "L0" : b.scope === "all" ? "L2" : b.chat ? "L1" : "L0";
|
|
@@ -4285,7 +4519,7 @@ const main = async () => {
|
|
|
4285
4519
|
model: live ? lastModel(live) || r.model : r.model,
|
|
4286
4520
|
materials,
|
|
4287
4521
|
files: [...new Set(materials.filter((m) => m.confirmed && m.kind === "read").map((m) => m.path))],
|
|
4288
|
-
asks: live ?
|
|
4522
|
+
asks: live ? recentAsks(live, 12) : [],
|
|
4289
4523
|
summary: live ? lastExchange(live, 80) : "",
|
|
4290
4524
|
};
|
|
4291
4525
|
});
|
|
@@ -4675,9 +4909,10 @@ const main = async () => {
|
|
|
4675
4909
|
// 不拷的话它开局就没有, /clear 或交接重开后更是彻底没了。标上来源; 已经是继承来的不再套一层。
|
|
4676
4910
|
...(inherit ? { memory: (wizards.get(source)?.memory ?? []).map((x) => x.startsWith("(继承自 ") ? x : `(继承自 ${displayName(source)}) ${x}`) } : {}),
|
|
4677
4911
|
tier: pick.tier,
|
|
4678
|
-
// 显式写 undefined: 复用的冷记录可能当过 lead
|
|
4912
|
+
// 显式写 undefined: 复用的冷记录可能当过 lead / 被人结束过。
|
|
4679
4913
|
lead: b.lead === true ? true : undefined,
|
|
4680
4914
|
leadOf: undefined,
|
|
4915
|
+
endedAt: undefined,
|
|
4681
4916
|
// 生完才清; 这个进程中途没了, 下次开机由 sweepUnborn 认出并收掉。
|
|
4682
4917
|
spawning: BOOT_ID,
|
|
4683
4918
|
});
|
|
@@ -4844,6 +5079,9 @@ const main = async () => {
|
|
|
4844
5079
|
json(res, again?.status ?? 409, { ok: false, reason: again?.reason ?? "wizard retirement is blocked" });
|
|
4845
5080
|
return;
|
|
4846
5081
|
}
|
|
5082
|
+
// 记录留着 = 「有过身份、被人明确结束」: 泵不许再替它冷启动 (room-hub 的 coldStart 判据)。
|
|
5083
|
+
if (!forgotten)
|
|
5084
|
+
wizards.upsert(cold.target, { endedAt: Date.now() });
|
|
4847
5085
|
json(res, 200, { ok: true, target: cold.target, name: cold.name, mode: "end", forgotten, note: "它本来就没有会话在跑" });
|
|
4848
5086
|
return;
|
|
4849
5087
|
}
|
|
@@ -4936,6 +5174,9 @@ const main = async () => {
|
|
|
4936
5174
|
json(res, blocked?.status ?? 409, { ok: false, target, reason: blocked?.reason ?? "wizard retirement is blocked" });
|
|
4937
5175
|
return;
|
|
4938
5176
|
}
|
|
5177
|
+
// 记录留着 = 「被人明确结束」: endedAt 让泵的冷启动判据认出它 (不许自动重生)。
|
|
5178
|
+
if (end && !forgotten && wizards.get(target))
|
|
5179
|
+
wizards.upsert(target, { endedAt: Date.now() });
|
|
4939
5180
|
// 打断只是停了它这一轮, 它还在; 只有结束才是名册变了。
|
|
4940
5181
|
if (end)
|
|
4941
5182
|
postRoster(baseOfKey(target), [target, self], { op: "ended", name: victim.name || target, by: displayName(self), ...(b.forget ? { why: "forgotten" } : {}) }, subjectOf(victimRec));
|
|
@@ -5691,7 +5932,7 @@ const main = async () => {
|
|
|
5691
5932
|
// 两种清扫串行: 并发时同一个 pane 会被两边各收一次 (第二次 kill-pane 失败、日志重复)。
|
|
5692
5933
|
let reapChain = Promise.resolve();
|
|
5693
5934
|
const serialReap = (what, job) => {
|
|
5694
|
-
reapChain = reapChain.then(job).catch((e) => log.warn({ err: e.message }, `${what} failed`));
|
|
5935
|
+
reapChain = reapChain.then(() => bg.track(what, job)).catch((e) => log.warn({ err: e.message }, `${what} failed`));
|
|
5695
5936
|
};
|
|
5696
5937
|
// pane 上限 — 每新建一个 wizard 数一次: 活着的会话 pane 超过 wrc.mirror.maxPanes
|
|
5697
5938
|
// (默认 20, 0=关) 就从最久没动的收起。数量只在出生时增长, 所以不设定时器。只收
|