wezard 3.0.1 → 3.0.2
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 +14 -11
- package/README.md +2 -2
- package/cli/wezard.sh +56 -20
- package/config.example.jsonc +3 -0
- package/dist/cli/audit.js +11 -13
- package/dist/cli/audit.js.map +1 -1
- package/dist/cli/codex-hook.js +20 -17
- package/dist/cli/codex-hook.js.map +1 -1
- package/dist/cli/ext.js +271 -0
- package/dist/cli/ext.js.map +1 -0
- package/dist/cli/init.js +9 -13
- package/dist/cli/init.js.map +1 -1
- package/dist/cli/sync.js +3 -2
- package/dist/cli/sync.js.map +1 -1
- package/dist/cli/wx.js +7 -6
- package/dist/cli/wx.js.map +1 -1
- package/dist/daemon/aibot-media.js +28 -20
- package/dist/daemon/aibot-media.js.map +1 -1
- package/dist/daemon/approval.js +60 -37
- package/dist/daemon/approval.js.map +1 -1
- package/dist/daemon/channel-onboarding.js +61 -0
- package/dist/daemon/channel-onboarding.js.map +1 -0
- package/dist/daemon/channel-posts.js +56 -16
- package/dist/daemon/channel-posts.js.map +1 -1
- package/dist/daemon/channel-rebind.js +100 -0
- package/dist/daemon/channel-rebind.js.map +1 -0
- package/dist/daemon/channel-store.js.map +1 -1
- package/dist/daemon/channel.js +218 -466
- package/dist/daemon/channel.js.map +1 -1
- package/dist/daemon/claim.js +1 -45
- package/dist/daemon/claim.js.map +1 -1
- package/dist/daemon/classes.js +11 -13
- package/dist/daemon/classes.js.map +1 -1
- package/dist/daemon/config-api.js +5 -29
- package/dist/daemon/config-api.js.map +1 -1
- package/dist/daemon/control-socket.js +93 -0
- package/dist/daemon/control-socket.js.map +1 -0
- package/dist/daemon/danger-scrub.js +315 -0
- package/dist/daemon/danger-scrub.js.map +1 -0
- package/dist/daemon/danger.js +146 -16
- package/dist/daemon/danger.js.map +1 -1
- package/dist/daemon/detail.js +37 -15
- package/dist/daemon/detail.js.map +1 -1
- package/dist/daemon/exec-surface.js +108 -0
- package/dist/daemon/exec-surface.js.map +1 -0
- package/dist/daemon/external.js +595 -0
- package/dist/daemon/external.js.map +1 -0
- package/dist/daemon/http.js +97 -16
- package/dist/daemon/http.js.map +1 -1
- package/dist/daemon/inbound.js +91 -80
- package/dist/daemon/inbound.js.map +1 -1
- package/dist/daemon/index.js +1268 -171
- package/dist/daemon/index.js.map +1 -1
- package/dist/daemon/last-response.js +8 -17
- package/dist/daemon/last-response.js.map +1 -1
- package/dist/daemon/legacy-panes.js +67 -0
- package/dist/daemon/legacy-panes.js.map +1 -0
- package/dist/daemon/mcp-http.js.map +1 -1
- package/dist/daemon/me-room.js +137 -0
- package/dist/daemon/me-room.js.map +1 -0
- package/dist/daemon/media.js +14 -0
- package/dist/daemon/media.js.map +1 -1
- package/dist/daemon/message-format.js +5 -0
- package/dist/daemon/message-format.js.map +1 -1
- package/dist/daemon/mirror-bridge.js +77 -26
- package/dist/daemon/mirror-bridge.js.map +1 -1
- package/dist/daemon/notices.js +4 -5
- package/dist/daemon/notices.js.map +1 -1
- package/dist/daemon/onboarding.js +120 -45
- package/dist/daemon/onboarding.js.map +1 -1
- package/dist/daemon/peers.js +2 -2
- package/dist/daemon/peers.js.map +1 -1
- package/dist/daemon/plan-http.js +2 -3
- package/dist/daemon/plan-http.js.map +1 -1
- package/dist/daemon/reach.js +1 -5
- package/dist/daemon/reach.js.map +1 -1
- package/dist/daemon/room-bind.js +297 -0
- package/dist/daemon/room-bind.js.map +1 -0
- package/dist/daemon/room-facts.js +1 -1
- package/dist/daemon/room-facts.js.map +1 -1
- package/dist/daemon/room-hub.js +158 -19
- package/dist/daemon/room-hub.js.map +1 -1
- package/dist/daemon/room-overdue.js +90 -28
- package/dist/daemon/room-overdue.js.map +1 -1
- package/dist/daemon/room-watchdog.js +44 -22
- package/dist/daemon/room-watchdog.js.map +1 -1
- package/dist/daemon/rooms.js +101 -4
- package/dist/daemon/rooms.js.map +1 -1
- package/dist/daemon/session-scan.js +1 -1
- package/dist/daemon/session-scan.js.map +1 -1
- package/dist/daemon/short-id-log.js +43 -0
- package/dist/daemon/short-id-log.js.map +1 -0
- package/dist/daemon/spawn-tmux.js +12 -9
- package/dist/daemon/spawn-tmux.js.map +1 -1
- package/dist/daemon/steward-guard.js +1 -1
- package/dist/daemon/steward-guard.js.map +1 -1
- package/dist/daemon/steward-model.js +17 -3
- package/dist/daemon/steward-model.js.map +1 -1
- package/dist/daemon/steward-repair.js +171 -0
- package/dist/daemon/steward-repair.js.map +1 -0
- package/dist/daemon/steward.js +48 -9
- package/dist/daemon/steward.js.map +1 -1
- package/dist/daemon/tool-face.js +31 -0
- package/dist/daemon/tool-face.js.map +1 -0
- package/dist/daemon/turn-opening.js +8 -3
- package/dist/daemon/turn-opening.js.map +1 -1
- package/dist/daemon/wizard-memory.js +4 -10
- package/dist/daemon/wizard-memory.js.map +1 -1
- package/dist/daemon/wizard.js +153 -73
- package/dist/daemon/wizard.js.map +1 -1
- package/dist/daemon/ws.js +1 -1
- package/dist/daemon/ws.js.map +1 -1
- package/dist/mcp/output.js +27 -5
- package/dist/mcp/output.js.map +1 -1
- package/dist/mcp/relay.js +152 -0
- package/dist/mcp/relay.js.map +1 -0
- package/dist/mcp/tools.js +87 -39
- package/dist/mcp/tools.js.map +1 -1
- package/dist/shared/chat-http.js +65 -48
- package/dist/shared/chat-http.js.map +1 -1
- package/dist/shared/cli-local-status.js +28 -0
- package/dist/shared/cli-local-status.js.map +1 -0
- package/dist/shared/cli-socket.js +14 -0
- package/dist/shared/cli-socket.js.map +1 -0
- package/dist/shared/codex-hooks.js +5 -2
- package/dist/shared/codex-hooks.js.map +1 -1
- package/dist/shared/config.js +45 -45
- package/dist/shared/config.js.map +1 -1
- package/dist/shared/daemon-addr.js +23 -0
- package/dist/shared/daemon-addr.js.map +1 -0
- package/dist/shared/daemon-client.js +41 -0
- package/dist/shared/daemon-client.js.map +1 -0
- package/dist/shared/daemon-token.js +2 -2
- package/dist/shared/daemon-token.js.map +1 -1
- package/dist/shared/external.js +402 -0
- package/dist/shared/external.js.map +1 -0
- package/dist/shared/inject-view.js +48 -10
- package/dist/shared/inject-view.js.map +1 -1
- package/dist/shared/instance-id.js +21 -0
- package/dist/shared/instance-id.js.map +1 -0
- package/dist/shared/message-footer.js +8 -1
- package/dist/shared/message-footer.js.map +1 -1
- package/dist/shared/model-tiers.js +39 -1
- package/dist/shared/model-tiers.js.map +1 -1
- package/dist/shared/ports.js +56 -0
- package/dist/shared/ports.js.map +1 -0
- package/dist/shared/pricing.js +0 -5
- package/dist/shared/pricing.js.map +1 -1
- package/dist/shared/role-render.js +8 -7
- package/dist/shared/role-render.js.map +1 -1
- package/dist/shared/role-view.js +5 -2
- package/dist/shared/role-view.js.map +1 -1
- package/dist/shared/room-overdue.js +84 -12
- package/dist/shared/room-overdue.js.map +1 -1
- package/dist/shared/room-view.js +18 -4
- package/dist/shared/room-view.js.map +1 -1
- package/dist/shared/room.js +245 -28
- package/dist/shared/room.js.map +1 -1
- package/dist/shared/session-label.js +29 -51
- package/dist/shared/session-label.js.map +1 -1
- package/dist/shared/session-mcp.js +35 -57
- package/dist/shared/session-mcp.js.map +1 -1
- package/dist/shared/smarts.js +15 -30
- package/dist/shared/smarts.js.map +1 -1
- package/dist/shared/world.js +1 -1
- package/dist/shared/world.js.map +1 -1
- package/dist/svr/facts-store.js.map +1 -1
- package/dist/svr/index.js +57 -15
- package/dist/svr/index.js.map +1 -1
- package/hooks/pre-tool-use.sh +14 -10
- package/hooks/stop.sh +5 -3
- package/launchd/com.wezard.svr.plist.template +2 -0
- package/package.json +3 -1
- package/scripts/install.sh +12 -0
- package/systemd/wezard-svr.service.template +2 -0
- package/web/chat.js +81 -40
- package/dist/daemon/bot-mux.js +0 -161
- package/dist/daemon/bot-mux.js.map +0 -1
package/dist/daemon/index.js
CHANGED
|
@@ -6,7 +6,7 @@ import { timingSafeEqual, randomBytes, randomUUID } from "node:crypto";
|
|
|
6
6
|
import { loadOrCreateSvrToken } from "../shared/svr-token.js";
|
|
7
7
|
import { DAEMON_TOKEN_FILE, DAEMON_TOKEN_HEADER } from "../shared/daemon-token.js";
|
|
8
8
|
import { homedir } from "node:os";
|
|
9
|
-
import { TIERS,
|
|
9
|
+
import { TIERS, tiersForBackend, loadConfig } from "../shared/config.js";
|
|
10
10
|
import { makeLogger } from "../shared/log.js";
|
|
11
11
|
import { memAvailableMb, memShortfall } from "../shared/mem-guard.js";
|
|
12
12
|
import { clipLine, sleep } from "../shared/std.js";
|
|
@@ -14,28 +14,31 @@ import { patchJsonc } from "../shared/config-writer.js";
|
|
|
14
14
|
import { EFFORTS, parseEffort } from "../shared/effort.js";
|
|
15
15
|
import { bindCliBackends, projectDirsFor } from "../shared/cli-backends.js";
|
|
16
16
|
import { bindCodexStateDir } from "../shared/codex.js";
|
|
17
|
-
import {
|
|
17
|
+
import { startWs } from "./ws.js";
|
|
18
18
|
import { startWeixin } from "./weixin.js";
|
|
19
19
|
import { installWeixinPort } from "./weixin-port.js";
|
|
20
20
|
import { bindWxCommands, makeOnBound, makeWxCommands, routeSendMedia, wecomBindSink, weixinSendMedia, wxAdmins, wxRoutes } from "./weixin-cmd.js";
|
|
21
21
|
import { bindChatReach } from "./reach.js";
|
|
22
22
|
import { kindOf } from "./media.js";
|
|
23
|
-
import { aibotSendMedia } from "./aibot-media.js";
|
|
23
|
+
import { aibotSendMedia, uploadMediaId } from "./aibot-media.js";
|
|
24
24
|
import { startNetWatch } from "./net-watch.js";
|
|
25
25
|
import { startHttp, json, readBody } from "./http.js";
|
|
26
26
|
import { registerMcpHttp } from "./mcp-http.js";
|
|
27
27
|
import { parsePath } from "../shared/config-meta.js";
|
|
28
|
-
import { pickTier } from "../shared/model-tiers.js";
|
|
29
|
-
import { applyHot,
|
|
28
|
+
import { pickTier, tierOfModel } from "../shared/model-tiers.js";
|
|
29
|
+
import { applyHot, patchedTop, pinChatKeys, configGet, planSet, renderPlan, tierEvidence } from "./config-api.js";
|
|
30
30
|
import { computeUsage, costOf, fmtCost, fmtTokens, sumTotal } from "./usage.js";
|
|
31
31
|
import { humanWakeTail, wakeInjectOpts, wakeTailPorts } from "./wake-tail.js";
|
|
32
32
|
import { installInboundRouter } from "./inbound.js";
|
|
33
|
-
import { installChannelTransport, installChannelEvents, readChannel, isTopicChat,
|
|
33
|
+
import { installChannelTransport, installChannelEvents, readChannel, isTopicChat, channelOutboundOf, sendTopicPost, sendTopicReply, sendTopicReplyOrPost } from "./channel.js";
|
|
34
|
+
import { channelOf, channelRefOf, learnChannelRoom, postRefOf, postsOfChannel } from "./channel-posts.js";
|
|
35
|
+
import { channelMonitorLeaveOps, channelMonitorWanted, channelRoomOf, channelGuideJoinOps, hostJoinOps, planChannelGuideTurn, postRoomBirthOps } from "./channel-onboarding.js";
|
|
36
|
+
import { rebindChannel } from "./channel-rebind.js";
|
|
34
37
|
import { loadMirrorStore } from "./mirror-store.js";
|
|
35
38
|
import { startMirror, installMirrorEventListener } from "./mirror-bridge.js";
|
|
36
39
|
import { backendFor, prewarmShell, runTmux, setTmuxTimeoutReporter, spawnTmuxClaude } from "./spawn-tmux.js";
|
|
37
40
|
import { installApprovalEventListener, makeApproveHandler, requestConfirm } from "./approval.js";
|
|
38
|
-
import { initDetailPersistence, makeDetailHandler, chatHandlers, configureRemoteForward, chatUrlFor,
|
|
41
|
+
import { initDetailPersistence, makeDetailHandler, chatHandlers, configureRemoteForward, chatUrlFor, detailRoot, setViewPort, linksDead, setRoomReader, setWorldFactsProvider, recordCharter, backfillCharter, lastChannelOf, setChannelRef } from "./detail.js";
|
|
39
42
|
import { EMPTY_FACTS } from "../shared/world.js";
|
|
40
43
|
import { clearAutoWindow, initAutoWindowPersistence, setAutoWindow } from "./session-cache.js";
|
|
41
44
|
import { makeMessageHandler } from "./outbound.js";
|
|
@@ -43,29 +46,38 @@ import { makeCardHandler, makeAskHandler, installAskEventListener } from "./ask.
|
|
|
43
46
|
import { drainForReload, listPending } from "./pending.js";
|
|
44
47
|
import { makeClaimStartHandler, makeClaimStatusHandler, makeClaimResetHandler, } from "./claim.js";
|
|
45
48
|
import { errText, installResponseTracker } from "./last-response.js";
|
|
46
|
-
import { openRoomStore } from "./rooms.js";
|
|
49
|
+
import { BindGateClosed, openRoomStore, resolveHashRef } from "./rooms.js";
|
|
50
|
+
import { openShortIdLog } from "./short-id-log.js";
|
|
51
|
+
import { bindCandidates, planBind, planChannelBackfill, planFork, planUnbind, pendingFirstTouches, sourceRoomOf } from "./room-bind.js";
|
|
47
52
|
import { stewardRoute as resolveSteward } from "./steward.js";
|
|
53
|
+
import { repairStewardInstances, unspawnedStewards } from "./steward-repair.js";
|
|
48
54
|
import { createRoomWatchdog, parsePaneIds } from "./room-watchdog.js";
|
|
49
55
|
import { pruneLeaveOps, selectRoomPrune } from "./room-prune.js";
|
|
50
56
|
import { createOverdueScan } from "./room-overdue.js";
|
|
51
57
|
import { createRoomHub } from "./room-hub.js";
|
|
58
|
+
import { createExternal } from "./external.js";
|
|
59
|
+
import { extLabel, extNameOf, extReceptionTagOf, extReceptionTargetOf, receptionDenial } from "../shared/external.js";
|
|
60
|
+
import { ensureMeRoom, isMeRoom, meChannelSay, meRoomId, meRowMirror, meUserOf, meWorkspaceOf } from "./me-room.js";
|
|
52
61
|
import { autoAdhocTarget } from "./room-auto-adhoc.js";
|
|
53
62
|
import { checkRoomTarget, seatThenAppend } from "./room-spawn.js";
|
|
54
|
-
import { DAEMON, adhocRoomId, canRename, dmPeers, dmRoomId, findPairAdhoc, holderOf, idList, isUid, judgeNotice, leaveOps, dutiesHeldBy, planDm, quotedRowIds, seatSeenOps, openDuties, roomHost, roomsDirOf, sameWho, whoKey, } from "../shared/room.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";
|
|
55
64
|
import { CLASS_NAME_MAX, loadClassMerges, loadClassStore, migrateClasses, parseInstanceName, planClasses, renderClassReport, validClassName } from "./classes.js";
|
|
56
|
-
import { addressed, footerTarget, responseFormatPolicy, roomBubble } from "./message-format.js";
|
|
57
|
-
import { scanClaudeSessions } from "./session-scan.js";
|
|
65
|
+
import { addressed, footerTarget, responseFormatPolicy, roomBubble, withBubbleFooter } from "./message-format.js";
|
|
66
|
+
import { procSnapshot, scanClaudeSessions } from "./session-scan.js";
|
|
67
|
+
import { createLegacyPaneReaper, parsePanePids } from "./legacy-panes.js";
|
|
68
|
+
import { removeLegacyMcpFiles } from "../shared/session-mcp.js";
|
|
58
69
|
import { startScheduler, promptWantsFreshWizard, renderTask, sinceOf, } from "./tasks.js";
|
|
59
70
|
import { openTaskRegistry } from "./task-registry.js";
|
|
60
71
|
import { describeTrigger, nextFire, parseTrigger, WHEN_HELP } from "../shared/trigger.js";
|
|
61
72
|
import { slugify, uniqueId } from "../shared/task-file.js";
|
|
62
|
-
import { baseOfKey,
|
|
73
|
+
import { baseOfKey, bindTagLinker, headed, ownHead, isInternalKey, keyOf, linkTags, normalizeTag, stripSigil, tagOfKey, uniqueTag, withTagHeader } from "../shared/session-label.js";
|
|
63
74
|
import { appendEpisode, clipForCharter, cwdOfMd, episodePath, inboxPath, mdsOf, proposedCwds, memoryPath, memoryRoot, proposeMemory, readMemory } from "./wizard-memory.js";
|
|
64
75
|
import { startSteward, stewardEnvelope, STEWARD_ID, STEWARD_RUN_MS, STEWARD_TARGET } from "./memory-steward.js";
|
|
65
76
|
import { chatBaseOf, chatNameOf, chatPolicyOf, listChatNames, peerAddress } from "./chat-name.js";
|
|
66
|
-
import { isStewardTarget, markGlobalSteward, STEWARD_KINDS, stewardRoute, stewardsAt } from "./steward.js";
|
|
77
|
+
import { appointedSteward, isStewardTarget, localManifestation, markGlobalSteward, STEWARD_KINDS, stewardIdentityOf, stewardRoute, stewardsAt } from "./steward.js";
|
|
67
78
|
import { apprenticeOf, ensureApprentice, ensurePatrolTask, handoffLineOf, isApprentice } from "./apprentice.js";
|
|
68
|
-
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, } from "./wizard.js";
|
|
79
|
+
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
|
+
import { faceRefusal } from "./tool-face.js";
|
|
69
81
|
import { activeRows, bindNoticeBox, createNoticeBox, createSeenRing, gcSeen, chatAudience, hears } from "./notices.js";
|
|
70
82
|
import { cacheTouchMs, cacheTtlSec, contextMaterials, firstStamp, lastContextTokens, lastExchange, lastModel, talkTurns } from "./peers.js";
|
|
71
83
|
import { expandHome } from "../shared/paths.js";
|
|
@@ -80,7 +92,7 @@ import { parseWhen, planHasOpenDuty, renderRoomRead } from "../shared/room-view.
|
|
|
80
92
|
import { memberLabel } from "../shared/room-label.js";
|
|
81
93
|
import { roomFacts, nameTable } from "./room-facts.js";
|
|
82
94
|
import { waitForIdle } from "./wait-idle.js";
|
|
83
|
-
import { applyOnboarding, bindSteward, guideHandoffOps, guideOf,
|
|
95
|
+
import { applyOnboarding, bindSteward, GUIDE_DESC, guideHandoffOps, guideOf, isGuideManifestation, judgeOnboarding, loadOnboardingStore, needsOnboarding, planOnboardBind, renderGuideOpening, renderGuideRetry, renderOnboardingDone, rewriteStewardBindings } from "./onboarding.js";
|
|
84
96
|
import { reminderToken, startPlanReminders } from "./plan-reminders.js";
|
|
85
97
|
const retiredOrchestrationField = (body) => {
|
|
86
98
|
if (!body || typeof body !== "object" || Array.isArray(body))
|
|
@@ -117,7 +129,6 @@ const main = async () => {
|
|
|
117
129
|
if (stale.length)
|
|
118
130
|
console.warn("[wezard] 配置里还有已废弃的 chatPolicy 旧键 (room 模型已移除, 忽略): " + stale.join(", "));
|
|
119
131
|
}
|
|
120
|
-
bindMultiBot(cfg.bots.length > 0);
|
|
121
132
|
const log = makeLogger({
|
|
122
133
|
logFile: cfg.daemon.logFile,
|
|
123
134
|
logLevel: cfg.daemon.logLevel,
|
|
@@ -128,6 +139,13 @@ const main = async () => {
|
|
|
128
139
|
// wizards / m / notifyChat), 但 startScheduler 在那块外面接线 —— 见文件尾。
|
|
129
140
|
// 记忆整理者的执行体, 同样只有 mirror 模式给得出 —— 赋值见 scheduledTaskInject 旁边。
|
|
130
141
|
let stopPlanReminders = () => { };
|
|
142
|
+
// 频道入站的三条接线 (room 块在下面才立起来, 先留引用): 人话落 room / 频道首次见到 / 帖子源首触
|
|
143
|
+
// (只记事, 不建 room —— 见 docs/room/multi-source-binding.md §4.1)。
|
|
144
|
+
let channelIngest;
|
|
145
|
+
let channelRoomSeen;
|
|
146
|
+
let channelPostTouched;
|
|
147
|
+
/** 入站源解析 (§4.1): 源已绑 / 帖子源未诞生时, 这句话落哪本账、谁是接待人。恒等路径 = undefined。 */
|
|
148
|
+
let sourceRouteHook;
|
|
131
149
|
let stewardRun;
|
|
132
150
|
let stewardWiring = {};
|
|
133
151
|
let scheduledTaskInject;
|
|
@@ -143,19 +161,25 @@ const main = async () => {
|
|
|
143
161
|
// wedged tmux server, and the exec helper has no logger of its own. Wire it
|
|
144
162
|
// up before anything can spawn a pane.
|
|
145
163
|
setTmuxTimeoutReporter(({ args, timeoutMs }) => log.warn({ args: args.slice(0, 4), timeoutMs }, "tmux command timed out — killed"));
|
|
164
|
+
// 旧版的按会话 MCP 产物: TCP 时代的 session-mcp.json / session-mcp-http.json 不再生成, 这里清掉
|
|
165
|
+
// (http 那份里是口令原文, 留在盘上就是个泄露点)。新产物是 session-mcp-sock.json, 由 spawn 时写。
|
|
166
|
+
const removedMcp = removeLegacyMcpFiles(expandHome(cfg.daemon.stateDir));
|
|
167
|
+
if (removedMcp.length)
|
|
168
|
+
log.info({ files: removedMcp }, "legacy per-session MCP configs removed");
|
|
146
169
|
// Restore auto-approve windows persisted across daemon restarts —
|
|
147
170
|
// otherwise a `wezard reload` silently drops the user's "10min" choice.
|
|
148
171
|
initAutoWindowPersistence(cfg.daemon.stateDir);
|
|
172
|
+
// rolepage 的频道 / 帖子 kind 与归属读时算 (channel-posts), 不落账本。
|
|
173
|
+
setChannelRef((room) => channelRefOf(cfg, room));
|
|
149
174
|
// Replay tool/approval detail records so reload doesn't lose click-to-detail
|
|
150
175
|
// links from messages already on the user's WeCom timeline.
|
|
151
176
|
initDetailPersistence(cfg.daemon.stateDir, log.child({ mod: "detail" }));
|
|
152
177
|
configureRemoteForward(cfg.daemon.detailRemoteBase, cfg.daemon.detailRemoteToken);
|
|
153
|
-
//
|
|
154
|
-
|
|
155
|
-
const ws = startMux(cfg, log);
|
|
178
|
+
// 必须先于 weixin-port / response-tracker 建好 —— 它们包在 ws.client 外层。
|
|
179
|
+
const ws = startWs(cfg.bot, log);
|
|
156
180
|
// 频道出站补丁必须先于 response-tracker:tracker 会把当时的 sendMessage /
|
|
157
181
|
// replyStream 抓成 orig*,晚装就绕过了频道分支(终句会走成群消息)。
|
|
158
|
-
installChannelTransport(ws.client, log.child({ mod: "channel" })
|
|
182
|
+
installChannelTransport(ws.client, log.child({ mod: "channel" }));
|
|
159
183
|
// 切网 (换 WiFi / VPN 起停) 后原地重建 WS, 等价于自动做了一次 reload 的
|
|
160
184
|
// 联通性部分 — 但保留全部内存态 (pending 长轮询、镜像绑定),
|
|
161
185
|
// 也不依赖 launchd/systemd 的 respawn 策略 (nohup fallback 没有 supervisor)。
|
|
@@ -209,6 +233,8 @@ const main = async () => {
|
|
|
209
233
|
let ensureRoom;
|
|
210
234
|
/** mirror 轮终回调 (bridge 创建早于 room 块, 这里先挂口)。 */
|
|
211
235
|
let roomTurnEnd = () => undefined;
|
|
236
|
+
/** 注入头 #hash8 → room 全 id (mirror 的 turn-opening 回读用; room 块里回填)。 */
|
|
237
|
+
let roomOfHashHook = () => undefined;
|
|
212
238
|
/** room 泵注入成功的 touch (看门狗活动时钟; 同上, room 块里回填)。 */
|
|
213
239
|
let roomActivityTouch = () => undefined;
|
|
214
240
|
/** 新群引导在 room 模型里的两个接线点 (见 inbound.ts InboundOpts): room 块里回填 —— 只有它持有 hub。 */
|
|
@@ -218,7 +244,7 @@ const main = async () => {
|
|
|
218
244
|
let getNoticeHook;
|
|
219
245
|
/** 引导在途状态 (onboarding.json): inbound 与 /onboarding/bind 共用这一份, 不各读各的盘。 */
|
|
220
246
|
const onboarding = loadOnboardingStore(cfg);
|
|
221
|
-
const bridge = startMirror({ cfg, log: log.child({ mod: "mirror" }), client: ws.client, store: mirrorStore, identityWorkspace: (t) => identityWorkspaceOf(wizardStore(), t), sendFrozen: (channel, content, stream) => responseTracker.sendFrozen(channel.replace(/^(user|chat|group):/, ""), content, stream),
|
|
247
|
+
const bridge = startMirror({ cfg, log: log.child({ mod: "mirror" }), client: ws.client, store: mirrorStore, identityWorkspace: (t) => identityWorkspaceOf(wizardStore(), t), roomOfHash: (h) => roomOfHashHook(h), sendFrozen: (channel, content, stream) => responseTracker.sendFrozen(channel.replace(/^(user|chat|group):/, ""), content, stream),
|
|
222
248
|
// 轮终事件 (wiring C): mirror tail 的非 soft turn_end → room 的 F-1 轮界。
|
|
223
249
|
onTurnEnd: (target) => { roomTurnEnd(target); } });
|
|
224
250
|
// 群里每个 `.name` 都挂它的 rolepage (见 session-label 的 TagLinker)。正文提及
|
|
@@ -226,11 +252,11 @@ const main = async () => {
|
|
|
226
252
|
const known = (t) => bridge.chatTargets(t).includes(t);
|
|
227
253
|
// 名册在下面的 mirror 块里才绑 (bindWizardStore) —— 这里全走 wizardStore() 惰性取。
|
|
228
254
|
bindTagLinker({
|
|
229
|
-
targetOfUrl: (url) => footerTarget(url,
|
|
255
|
+
targetOfUrl: (url) => footerTarget(url, detailRoot(cfg.daemon.detailPublicBase, cfg.daemon.host, cfg.daemon.port), known),
|
|
230
256
|
urlOf: (t) => chatUrlFor(cfg.daemon, t),
|
|
231
257
|
resolve: (name, from) => {
|
|
232
258
|
const t = wizardStore()?.byName(name)?.target;
|
|
233
|
-
return t && known(t)
|
|
259
|
+
return t && known(t) ? t : undefined;
|
|
234
260
|
},
|
|
235
261
|
nameOf: (t) => settleName(wizardStore(), chatNameOf(cfg, t), t),
|
|
236
262
|
voiceOf: (t) => wizardStore()?.get(t)?.voiceOf,
|
|
@@ -248,9 +274,16 @@ const main = async () => {
|
|
|
248
274
|
}
|
|
249
275
|
// 人话进 room 账本 (wiring B): 绑定 room = 本聊天的 base principal, 原样作 room id (契约 §1)。
|
|
250
276
|
// room 块还没装上 (启动竞态) 或落行被拒 → 退回老路径, 人话不能丢。
|
|
251
|
-
const room = ensureRoom ? ensureRoom(baseOfKey(a.channel), a.principal) : baseOfKey(a.channel);
|
|
252
277
|
const author = { kind: "human", id: String(a.speaker ?? "").replace(/^user:/, "") };
|
|
253
278
|
const routed = wizardStore()?.get(a.principal);
|
|
279
|
+
// .me 分流 (人 2026-11-24 拍板): 路由到说话人自己的分身 (kind "me") → 这句人话不落
|
|
280
|
+
// 发生地 room, 落他的私有 me-room (幂等开房, me/人入座)。发生地零行: 不 ensureRoom、
|
|
281
|
+
// monitor/host 看不见、不耗发生地预算; duty 开在 me 名下 (host 槽位 —— me 是唯一 wizard
|
|
282
|
+
// 成员), 占位气泡照开在发生地 (回发由 roomMirror 的 me 分支覆盖它)。
|
|
283
|
+
const meRoom = routed?.kind === "me" && author.id
|
|
284
|
+
? ensureMeRoom({ state: (r) => roomStateOf?.(r), write: (r, ops) => { roomHub?.write(r, ops); }, meUid: () => routed.uid }, author.id)
|
|
285
|
+
: undefined;
|
|
286
|
+
const room = meRoom ?? (ensureRoom ? ensureRoom(baseOfKey(a.channel), a.principal) : baseOfKey(a.channel));
|
|
254
287
|
// 点名 (.name 路由到别的 wizard): 先拉进 room (via mention), duty 开给它;
|
|
255
288
|
// 管家接待轮 (routed 就是 host) 不点名 → duty 按 §2 落 host。
|
|
256
289
|
let to;
|
|
@@ -265,7 +298,9 @@ const main = async () => {
|
|
|
265
298
|
to = [w];
|
|
266
299
|
}
|
|
267
300
|
// 图片以 @path 文本随行 (codebuddy 的唯一通道), 账本行同时记 files。
|
|
268
|
-
|
|
301
|
+
// 账本行只存人的原话 (rawText): prompt 里为引用加的块不进正文 —— rolepage 与之后每次
|
|
302
|
+
// room_read / wake 都按行正文复读, 引用 (尤其频道帖子摘要) 进正文等于反复抄整帖。
|
|
303
|
+
const text = (a.rawText ?? a.text) + (a.images?.length ? "\n" + a.images.map((p) => "@" + p).join(" ") : "");
|
|
269
304
|
const streamId = String(a.streamId ?? "");
|
|
270
305
|
const expires = Date.now() + 6 * 60_000;
|
|
271
306
|
// 占位气泡: frame 记表 (reload 后也能收口), 先挂 loading; 第一条 re 它的 reply 覆盖 (§3a)。
|
|
@@ -278,7 +313,8 @@ const main = async () => {
|
|
|
278
313
|
const v = roomHub?.append(room, { author, kind: "say", text, origin: "inbound", ext: streamId,
|
|
279
314
|
bubble: { stream: streamId, expires }, ...(re.length ? { re } : {}),
|
|
280
315
|
...(a.images?.length ? { files: a.images.map((p) => ({ path: p, kind: kindOf(p), name: basename(p) })) } : {}),
|
|
281
|
-
...(to?.length ? { to } : {}) })
|
|
316
|
+
...(to?.length ? { to } : {}), ...(a.mentionBot ? { mention: "bot" } : {}),
|
|
317
|
+
...(a.src ? { src: a.src } : {}), ...(a.post ? { post: a.post } : {}) });
|
|
282
318
|
if (!v || !v.ok) {
|
|
283
319
|
// 被拒不回退旧路径 (wiring C): 按 verdict 原因回一行系统提示 —— 人话不能丢, 也不能绕过账本。
|
|
284
320
|
const reason = v ? v.reason : "room 接线还没就绪 (启动竞态), 稍后再发一句";
|
|
@@ -295,6 +331,7 @@ const main = async () => {
|
|
|
295
331
|
.catch(() => undefined);
|
|
296
332
|
}
|
|
297
333
|
} }, sourcePath, (w, c) => guardCharter(w, c), { onboarding,
|
|
334
|
+
sourceRoute: (base) => sourceRouteHook?.(base),
|
|
298
335
|
guideInbound: (a) => (guideInboundHook ? guideInboundHook(a) : Promise.resolve({ ok: false, reason: "room 接线还没就绪" })),
|
|
299
336
|
guideSettle: (base, bound) => (guideSettleHook ? guideSettleHook(base, bound) : false),
|
|
300
337
|
getNotice: (base) => (getNoticeHook ? getNoticeHook(base) : undefined),
|
|
@@ -302,7 +339,9 @@ const main = async () => {
|
|
|
302
339
|
});
|
|
303
340
|
// 频道(topic)事件层:接在 inbound 之后,让频道消息复用同一套 gate / route / mirror。
|
|
304
341
|
installChannelEvents(ws.client, cfg, log.child({ mod: "channel" }), {
|
|
305
|
-
|
|
342
|
+
ingest: (e) => (channelIngest ? channelIngest(e) : log.warn({ room: e.room, msgid: e.msgid }, "channel: room wiring not ready, 人话没落账本")),
|
|
343
|
+
channelSeen: (t) => channelRoomSeen?.(t),
|
|
344
|
+
postTouched: (t, b) => channelPostTouched?.(t, b),
|
|
306
345
|
});
|
|
307
346
|
// approval click → finalize 当前 liveStream, 后续 tool/text 落到 standalone。
|
|
308
347
|
// 规则 2: 用户点击授权那一刻就是"上一段对话"的边界, 截断 stream 让授权后的
|
|
@@ -333,8 +372,22 @@ const main = async () => {
|
|
|
333
372
|
};
|
|
334
373
|
// room 模型的 /status 增量 (修复单 §4): startHttp 在 room 模块之前起, 用可改写的 holder 接。
|
|
335
374
|
const roomStatusRef = { get: () => ({}) };
|
|
336
|
-
|
|
337
|
-
|
|
375
|
+
// 视图口的结局定了才知道链接根: 实际口 (可能是配置口 +N) 给 detail.ts; 一个 base 都没有又没起来 = 链接全是死链,
|
|
376
|
+
// 那就不发链接 (裸头), 在这里说一次为什么。
|
|
377
|
+
const onView = (port) => {
|
|
378
|
+
setViewPort(port);
|
|
379
|
+
if (linksDead(cfg.daemon.detailPublicBase))
|
|
380
|
+
log.warn({ port: cfg.daemon.port }, "no view listener and no detailPublicBase/detailRemoteBase: chat messages go out without rolepage / detail links");
|
|
381
|
+
};
|
|
382
|
+
const http = startHttp({ cfg, ws, log, sourcePath, roomStatus: roomStatusRef, onView });
|
|
383
|
+
// 控制面 socket 绑不上 (活 daemon 在听 / 目录不是自己的 / 路径超长) = 起不来: 报原因后 exit 1,
|
|
384
|
+
// systemd / launchd 重试, 对方退出后自然接手。视图 TCP 监听失败不走这里 (只告警)。
|
|
385
|
+
await http.ready.catch((e) => fatalExit(`control socket: ${e.message}`));
|
|
386
|
+
// 外部调用方的生效名单 (配置 ∪ 首连登记表): 审批判定 / 接待禁用表 / 逾期落点都读它。
|
|
387
|
+
// 登记表在 gateway 里, gateway 稍后才建 —— 这里先给回落到配置的读法, 建好后换成合并版 (闭包绕开顺序)。
|
|
388
|
+
let externalPrincipalsNow = () => cfg.external?.principals ?? [];
|
|
389
|
+
http.register("POST /approve", makeApproveHandler({ cfg, log: log.child({ mod: "approval" }), client: ws.client, sourcePath, getMirrorTarget, flushBeforeCard, nativeModal,
|
|
390
|
+
externalPrincipals: () => externalPrincipalsNow() }));
|
|
338
391
|
http.register("POST /message", makeMessageHandler(ws.client, log.child({ mod: "outbound" })));
|
|
339
392
|
http.register("POST /card", makeCardHandler(ws.client, log.child({ mod: "outbound" })));
|
|
340
393
|
http.register("POST /ask", makeAskHandler(ws.client, log.child({ mod: "ask" })));
|
|
@@ -463,7 +516,7 @@ const main = async () => {
|
|
|
463
516
|
return;
|
|
464
517
|
const sessions = await scanClaudeSessions();
|
|
465
518
|
// 已绑在别的机器人聊天上的会话与不存在同形。
|
|
466
|
-
const hit = sessions.find((s) => s.sessionId === sessionId
|
|
519
|
+
const hit = sessions.find((s) => s.sessionId === sessionId);
|
|
467
520
|
if (!hit) {
|
|
468
521
|
json(res, 404, { ok: false, reason: `session ${sessionId} not found among live tmux sessions` });
|
|
469
522
|
return;
|
|
@@ -500,6 +553,8 @@ const main = async () => {
|
|
|
500
553
|
json(res, 400, { ok: false, reason: "target required (or pass sessionId of an attached chat)" });
|
|
501
554
|
return;
|
|
502
555
|
}
|
|
556
|
+
if (refuseReception(res, "POST /mirror/workspace", target))
|
|
557
|
+
return;
|
|
503
558
|
const caller = resolveSelf({ sessionId: body.sessionId, tmuxPane: body.tmuxPane });
|
|
504
559
|
if (refuseGuide(res, caller, "set_workspace") || refuseGuide(res, target, "set_workspace", false))
|
|
505
560
|
return;
|
|
@@ -545,6 +600,50 @@ const main = async () => {
|
|
|
545
600
|
? { ok: true, target, sessionId: r.sessionId, cwd: r.cwd }
|
|
546
601
|
: { ok: false, reason: r.reason, target, runningCwd: set.runningCwd, pendingCwd: set.pendingCwd });
|
|
547
602
|
});
|
|
603
|
+
// 频道换绑 (人 2026-11-23: 「绑定工作区为 cc-wecom」): 频道 = 一条类绑定; 换绑 = 建 / 复用
|
|
604
|
+
// 该目录的管家类 + 写 wrc.channel.steward + 频道 room 与各帖子 room 坐上新类的**本 room**
|
|
605
|
+
// 实例 (旧 host 不离开: leave 会把它手上没交代的件全 canceled)。只动这一个频道。
|
|
606
|
+
http.register("POST /mirror/channel/rebind", async (req, res) => {
|
|
607
|
+
const body = (await readBody(req));
|
|
608
|
+
const self = resolveSelf(body);
|
|
609
|
+
if (!self) {
|
|
610
|
+
json(res, 400, { ok: false, reason: "cannot resolve caller session" });
|
|
611
|
+
return;
|
|
612
|
+
}
|
|
613
|
+
const topicId = (body.topicId ?? "").trim();
|
|
614
|
+
// 权限: 频道管家表本来就对 wizard 可写 (config_set 那条), 这里不另设身份闸 —— 只要求
|
|
615
|
+
// 频道已有账本 (认得出的频道才谈得上换绑), 并把这次改动写进频道 room (谁换的, 换成什么)。
|
|
616
|
+
if (!roomState("chat:" + topicId)) {
|
|
617
|
+
json(res, 404, { ok: false, reason: "这个频道还没有 room 账本: " + topicId });
|
|
618
|
+
return;
|
|
619
|
+
}
|
|
620
|
+
const { r: out, note } = guardCharter(() => rebindChannel({
|
|
621
|
+
cfg, sourcePath, store: wizards, stateOf: roomState,
|
|
622
|
+
write: (room, ops) => { hub.write(room, ops); },
|
|
623
|
+
topicId, workspace: (body.workspace ?? "").toString(), ...(body.name ? { name: body.name.toString() } : {}),
|
|
624
|
+
}), (r) => r.ok ? { what: "频道 " + r.topicId + " 换绑到 ." + r.className, self, byHuman: true } : undefined);
|
|
625
|
+
if (!out.ok) {
|
|
626
|
+
json(res, 400, out);
|
|
627
|
+
return;
|
|
628
|
+
}
|
|
629
|
+
// 频道级事实留一条系统行 (不唤醒谁、不开 duty): 人一眼看到 host 换成了谁。
|
|
630
|
+
const ownRoom = "chat:" + out.topicId;
|
|
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);
|
|
644
|
+
roomLog.info({ ...out }, "channel: rebind");
|
|
645
|
+
json(res, 200, { ...out, charter: await note });
|
|
646
|
+
});
|
|
548
647
|
// ── wizard ↔ wizard + 流水线 ───────────────────────────────────────
|
|
549
648
|
// 这组路由让一个 pane 里的 wizard 作用到它的**同伴**身上。MCP 工具只看得见自己那个
|
|
550
649
|
// 进程, 所以「另一个 wizard 在干嘛」「把这句话注入给它」只有守护进程答得了 ——
|
|
@@ -563,14 +662,14 @@ const main = async () => {
|
|
|
563
662
|
};
|
|
564
663
|
/** 聊天名候选只列与调用方同机器人的 —— 别的机器人的聊天名也是它的存在。指名别的机器人的聊天,
|
|
565
664
|
* 各路由一律走它们自己「认不出这个聊天」的分支 (同状态码同原话), 不说「那边有, 但归别人」。 */
|
|
566
|
-
const chatNamesFor = (self) => listChatNames(cfg).
|
|
665
|
+
const chatNamesFor = (self) => listChatNames(cfg).map((c) => c.name);
|
|
567
666
|
// ── Chat naming ────────────────────────────────────────────────────
|
|
568
667
|
// A WeCom chat's identity is a canonical principal such as `chat:wrkS…`.
|
|
569
668
|
// 聊天命名已下线 (2026-11-16): 一律用 principal 标识; chats{} 里的存量名仅作显示标签,
|
|
570
669
|
// 跨聊天参数直接收 principal (存量名仍能解析回来)。
|
|
571
670
|
http.register("POST /chats/list", async (req, res) => {
|
|
572
671
|
const { self } = await readPeerBody(req);
|
|
573
|
-
const roster = self ? m.chatRoster(self)
|
|
672
|
+
const roster = self ? m.chatRoster(self) : listChatNames(cfg).map((c) => ({ ...c, self: false, targets: [] }));
|
|
574
673
|
json(res, 200, {
|
|
575
674
|
ok: true,
|
|
576
675
|
self,
|
|
@@ -615,7 +714,7 @@ const main = async () => {
|
|
|
615
714
|
// 的会话; 引导状态机不动, 人下一句话会重起一个干净的引导化身接着引导。别人冲着引导化身来的
|
|
616
715
|
// (替它 handoff / 给它设工作区) 只拒不收 (reap=false): 越权的不是它。
|
|
617
716
|
const refuseGuide = (res, target, action, reap = true) => {
|
|
618
|
-
const reason =
|
|
717
|
+
const reason = faceRefusal(wizardStore()?.get(target), action);
|
|
619
718
|
if (!reason)
|
|
620
719
|
return false;
|
|
621
720
|
json(res, 403, { ok: false, reason });
|
|
@@ -626,6 +725,15 @@ const main = async () => {
|
|
|
626
725
|
notifyChat(baseOfKey(target), "[wezard] 引导会话越权调用了 " + action + ", 已收掉; 请再发一次上一条, 引导会重新接上。");
|
|
627
726
|
return true;
|
|
628
727
|
};
|
|
728
|
+
/** monitor 的工具面硬限 (wizard.ts monitorRefusal): 审批层已全拒, 审批关掉时在这里兜一道。 */
|
|
729
|
+
const refuseMonitor = (res, target, action) => {
|
|
730
|
+
const reason = faceRefusal(wizardStore()?.get(target), action);
|
|
731
|
+
if (!reason)
|
|
732
|
+
return false;
|
|
733
|
+
json(res, 403, { ok: false, reason });
|
|
734
|
+
log.warn({ target, action }, "monitor tool surface refused");
|
|
735
|
+
return true;
|
|
736
|
+
};
|
|
629
737
|
// wizard 在群里的称呼, 只用在**正文**里。气泡的头照旧交给 withTagHeader ——
|
|
630
738
|
// 那一段是路由信息 (`.name:` / 签名名 / role 链接头), parseTagHeader 靠它反解, 群里引用一条气泡
|
|
631
739
|
// 就能直接跟那个 wizard 说话; 把它换成名字会把这条通路弄断。
|
|
@@ -635,13 +743,34 @@ const main = async () => {
|
|
|
635
743
|
};
|
|
636
744
|
/** 以 `self` 的名义往 `dest` 群发一条: 头独占一行; 头怎么写 (群默认 wizard 报不报名) 归 ownHead。 */
|
|
637
745
|
const postAs = (self, dest, text) => notifyChat(dest, headed(ownHead(self), text, "\n\n"));
|
|
638
|
-
/**
|
|
639
|
-
*
|
|
640
|
-
const postAsTopic = (self, dest, text,
|
|
746
|
+
/** 同 postAs, 但去到的是频道 room (chat:<topic_id>) —— 一律发新帖 (send_post)。
|
|
747
|
+
* 频道 / 帖子直连 send_post / send_reply, 绕过 tracker, 署名收尾 (withBubbleFooter) 得自己补。 */
|
|
748
|
+
const postAsTopic = (self, dest, text, media) => {
|
|
641
749
|
const topicId = dest.replace(/^chat:/, "");
|
|
642
|
-
void
|
|
750
|
+
void sendTopicPost(ws.client, log.child({ mod: "channel" }), topicId, linkTags(dest, withBubbleFooter(headed(ownHead(self), text, "\n\n"), self)), media)
|
|
643
751
|
.catch((e) => log.warn({ topicId, err: errText(e) }, "channel tool send failed"));
|
|
644
752
|
};
|
|
753
|
+
/** 回话的引用标注: 评论被拒回退成新帖时, 让人知道这条在回谁的原话 (企微只允许评论 @ 过 bot 的帖子)。 */
|
|
754
|
+
const replyQuote = (row) => {
|
|
755
|
+
const s = roomState(row.room);
|
|
756
|
+
const src = (row.re ?? []).map((id) => s?.byId.get(id)).find((r) => r?.author.kind === "human");
|
|
757
|
+
const text = src ? src.text.replace(/\s+/g, " ").trim() : "";
|
|
758
|
+
if (!text)
|
|
759
|
+
return "";
|
|
760
|
+
return "> 回 " + roomNameOf(src.author) + ": " + text.slice(0, 80) + (text.length > 80 ? "…" : "") + "\n\n";
|
|
761
|
+
};
|
|
762
|
+
/** 频道 room 的回话: 评论回原帖; 被企微拒 (没 @ 过 bot 的帖子) 回退发新帖, 正文带引用标注。 */
|
|
763
|
+
const postAsChannelReply = (self, dest, post, text, quote, media) => {
|
|
764
|
+
const topicId = dest.replace(/^chat:/, "");
|
|
765
|
+
const full = linkTags(dest, withBubbleFooter(headed(ownHead(self), text, "\n\n"), self));
|
|
766
|
+
void sendTopicReplyOrPost(ws.client, log.child({ mod: "channel" }), topicId, post, full, quote ? quote + full : full, media)
|
|
767
|
+
.catch((e) => log.warn({ topicId, post, err: errText(e) }, "channel post reply failed"));
|
|
768
|
+
};
|
|
769
|
+
/** 帖子 room (chat:<opk…>) —— 一律评论到根帖 (send_reply)。 */
|
|
770
|
+
const postAsReply = (self, dest, channel, post, text, media) => {
|
|
771
|
+
void sendTopicReply(ws.client, log.child({ mod: "channel" }), channel, post, linkTags(dest, withBubbleFooter(headed(ownHead(self), text, "\n\n"), self)), media)
|
|
772
|
+
.catch((e) => log.warn({ channel, post, err: errText(e) }, "channel post reply failed"));
|
|
773
|
+
};
|
|
645
774
|
const retiringWizardTargets = new Set();
|
|
646
775
|
const plans = (() => {
|
|
647
776
|
try {
|
|
@@ -771,11 +900,6 @@ const main = async () => {
|
|
|
771
900
|
const clash = asked ? wizards.byName(asked) : undefined;
|
|
772
901
|
if (clash?.spawning)
|
|
773
902
|
return { ok: false, status: 409, body: { ok: false, reason: "wizard is being spawned", name: clash.name } };
|
|
774
|
-
// 名字全机唯一, 撞上别的机器人的 wizard 照样拒 —— 但不顶掉它、不复用它的槽, 也不报它的死活:
|
|
775
|
-
// 那边的 wizard 在这个机器人眼里不存在, 只剩「名字被占了」这一个事实。
|
|
776
|
-
if (clash && !sameBot(base, clash.target)) {
|
|
777
|
-
return { ok: false, status: 409, body: { ok: false, reason: `名字 '.${clash.name}' 已被占用 (名字全局唯一) —— 换个名字`, name: clash.name } };
|
|
778
|
-
}
|
|
779
903
|
if (clash && !allowed(clash.target, clash.name))
|
|
780
904
|
return { ok: false, status: 409, body: { ok: false, reason: "wizard identity changed during slot claim" } };
|
|
781
905
|
const bound = !!clash && m.chatTargets(baseOfKey(clash.target)).includes(clash.target);
|
|
@@ -1122,12 +1246,30 @@ const main = async () => {
|
|
|
1122
1246
|
const reconciled = reconcileKin(wizards);
|
|
1123
1247
|
if (reconciled > 0)
|
|
1124
1248
|
log.child({ mod: "wizard" }).info({ reconciled }, "identity kin reconciled");
|
|
1249
|
+
// 存量名册补 tier / 修掉过期的 tier (聪明度只认它): 按此刻记下的模型 + effort 反查档位表。
|
|
1250
|
+
// 只写反查得出的结果 —— 表外模型 (kimi 之类) 不覆盖原值, 原记录仍是唯一证据。幂等。
|
|
1251
|
+
{
|
|
1252
|
+
let fixed = 0;
|
|
1253
|
+
for (const rec of wizards.all()) {
|
|
1254
|
+
const info = m.sessionInfo(rec.target);
|
|
1255
|
+
if (!info?.model.trim())
|
|
1256
|
+
continue;
|
|
1257
|
+
const probe = tierOfModel(cfg, info.cli, info.model, info.effort, rec.tier);
|
|
1258
|
+
if (probe.tier && probe.tier !== rec.tier) {
|
|
1259
|
+
wizards.upsert(rec.target, { tier: probe.tier });
|
|
1260
|
+
fixed += 1;
|
|
1261
|
+
}
|
|
1262
|
+
}
|
|
1263
|
+
if (fixed)
|
|
1264
|
+
log.child({ mod: "wizard" }).info({ fixed }, "tier backfilled from model + tiers table");
|
|
1265
|
+
}
|
|
1125
1266
|
// ── room 账本 (docs/room/wiring.md A): hub 实例化 + /room/* HTTP ──────
|
|
1126
1267
|
// room 是唯一的沟通对象: 人话 (inbound) 与 wizard 工具都 append 进同一份账本
|
|
1127
1268
|
// (daemon/room-hub.ts), 唤醒按 seen 游标重算, 镜像按 §3a 一条规则。旧的路由 /
|
|
1128
1269
|
// 事件表这一步还并行活着 (B/C 节再拆), 这里只把新面接上。
|
|
1129
1270
|
const roomsDir = roomsDirOf(cfg.daemon.stateDir);
|
|
1130
1271
|
const roomStore = openRoomStore(roomsDir);
|
|
1272
|
+
roomOfHashHook = (h) => roomStore.roomByHash(h);
|
|
1131
1273
|
/** 损坏的 room 文件 (RoomBroken) 不挡 boot, 也不参与任何判定 —— 只记一行。 */
|
|
1132
1274
|
const roomState = (id) => {
|
|
1133
1275
|
try {
|
|
@@ -1208,12 +1350,14 @@ const main = async () => {
|
|
|
1208
1350
|
};
|
|
1209
1351
|
const roomNameOf = (w) => w.kind === "wizard" ? "." + (roomWizardOf(w.id)?.name ?? w.id)
|
|
1210
1352
|
: w.kind === "human" ? w.id
|
|
1211
|
-
: "wezard";
|
|
1353
|
+
: (extNameOf(w) ? extLabel(extNameOf(w)) : "wezard");
|
|
1212
1354
|
const roomLabel = (room) => {
|
|
1213
1355
|
// host 起的名字是显式别名, 优先于聊天名与成员拼名 (对 dm 也生效; 只影响显示, 寻址仍只认 id)。
|
|
1214
1356
|
const s = roomState(room);
|
|
1215
1357
|
if (s?.title)
|
|
1216
1358
|
return s.title;
|
|
1359
|
+
if (isMeRoom(room))
|
|
1360
|
+
return (chatNameOf(cfg, "user:" + meUserOf(room)) || meUserOf(room)) + " 的 me";
|
|
1217
1361
|
if (room.startsWith("dm:")) {
|
|
1218
1362
|
const pair = dmPeers(room);
|
|
1219
1363
|
if (!pair)
|
|
@@ -1227,11 +1371,75 @@ const main = async () => {
|
|
|
1227
1371
|
return memberLabel([...(s?.members.values() ?? [])].map((x) => roomNameOf(x.who))) || room;
|
|
1228
1372
|
return chatNameOf(cfg, room) || room;
|
|
1229
1373
|
};
|
|
1374
|
+
/** 频道 room 判据: 进程内见过的 topic (事件登记) **或** channel-posts 认识且没有根帖的频道。
|
|
1375
|
+
* 只看 isTopicChat 不够 —— reload 后 topics 是空的, 频道 room 会被当成帖子 room, 出站走
|
|
1376
|
+
* send_reply(post_id="") 被企微 40058 拒掉 (2026-11-24 实测: send_file 进频道首条即此)。 */
|
|
1377
|
+
const isChannelRoom = (base) => {
|
|
1378
|
+
if (isTopicChat(base))
|
|
1379
|
+
return true;
|
|
1380
|
+
const ref = channelRefOf(cfg, base);
|
|
1381
|
+
return !!ref && !ref.post;
|
|
1382
|
+
};
|
|
1230
1383
|
/** 绑定 room 的镜像出站 (§3a): 覆盖占位 > 媒体 > topic 评论 > wx > 群消息。
|
|
1231
1384
|
* 返回 true = 已成功交给传输 (hub 拿它打 O3 的 room: mirrored; 内部失败各路径自己 warn)。 */
|
|
1232
1385
|
const roomMirror = async (row, cover) => {
|
|
1386
|
+
// me-room 出站: 占位气泡覆盖 (回发生地) > 文件/正文兜底发用户私聊; 带 .me 独立对话标注。
|
|
1387
|
+
if (isMeRoom(row.room)) {
|
|
1388
|
+
return meRowMirror(row, cover, {
|
|
1389
|
+
authorTargetOf: (u) => roomWizardOf(u)?.target,
|
|
1390
|
+
coverBubble,
|
|
1391
|
+
sendMedia: (principal, f) => sendMedia(principal, f),
|
|
1392
|
+
notify: (principal, md) => notifyChat(principal, md),
|
|
1393
|
+
rowById: (room, id) => roomState(room)?.byId.get(id),
|
|
1394
|
+
// 人被 .me 点名的位置是频道 / 帖子 (那行带 src): 评论回那条原帖, 被企微拒就回退
|
|
1395
|
+
// 发新帖并带引用标注 (人 2026-11-24 拍板) —— 不再把答案发去私聊。
|
|
1396
|
+
replyToSource: async (r, said, md) => {
|
|
1397
|
+
const base = said.src ?? "";
|
|
1398
|
+
const ref = channelRefOf(cfg, base);
|
|
1399
|
+
const topicId = ref ? ref.channel : isChannelRoom(base) ? base.slice("chat:".length) : "";
|
|
1400
|
+
if (!topicId)
|
|
1401
|
+
return false;
|
|
1402
|
+
const postId = said.post || ref?.post || "";
|
|
1403
|
+
let topicMedia;
|
|
1404
|
+
if (r.files?.length) {
|
|
1405
|
+
const imageIds = [];
|
|
1406
|
+
const inline = [];
|
|
1407
|
+
for (const f of r.files) {
|
|
1408
|
+
const up = await uploadMediaId(ws.client, base, { path: f.path, kind: f.kind, name: f.name }, log);
|
|
1409
|
+
if (!up.ok) {
|
|
1410
|
+
log.warn({ mod: "room", room: r.room, file: f.path, reason: up.reason }, "me: 频道素材上传失败 (只影响传输, 不回滚)");
|
|
1411
|
+
continue;
|
|
1412
|
+
}
|
|
1413
|
+
if (up.kind === "image")
|
|
1414
|
+
imageIds.push(up.mediaId);
|
|
1415
|
+
else
|
|
1416
|
+
inline.push({ mediaId: up.mediaId, name: up.name });
|
|
1417
|
+
}
|
|
1418
|
+
if (imageIds.length || inline.length)
|
|
1419
|
+
topicMedia = { ...(imageIds.length ? { imageIds } : {}), ...(inline.length ? { files: inline } : {}) };
|
|
1420
|
+
}
|
|
1421
|
+
const full = withBubbleFooter(linkTags(r.room, md), r.room);
|
|
1422
|
+
const quote = replyQuote(r);
|
|
1423
|
+
const child = log.child({ mod: "channel" });
|
|
1424
|
+
// 频道帖子的正文 (没有 post 可评论) / 帖子 room 认不出根帖: 直接发新帖。
|
|
1425
|
+
if (!postId) {
|
|
1426
|
+
void sendTopicPost(ws.client, child, topicId, quote ? quote + full : full, topicMedia)
|
|
1427
|
+
.catch((e) => log.warn({ mod: "room", room: r.room, topicId, err: errText(e) }, "me: 频道发帖失败"));
|
|
1428
|
+
}
|
|
1429
|
+
else {
|
|
1430
|
+
void sendTopicReplyOrPost(ws.client, child, topicId, postId, full, quote ? quote + full : full, topicMedia)
|
|
1431
|
+
.catch((e) => log.warn({ mod: "room", room: r.room, topicId, postId, err: errText(e) }, "me: 评论回原帖失败"));
|
|
1432
|
+
}
|
|
1433
|
+
return true;
|
|
1434
|
+
},
|
|
1435
|
+
});
|
|
1436
|
+
}
|
|
1233
1437
|
const chat = row.room;
|
|
1234
|
-
|
|
1438
|
+
// 出站目标源 (设计稿 §4.2): reply 跟所 re 那行的 src (缺省 = 主源), say / file / notify 回主源。
|
|
1439
|
+
// src 缺省路径 = out === chat = 现行为, 存量账本一比特不变。
|
|
1440
|
+
const { source: out, fellBack } = outboundSourceOf(row, (id) => roomState(chat)?.byId.get(id));
|
|
1441
|
+
if (fellBack)
|
|
1442
|
+
log.warn({ mod: "room", room: chat, re: row.re }, "room: reply 的 re 在本 room 账本里查不到, 出站回落主源");
|
|
1235
1443
|
const authorTarget = row.author.kind === "wizard" ? roomWizardOf(row.author.id)?.target : undefined;
|
|
1236
1444
|
const plain = row.text.trim() || (row.files?.length ? "📎 " + row.files.map((f) => f.name).join(", ") : "");
|
|
1237
1445
|
// 收话人: 显式点名的 wizard (to) + 被答复那条消息的 wizard 作者 (re), 去掉自己与重复。
|
|
@@ -1243,14 +1451,46 @@ const main = async () => {
|
|
|
1243
1451
|
// 头像 / 尾部署名都由 tracker 从正文头反解 —— 覆盖占位气泡也必须带这个头,
|
|
1244
1452
|
// 否则那条气泡既没有身份也没有 rolepage 链接 (它就是人点名的那个 wizard 的答复)。
|
|
1245
1453
|
const md = roomBubble(authorTarget, body);
|
|
1246
|
-
|
|
1454
|
+
// 占位气泡盖在人话行的发生源上; 与这行的目标源不是同一个就不盖 (退回普通发送, 流由 hardTimer 收口)。
|
|
1455
|
+
if (cover?.ext && body && bubbleSourceOf(cover) === out) {
|
|
1247
1456
|
if (await coverBubble(cover.ext, md))
|
|
1248
1457
|
return true;
|
|
1249
1458
|
}
|
|
1250
|
-
|
|
1459
|
+
const plan = planOutbound(out, row, {
|
|
1460
|
+
wxOwns: (id) => wx.owns(id),
|
|
1461
|
+
isTopic: isChannelRoom,
|
|
1462
|
+
postRefOf: (base) => postRefOf(cfg, base),
|
|
1463
|
+
channelAction: (r) => channelOutboundOf(r, (id) => roomState(chat)?.byId.get(id)?.post),
|
|
1464
|
+
});
|
|
1465
|
+
// 频道 / 帖子没有群 chatid: 素材先换 media_id, 随 send_post / send_reply 的
|
|
1466
|
+
// image_list (图片) / inline_file_list (其余) 一起带 —— 直接用 sendMediaMessage 发到
|
|
1467
|
+
// 那里只会被频道出站补丁当「不支持的 msgtype」丢掉 (channel.ts)。
|
|
1468
|
+
const toTopic = plan.via === "channel" || plan.via === "post";
|
|
1469
|
+
let topicMedia;
|
|
1470
|
+
if (row.files?.length && toTopic) {
|
|
1471
|
+
const imageIds = [];
|
|
1472
|
+
const inline = [];
|
|
1473
|
+
for (const f of row.files) {
|
|
1474
|
+
const up = await uploadMediaId(ws.client, out, { path: f.path, kind: f.kind, name: f.name }, log);
|
|
1475
|
+
if (!up.ok) {
|
|
1476
|
+
log.warn({ mod: "room", room: chat, file: f.path, reason: up.reason }, "room: 频道素材上传失败 (只影响传输, 不回滚)");
|
|
1477
|
+
continue;
|
|
1478
|
+
}
|
|
1479
|
+
if (up.kind === "image")
|
|
1480
|
+
imageIds.push(up.mediaId);
|
|
1481
|
+
else
|
|
1482
|
+
inline.push({ mediaId: up.mediaId, name: up.name });
|
|
1483
|
+
}
|
|
1484
|
+
if (imageIds.length || inline.length) {
|
|
1485
|
+
topicMedia = { ...(imageIds.length ? { imageIds } : {}), ...(inline.length ? { files: inline } : {}) };
|
|
1486
|
+
}
|
|
1487
|
+
if (!body && !topicMedia)
|
|
1488
|
+
return false;
|
|
1489
|
+
}
|
|
1490
|
+
else if (row.files?.length) {
|
|
1251
1491
|
let filesOk = true;
|
|
1252
1492
|
for (const f of row.files) {
|
|
1253
|
-
const r = await sendMedia(
|
|
1493
|
+
const r = await sendMedia(out, { path: f.path, kind: f.kind, name: f.name, ...(row.text.trim() ? { description: row.text } : {}) });
|
|
1254
1494
|
if (!r.ok) {
|
|
1255
1495
|
filesOk = false;
|
|
1256
1496
|
log.warn({ mod: "room", room: chat, file: f.path, reason: r.reason }, "room: 镜像媒体发送失败 (只影响传输, 不回滚)");
|
|
@@ -1259,31 +1499,56 @@ const main = async () => {
|
|
|
1259
1499
|
if (!body)
|
|
1260
1500
|
return filesOk;
|
|
1261
1501
|
}
|
|
1262
|
-
if (wx
|
|
1263
|
-
const r = wx.sendFinal(chatId, wxMarkdown(md), row.id);
|
|
1502
|
+
if (plan.via === "wx") {
|
|
1503
|
+
const r = wx.sendFinal(plan.chatId, wxMarkdown(md), row.id);
|
|
1264
1504
|
if (r.state === "failed") {
|
|
1265
|
-
log.warn({ mod: "room", room: chat, reason: r.reason }, "room: wx 镜像失败");
|
|
1505
|
+
log.warn({ mod: "room", room: chat, src: out, reason: r.reason }, "room: wx 镜像失败");
|
|
1266
1506
|
return false;
|
|
1267
1507
|
}
|
|
1268
1508
|
return true;
|
|
1269
1509
|
}
|
|
1270
|
-
if (
|
|
1510
|
+
if (plan.via === "channel") {
|
|
1511
|
+
// 频道: 回话 (reply 且 re 到带 post 的评论行) = 评论回原帖; 主动说 = 新帖 (§2.3)。
|
|
1512
|
+
if (plan.action === "reply") {
|
|
1513
|
+
// 企微只允许评论 @ 过 bot 的帖子; 被拒就回退新帖 (带引用), 不让交代静默丢失。
|
|
1514
|
+
const quote = replyQuote(row);
|
|
1515
|
+
const post = plan.post ?? "";
|
|
1516
|
+
if (authorTarget)
|
|
1517
|
+
postAsChannelReply(authorTarget, out, post, body, quote, topicMedia);
|
|
1518
|
+
else {
|
|
1519
|
+
const full = withBubbleFooter(linkTags(out, md), out);
|
|
1520
|
+
void sendTopicReplyOrPost(ws.client, log.child({ mod: "room" }), plan.topicId, post, full, quote ? quote + full : full, topicMedia)
|
|
1521
|
+
.catch((e) => log.warn({ mod: "room", room: chat, src: out, post, err: errText(e) }, "room: topic 评论回帖失败"));
|
|
1522
|
+
}
|
|
1523
|
+
return true;
|
|
1524
|
+
}
|
|
1271
1525
|
if (authorTarget)
|
|
1272
|
-
postAsTopic(authorTarget,
|
|
1526
|
+
postAsTopic(authorTarget, out, body, topicMedia);
|
|
1273
1527
|
else
|
|
1274
|
-
void
|
|
1275
|
-
.catch((e) => log.warn({ mod: "room", room: chat, err: errText(e) }, "room: topic 镜像失败"));
|
|
1528
|
+
void sendTopicPost(ws.client, log.child({ mod: "room" }), plan.topicId, withBubbleFooter(linkTags(out, md), out), topicMedia)
|
|
1529
|
+
.catch((e) => log.warn({ mod: "room", room: chat, src: out, err: errText(e) }, "room: topic 镜像失败"));
|
|
1276
1530
|
return true; // 已交给传输; 异步失败由上面的 catch 记 warn
|
|
1277
1531
|
}
|
|
1532
|
+
if (plan.via === "post") {
|
|
1533
|
+
// 帖子: 一律评论到根帖 (副源帖子 = 绑进本 room 的那条帖; 企微侧地址仍查 channel-posts)。
|
|
1534
|
+
if (authorTarget)
|
|
1535
|
+
postAsReply(authorTarget, out, plan.channel, plan.post, body, topicMedia);
|
|
1536
|
+
else
|
|
1537
|
+
void sendTopicReply(ws.client, log.child({ mod: "room" }), plan.channel, plan.post, withBubbleFooter(linkTags(out, md), out), topicMedia)
|
|
1538
|
+
.catch((e) => log.warn({ mod: "room", room: chat, src: out, err: errText(e) }, "room: post 镜像失败"));
|
|
1539
|
+
return true;
|
|
1540
|
+
}
|
|
1278
1541
|
if (authorTarget)
|
|
1279
|
-
postAs(authorTarget,
|
|
1542
|
+
postAs(authorTarget, out, body);
|
|
1280
1543
|
else
|
|
1281
|
-
notifyChat(
|
|
1544
|
+
notifyChat(out, md);
|
|
1282
1545
|
return true;
|
|
1283
1546
|
};
|
|
1284
1547
|
const roomLog = log.child({ mod: "room" });
|
|
1285
1548
|
const hub = createRoomHub({
|
|
1286
1549
|
store: roomStore, log: roomLog,
|
|
1550
|
+
// 短 id 补全的依据: 每一批成功投递过哪些行, 落 stateDir (轮终 / reload 后仍能反查)。
|
|
1551
|
+
deliveryLog: openShortIdLog(join(expandHome(cfg.daemon.stateDir), "short-id-deliveries.json")),
|
|
1287
1552
|
wizardOf: roomWizardOf, nameOf: roomNameOf, roomLabel,
|
|
1288
1553
|
mirror: roomMirror,
|
|
1289
1554
|
live: (target) => m.paneAliveFor(target),
|
|
@@ -1296,6 +1561,8 @@ const main = async () => {
|
|
|
1296
1561
|
onClosed: () => settleLeads(),
|
|
1297
1562
|
replyHintWindow: () => cfg.rooms?.replyHint?.window ?? 10,
|
|
1298
1563
|
tailOf: (target, triggers) => humanWakeTail(wakeTailPorts(cfg, m), target, triggers),
|
|
1564
|
+
// 感知懒建 (2026-11-24): 人话需要感知而本 room 还没有 perceptron 时, append 先建再判 (见 ensurePerceptron)。
|
|
1565
|
+
ensurePerceptron: (room) => { ensurePerceptron(room); },
|
|
1299
1566
|
paste: async (target, text, tail) => {
|
|
1300
1567
|
const r = await m.injectText(target, text, wakeInjectOpts(tail));
|
|
1301
1568
|
if (r.ok)
|
|
@@ -1303,6 +1570,90 @@ const main = async () => {
|
|
|
1303
1570
|
return r.ok ? "ok" : r.uncertain ? "uncertain" : r.gone ? "gone" : "failed";
|
|
1304
1571
|
},
|
|
1305
1572
|
});
|
|
1573
|
+
// 外部 agent (CoC) 接入: 每个调用方一间 adhoc room, 请求 = 一条 ask 行, 状态从账本现算。
|
|
1574
|
+
// 路由只挂在控制面 socket (视图口按规则 410); 口令按调用方一个文件, boot / 配置热载时补齐。
|
|
1575
|
+
const external = createExternal({
|
|
1576
|
+
cfg: () => cfg, log: log.child({ mod: "external" }), store: roomStore,
|
|
1577
|
+
append: (room, d) => hub.append(room, d),
|
|
1578
|
+
write: (room, ops) => hub.write(room, ops),
|
|
1579
|
+
findWizard: (name) => {
|
|
1580
|
+
const rec = wizards.byName(name);
|
|
1581
|
+
return rec?.uid ? { uid: rec.uid, name: rec.name || name, target: rec.target } : undefined;
|
|
1582
|
+
},
|
|
1583
|
+
// 首连登记 (第 3 步): 卡发审批人私聊 (频道 home 发卡会 93006), 批准后才落登记表与接待 wizard。
|
|
1584
|
+
approver: () => wxAdmins(cfg)[0] ?? "",
|
|
1585
|
+
confirm: async (a) => {
|
|
1586
|
+
// 演练口子: WEZARD_TEST_ENROLL_DECIDE 指向一个决定文件 ("yes" / "no"), 读到就消费掉;
|
|
1587
|
+
// 生产不设这个环境变量, 走的就是 requestConfirm, 行为不变。
|
|
1588
|
+
const decideFile = process.env.WEZARD_TEST_ENROLL_DECIDE?.trim() || "";
|
|
1589
|
+
if (decideFile) {
|
|
1590
|
+
const decided = new Promise((resolve) => {
|
|
1591
|
+
const t0 = Date.now();
|
|
1592
|
+
const tick = () => {
|
|
1593
|
+
let v = "";
|
|
1594
|
+
try {
|
|
1595
|
+
v = readFileSync(decideFile, "utf8").trim();
|
|
1596
|
+
}
|
|
1597
|
+
catch {
|
|
1598
|
+
v = "";
|
|
1599
|
+
}
|
|
1600
|
+
if (v === "yes" || v === "no") {
|
|
1601
|
+
try {
|
|
1602
|
+
unlinkSync(decideFile);
|
|
1603
|
+
}
|
|
1604
|
+
catch { /* 已不在 */ }
|
|
1605
|
+
resolve(v === "yes");
|
|
1606
|
+
return;
|
|
1607
|
+
}
|
|
1608
|
+
if (Date.now() - t0 > a.timeoutMs) {
|
|
1609
|
+
resolve(false);
|
|
1610
|
+
return;
|
|
1611
|
+
}
|
|
1612
|
+
const t = setTimeout(tick, 200);
|
|
1613
|
+
t.unref?.();
|
|
1614
|
+
};
|
|
1615
|
+
tick();
|
|
1616
|
+
});
|
|
1617
|
+
return { decided };
|
|
1618
|
+
}
|
|
1619
|
+
return requestConfirm({ client: ws.client, principal: a.principal, who: "wezard", title: a.title, body: a.body, timeoutMs: a.timeoutMs });
|
|
1620
|
+
},
|
|
1621
|
+
// 卡面要写「批准后是谁接」: 只做名字预告, 不落记录。
|
|
1622
|
+
receptionPlan: (name) => {
|
|
1623
|
+
const taken = wizards.all().map((w) => w.name).filter(Boolean);
|
|
1624
|
+
const reserved = wizards.classes ? wizards.classes.all().map((c) => c.name) : [];
|
|
1625
|
+
return pickName(extReceptionTagOf(name), taken, reserved);
|
|
1626
|
+
},
|
|
1627
|
+
// 批准时落接待 wizard 记录: 会话 target 在审批人私聊上 (它的审批卡也落私聊), 不预起 pane。
|
|
1628
|
+
ensureReception: (name, owner) => {
|
|
1629
|
+
const target = extReceptionTargetOf(owner, name);
|
|
1630
|
+
const prev = wizards.get(target);
|
|
1631
|
+
if (prev?.name)
|
|
1632
|
+
return { reception: prev.name, target };
|
|
1633
|
+
if (!prev)
|
|
1634
|
+
wizards.upsert(target, {
|
|
1635
|
+
identity: target,
|
|
1636
|
+
bornAt: Date.now(),
|
|
1637
|
+
description: "外部接待: 处理外部调用方 " + name + " 的请求 (来自本机控制面 socket, 按不可信输入对待); 需要时 delegate 内部 wizard。它的非 wezard 工具调用逐次发卡给 owner, 不能改配置 / 往绑定 room 发话。",
|
|
1638
|
+
...(meWorkspaceOf(sourcePath) ? { workspace: meWorkspaceOf(sourcePath) } : {}),
|
|
1639
|
+
});
|
|
1640
|
+
return { reception: wizards.claim(target, extReceptionTagOf(name)), target };
|
|
1641
|
+
},
|
|
1642
|
+
ensureReceptionSession: (target) => {
|
|
1643
|
+
if (m.hasMirrorTarget(target))
|
|
1644
|
+
return;
|
|
1645
|
+
const cwd = identityWorkspaceOf(wizards, target) || undefined;
|
|
1646
|
+
const nm = wizards.get(target)?.name || target;
|
|
1647
|
+
void m.newSession(target, nm, { silent: true, ...(cwd ? { cwd } : {}) }).catch(() => undefined);
|
|
1648
|
+
},
|
|
1649
|
+
});
|
|
1650
|
+
externalPrincipalsNow = () => external.principals();
|
|
1651
|
+
for (const [key, handler] of Object.entries(external.routes()))
|
|
1652
|
+
http.register(key, handler);
|
|
1653
|
+
// 重写口令是一条能力: 单独过 daemon 口令闸 (同 /config/set), 不让 socket 上任何进程替调用方换口令。
|
|
1654
|
+
http.register("POST /external/rotate", guarded(external.rotateRoute()));
|
|
1655
|
+
http.register("GET /external/status", guarded(external.statusRoute()));
|
|
1656
|
+
external.syncTokens();
|
|
1306
1657
|
// boot 摘 lead: leadOf 全关了的, 以及没有 leadOf 的老 lead 名下已无同伴的活 (2026-11-22 admin 选 B)。
|
|
1307
1658
|
try {
|
|
1308
1659
|
settleLeads(true);
|
|
@@ -1408,18 +1759,27 @@ const main = async () => {
|
|
|
1408
1759
|
const uid = wizards.get(target)?.uid;
|
|
1409
1760
|
return uid ? { kind: "wizard", id: uid } : undefined;
|
|
1410
1761
|
};
|
|
1411
|
-
/** room 参数: room id 原样, 或聊天名 (chatBaseOf)。 */
|
|
1762
|
+
/** room 参数: room id 原样, 或聊天名 (chatBaseOf), 或注入头里的 #hash8 (可省 #)。 */
|
|
1412
1763
|
const roomResolve = (ref) => {
|
|
1413
1764
|
const raw = (ref ?? "").trim();
|
|
1414
1765
|
if (!raw)
|
|
1415
1766
|
return {};
|
|
1416
1767
|
if (roomState(raw))
|
|
1417
1768
|
return { room: raw };
|
|
1769
|
+
// #hash8: 注入头 / 消息 id 前缀的简写。撞车 = 有歧义, 不猜。
|
|
1770
|
+
const byHash = resolveHashRef(roomStore, raw);
|
|
1771
|
+
if (byHash)
|
|
1772
|
+
return "room" in byHash ? byHash : { error: byHash.error };
|
|
1418
1773
|
const base = chatBaseOf(cfg, raw);
|
|
1419
1774
|
if (base && base !== raw && roomState(base))
|
|
1420
1775
|
return { room: base };
|
|
1421
1776
|
return { error: "认不出这个 room: " + raw };
|
|
1422
1777
|
};
|
|
1778
|
+
/** 短 id 补全的调用口: 候选 room 来自「最近投递记录」(轮终 / reload 后仍在, 见 daemon/short-id-log)。 */
|
|
1779
|
+
const expandMsgRefs = (self, ids) => {
|
|
1780
|
+
const uid = wizards.get(self)?.uid;
|
|
1781
|
+
return sharedExpandRefs(ids, (id) => (uid && /^\d+$/.test(id) ? hub.msgRoomsOfSeq(uid, Number(id)) : []));
|
|
1782
|
+
};
|
|
1423
1783
|
/** 名字 (带不带 .) / uid / human:<id> → Who。 */
|
|
1424
1784
|
const whoRefOf = (ref) => {
|
|
1425
1785
|
const raw = stripSigil((ref ?? "").trim());
|
|
@@ -1435,7 +1795,7 @@ const main = async () => {
|
|
|
1435
1795
|
return undefined;
|
|
1436
1796
|
};
|
|
1437
1797
|
/** 名册里已经没有的身份只剩一条成员行 (迁移 / 实例结束留下, 迁移带进来的无名成员就是这样):
|
|
1438
|
-
* 按地址找「本 room 的人」的路径 (room_leave
|
|
1798
|
+
* 按地址找「本 room 的人」的路径 (room_leave) 要能认出它, 否则它永远移不掉。
|
|
1439
1799
|
* 只认本 room 现有的成员 —— uid (可带 uid: 前缀) 优先, 其次成员显示名。 */
|
|
1440
1800
|
const memberRefOf = (s, ref) => {
|
|
1441
1801
|
const raw = stripSigil((ref ?? "").trim());
|
|
@@ -1522,9 +1882,10 @@ const main = async () => {
|
|
|
1522
1882
|
? "本轮被多个 room 一起唤醒 (" + d.many.map(roomLabel).join(", ") + ") — 显式给 room"
|
|
1523
1883
|
: "没有缺省 room (本轮没有被唤醒) — 显式给 room" };
|
|
1524
1884
|
};
|
|
1525
|
-
const roomReply = (res, v) => {
|
|
1885
|
+
const roomReply = (res, v, extra = {}) => {
|
|
1526
1886
|
if (v.ok)
|
|
1527
1887
|
json(res, 200, { ok: true, room: v.row.room, id: v.row.id, seq: v.row.seq, woke: v.row.wake,
|
|
1888
|
+
...extra,
|
|
1528
1889
|
...(v.row.closes?.length ? { closes: v.row.closes } : {}), ...(v.degraded.length ? { degraded: v.degraded } : {}),
|
|
1529
1890
|
...(v.duplicate ? { duplicate: true } : {}) });
|
|
1530
1891
|
else
|
|
@@ -1543,6 +1904,29 @@ const main = async () => {
|
|
|
1543
1904
|
json(res, 403, { ok: false, reason: "引导会话只在 " + baseOfKey(self) + " 里说话" });
|
|
1544
1905
|
return true;
|
|
1545
1906
|
};
|
|
1907
|
+
// ── 外部接待 wizard 的禁用表 (第 2 步 §1) ────────────────────────────
|
|
1908
|
+
// 判据是身份: 调用方解析到的 wizard 名 ∈ 启用中的 external.principals[].reception, 现查配置。
|
|
1909
|
+
// 拦在路由层 —— CodeBuddy 的调用都包在 REPL 脚本里, 只看外层工具名拦不住。
|
|
1910
|
+
/** 这个名字; 不是接待 wizard = undefined。 */
|
|
1911
|
+
const receptionNameOf = (self) => {
|
|
1912
|
+
if (!self)
|
|
1913
|
+
return undefined;
|
|
1914
|
+
const name = wizards.get(self)?.name || "";
|
|
1915
|
+
if (!name)
|
|
1916
|
+
return undefined;
|
|
1917
|
+
return external.principals().some((x) => x.enabled && x.reception === name) ? name : undefined;
|
|
1918
|
+
};
|
|
1919
|
+
/** true = 已回 403 (调用方该 return)。 */
|
|
1920
|
+
const refuseReception = (res, route, self, extra = {}) => {
|
|
1921
|
+
const name = receptionNameOf(self);
|
|
1922
|
+
if (!name)
|
|
1923
|
+
return false;
|
|
1924
|
+
const why = receptionDenial({ route, selfName: name, ...extra }, (r) => hub.isBoundRoom(r));
|
|
1925
|
+
if (!why)
|
|
1926
|
+
return false;
|
|
1927
|
+
json(res, 403, { ok: false, reason: why });
|
|
1928
|
+
return true;
|
|
1929
|
+
};
|
|
1546
1930
|
// ── /room/*: 发言与交付 ───────────────────────────────────────────────
|
|
1547
1931
|
http.register("POST /room/say", async (req, res) => {
|
|
1548
1932
|
const { self, body } = await readPeerBody(req);
|
|
@@ -1571,6 +1955,8 @@ const main = async () => {
|
|
|
1571
1955
|
}
|
|
1572
1956
|
if (guideOutsideRoom(res, self, target.room))
|
|
1573
1957
|
return;
|
|
1958
|
+
if (refuseReception(res, "POST /room/say", self, { rooms: [target.room] }))
|
|
1959
|
+
return;
|
|
1574
1960
|
roomReply(res, hub.append(target.room, { author: me, kind: "say", text, origin: "tool",
|
|
1575
1961
|
...(to?.who?.length ? { to: to.who } : {}), ...(b.interrupt ? { interrupt: true } : {}) }));
|
|
1576
1962
|
});
|
|
@@ -1603,13 +1989,26 @@ const main = async () => {
|
|
|
1603
1989
|
json(res, target.status ?? 400, { ok: false, reason: target.error ?? target.reason });
|
|
1604
1990
|
return;
|
|
1605
1991
|
}
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
const
|
|
1609
|
-
|
|
1992
|
+
if (refuseReception(res, "POST /room/ask", self, { rooms: [target.room] }))
|
|
1993
|
+
return;
|
|
1994
|
+
const afterRefs = expandMsgRefs(self, idList(b.after));
|
|
1995
|
+
if (afterRefs.error) {
|
|
1996
|
+
json(res, 400, { ok: false, reason: afterRefs.error });
|
|
1997
|
+
return;
|
|
1998
|
+
}
|
|
1999
|
+
const after = afterRefs.ids;
|
|
2000
|
+
// for 缺省 = 本轮唤醒它的那一条欠账 (血缘; 逾期计时靠它把子件的活动算进来)。显式给的已关账 → 同样回落。
|
|
2001
|
+
const { for: forOf, note: forNote } = hub.resolveForEx(me.id, b.for);
|
|
2002
|
+
const v = hub.append(target.room, { author: me, kind: b.kind === "task" ? "task" : "ask", text, origin: "tool", to: to.who,
|
|
1610
2003
|
...(after.length ? { after } : {}), ...(forOf ? { for: forOf } : {}),
|
|
1611
2004
|
...((b.planId ?? "").toString().trim() ? { planId: (b.planId ?? "").toString().trim() } : {}),
|
|
1612
|
-
...(b.interrupt ? { interrupt: true } : {}) })
|
|
2005
|
+
...(b.interrupt ? { interrupt: true } : {}) });
|
|
2006
|
+
// 回包里带落定的收件人名: 模型常把回包当对象直接读 `name` 去转述「已经交给 .X」,
|
|
2007
|
+
// 缺了它就写成 .undefined (2026-11-24 群里的实录)。
|
|
2008
|
+
const names = v.ok
|
|
2009
|
+
? (v.row.to ?? []).map((w) => w.kind === "wizard" ? peerAddress(cfg, wizards.byUid(w.id)?.target ?? w.id) : w.id).filter(Boolean)
|
|
2010
|
+
: [];
|
|
2011
|
+
roomReply(res, v, { ...(names.length === 1 ? { name: names[0], names } : names.length ? { names } : {}), ...(forNote ? { forNote } : {}) });
|
|
1613
2012
|
});
|
|
1614
2013
|
http.register("POST /room/reply", async (req, res) => {
|
|
1615
2014
|
const { self, body } = await readPeerBody(req);
|
|
@@ -1621,7 +2020,12 @@ const main = async () => {
|
|
|
1621
2020
|
return;
|
|
1622
2021
|
}
|
|
1623
2022
|
const b = body;
|
|
1624
|
-
const
|
|
2023
|
+
const refs = expandMsgRefs(self, idList(b.re));
|
|
2024
|
+
if (refs.error) {
|
|
2025
|
+
json(res, 400, { ok: false, reason: refs.error });
|
|
2026
|
+
return;
|
|
2027
|
+
}
|
|
2028
|
+
const re = refs.ids;
|
|
1625
2029
|
if (!re.length) {
|
|
1626
2030
|
json(res, 400, { ok: false, reason: "re required: 要答的那条 (或那几条) 消息 id" });
|
|
1627
2031
|
return;
|
|
@@ -1637,6 +2041,8 @@ const main = async () => {
|
|
|
1637
2041
|
}
|
|
1638
2042
|
if (guideOutsideRoom(res, self, rooms[0]))
|
|
1639
2043
|
return;
|
|
2044
|
+
if (refuseReception(res, "POST /room/reply", self, { rooms: rooms.filter((x) => !!x) }))
|
|
2045
|
+
return;
|
|
1640
2046
|
const status = (b.status ?? "").toString().trim();
|
|
1641
2047
|
if (status && !["done", "need", "progress", "passed", "canceled", "error"].includes(status)) {
|
|
1642
2048
|
json(res, 400, { ok: false, reason: "status 只认 done / need / progress / passed / canceled (error 只有 daemon 能写)" });
|
|
@@ -1678,6 +2084,8 @@ const main = async () => {
|
|
|
1678
2084
|
}
|
|
1679
2085
|
rooms.push(d.room);
|
|
1680
2086
|
}
|
|
2087
|
+
if (refuseReception(res, "POST /room/notify", self, { rooms }))
|
|
2088
|
+
return;
|
|
1681
2089
|
const out = [];
|
|
1682
2090
|
for (const room of rooms) {
|
|
1683
2091
|
const v = hub.append(room, { author: me, kind: "say", text: markdown, origin: "tool" });
|
|
@@ -1718,7 +2126,14 @@ const main = async () => {
|
|
|
1718
2126
|
json(res, target.status ?? 400, { ok: false, reason: target.error ?? target.reason });
|
|
1719
2127
|
return;
|
|
1720
2128
|
}
|
|
1721
|
-
|
|
2129
|
+
if (refuseReception(res, "POST /room/file", self, { rooms: [target.room] }))
|
|
2130
|
+
return;
|
|
2131
|
+
const fileRefs = expandMsgRefs(self, idList(b.re));
|
|
2132
|
+
if (fileRefs.error) {
|
|
2133
|
+
json(res, 400, { ok: false, reason: fileRefs.error });
|
|
2134
|
+
return;
|
|
2135
|
+
}
|
|
2136
|
+
const re = fileRefs.ids;
|
|
1722
2137
|
const text = [b.title, b.caption, b.description].map((x) => (x ?? "").toString().trim()).filter(Boolean).join(" — ");
|
|
1723
2138
|
roomReply(res, hub.append(target.room, { author: me, kind: "file", text, origin: "tool",
|
|
1724
2139
|
files: [{ path, kind, name: basename(path) }], ...(re.length ? { re } : {}) }));
|
|
@@ -1728,6 +2143,8 @@ const main = async () => {
|
|
|
1728
2143
|
const { self, body } = await readPeerBody(req);
|
|
1729
2144
|
if (READ_ROOM_FAIL(res, self))
|
|
1730
2145
|
return;
|
|
2146
|
+
if (refuseMonitor(res, self, "room_open"))
|
|
2147
|
+
return;
|
|
1731
2148
|
const me = roomSelfOf(self);
|
|
1732
2149
|
if (!me) {
|
|
1733
2150
|
json(res, 400, { ok: false, reason: "caller 不在名册上, 没有 uid" });
|
|
@@ -1776,6 +2193,10 @@ const main = async () => {
|
|
|
1776
2193
|
const { self, body } = await readPeerBody(req);
|
|
1777
2194
|
if (READ_ROOM_FAIL(res, self))
|
|
1778
2195
|
return;
|
|
2196
|
+
if (refuseMonitor(res, self, "room_name"))
|
|
2197
|
+
return;
|
|
2198
|
+
if (refuseReception(res, "POST /room/name", self))
|
|
2199
|
+
return;
|
|
1779
2200
|
const me = roomSelfOf(self);
|
|
1780
2201
|
if (!me) {
|
|
1781
2202
|
json(res, 400, { ok: false, reason: "caller 不在名册上, 没有 uid" });
|
|
@@ -1820,6 +2241,10 @@ const main = async () => {
|
|
|
1820
2241
|
const { self, body } = await readPeerBody(req);
|
|
1821
2242
|
if (READ_ROOM_FAIL(res, self))
|
|
1822
2243
|
return;
|
|
2244
|
+
if (refuseMonitor(res, self, "room_invite"))
|
|
2245
|
+
return;
|
|
2246
|
+
if (refuseReception(res, "POST /room/invite", self))
|
|
2247
|
+
return;
|
|
1823
2248
|
const me = roomSelfOf(self);
|
|
1824
2249
|
if (!me) {
|
|
1825
2250
|
json(res, 400, { ok: false, reason: "caller 不在名册上, 没有 uid" });
|
|
@@ -1871,6 +2296,8 @@ const main = async () => {
|
|
|
1871
2296
|
const { self, body } = await readPeerBody(req);
|
|
1872
2297
|
if (READ_ROOM_FAIL(res, self))
|
|
1873
2298
|
return;
|
|
2299
|
+
if (refuseMonitor(res, self, "room_join"))
|
|
2300
|
+
return;
|
|
1874
2301
|
const me = roomSelfOf(self);
|
|
1875
2302
|
if (!me) {
|
|
1876
2303
|
json(res, 400, { ok: false, reason: "caller 不在名册上, 没有 uid" });
|
|
@@ -1888,13 +2315,20 @@ const main = async () => {
|
|
|
1888
2315
|
const { self, body } = await readPeerBody(req);
|
|
1889
2316
|
if (READ_ROOM_FAIL(res, self))
|
|
1890
2317
|
return;
|
|
2318
|
+
if (refuseMonitor(res, self, "room_approve"))
|
|
2319
|
+
return;
|
|
1891
2320
|
const me = roomSelfOf(self);
|
|
1892
2321
|
if (!me) {
|
|
1893
2322
|
json(res, 400, { ok: false, reason: "caller 不在名册上, 没有 uid" });
|
|
1894
2323
|
return;
|
|
1895
2324
|
}
|
|
1896
2325
|
const b = body;
|
|
1897
|
-
const
|
|
2326
|
+
const approveRef = expandMsgRefs(self, [(b.re ?? "").toString().trim()]);
|
|
2327
|
+
if (approveRef.error) {
|
|
2328
|
+
json(res, 400, { ok: false, reason: approveRef.error });
|
|
2329
|
+
return;
|
|
2330
|
+
}
|
|
2331
|
+
const re = approveRef.ids[0] ?? "";
|
|
1898
2332
|
const roomId = re ? roomStore.roomOfMsg(re) : undefined;
|
|
1899
2333
|
const s = roomId ? roomState(roomId) : undefined;
|
|
1900
2334
|
const row = s?.byId.get(re);
|
|
@@ -1924,6 +2358,8 @@ const main = async () => {
|
|
|
1924
2358
|
const { self, body } = await readPeerBody(req);
|
|
1925
2359
|
if (READ_ROOM_FAIL(res, self))
|
|
1926
2360
|
return;
|
|
2361
|
+
if (refuseMonitor(res, self, "room_leave"))
|
|
2362
|
+
return;
|
|
1927
2363
|
const me = roomSelfOf(self);
|
|
1928
2364
|
if (!me) {
|
|
1929
2365
|
json(res, 400, { ok: false, reason: "caller 不在名册上, 没有 uid" });
|
|
@@ -1942,6 +2378,8 @@ const main = async () => {
|
|
|
1942
2378
|
json(res, 400, { ok: false, reason: "认不出这个地址: " + b.who });
|
|
1943
2379
|
return;
|
|
1944
2380
|
}
|
|
2381
|
+
if (refuseReception(res, "POST /room/leave", self, { targetName: who ? stripSigil(roomNameOf(who)) : undefined }))
|
|
2382
|
+
return;
|
|
1945
2383
|
if (!sameWho(who, me) && !sameWho(roomHost(s), me)) {
|
|
1946
2384
|
json(res, 403, { ok: false, reason: "只有 host 能移出别人" });
|
|
1947
2385
|
return;
|
|
@@ -2018,7 +2456,9 @@ const main = async () => {
|
|
|
2018
2456
|
});
|
|
2019
2457
|
json(res, 200, { ok: true, applied: b.apply === true, keepRecentHours: keepRecentMs / 3600_000, rooms });
|
|
2020
2458
|
}));
|
|
2021
|
-
|
|
2459
|
+
/** monitor 的判决: 为 re 那条人话在 to 名下开 duty (to 为空 = 判不回应)。
|
|
2460
|
+
* 只有本 room 的 monitor 成员能写; 校验 (最后一条人话 / 重复激活 / to 是成员) 在 shared/room.ts 的 judge。 */
|
|
2461
|
+
http.register("POST /room/activate", async (req, res) => {
|
|
2022
2462
|
const { self, body } = await readPeerBody(req);
|
|
2023
2463
|
if (READ_ROOM_FAIL(res, self))
|
|
2024
2464
|
return;
|
|
@@ -2028,43 +2468,55 @@ const main = async () => {
|
|
|
2028
2468
|
return;
|
|
2029
2469
|
}
|
|
2030
2470
|
const b = body;
|
|
2031
|
-
const
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
if (!roomId || !s || !s.byId.has(re)) {
|
|
2035
|
-
json(res, 400, { ok: false, reason: "认不出的消息 id: " + re });
|
|
2471
|
+
const actRefs = expandMsgRefs(self, idList(b.re));
|
|
2472
|
+
if (actRefs.error) {
|
|
2473
|
+
json(res, 400, { ok: false, reason: actRefs.error });
|
|
2036
2474
|
return;
|
|
2037
2475
|
}
|
|
2038
|
-
const
|
|
2039
|
-
if (
|
|
2040
|
-
json(res, 400, { ok: false, reason: "
|
|
2476
|
+
const re = actRefs.ids;
|
|
2477
|
+
if (re.length !== 1) {
|
|
2478
|
+
json(res, 400, { ok: false, reason: "re 只收一条 (最后一条人话的消息 id)" });
|
|
2041
2479
|
return;
|
|
2042
2480
|
}
|
|
2043
|
-
|
|
2044
|
-
|
|
2481
|
+
const roomId = roomStore.roomOfMsg(re[0]);
|
|
2482
|
+
const s = roomId ? roomState(roomId) : undefined;
|
|
2483
|
+
if (!roomId || !s) {
|
|
2484
|
+
json(res, 400, { ok: false, reason: "认不出的消息 id: " + re[0] });
|
|
2045
2485
|
return;
|
|
2046
2486
|
}
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
json(res, 409, { ok: false, reason: "这笔没有未决的 duty (从未开出 / 已全部关闭)" });
|
|
2487
|
+
if (s.members.get(whoKey(me))?.role !== "monitor") {
|
|
2488
|
+
json(res, 403, { ok: false, reason: "只有本 room 的 perceptron 能写感知判决" });
|
|
2050
2489
|
return;
|
|
2051
2490
|
}
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2491
|
+
// to = 应回应名单 (可多个, 2026-11-24 人定); 空 / 缺省 = 判不回应, 不落任何记录。
|
|
2492
|
+
const tos = [];
|
|
2493
|
+
for (const ref of idList(Array.isArray(b.to) ? b.to : b.to ?? [])) {
|
|
2494
|
+
const t = whoRefOf(ref) ?? memberRefOf(s, ref);
|
|
2495
|
+
if (!t) {
|
|
2496
|
+
json(res, 400, { ok: false, reason: "认不出这个地址: " + ref });
|
|
2056
2497
|
return;
|
|
2057
2498
|
}
|
|
2058
|
-
|
|
2499
|
+
if (!tos.some((x) => sameWho(x, t)))
|
|
2500
|
+
tos.push(t);
|
|
2059
2501
|
}
|
|
2060
|
-
const
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
//
|
|
2066
|
-
|
|
2067
|
-
|
|
2502
|
+
const v = judgeActivate(s, me, re, tos);
|
|
2503
|
+
if (!v.ok) {
|
|
2504
|
+
json(res, v.status, { ok: false, reason: v.reason });
|
|
2505
|
+
return;
|
|
2506
|
+
}
|
|
2507
|
+
// 感知判决 (2026-11-24 人定): 一条 perceive op 带全名单 + 理由 —— 不写消息行、不占 seq、不镜像,
|
|
2508
|
+
// 名单里每个成员名下开 duty 并唤醒; fold 出的 verdict 供 rolepage。空名单什么都不落。
|
|
2509
|
+
if (tos.length) {
|
|
2510
|
+
const why = typeof b.reason === "string" ? b.reason.trim() : "";
|
|
2511
|
+
hub.write(roomId, [{ op: "perceive", at: Date.now(), room: roomId, duty: re[0], to: tos,
|
|
2512
|
+
asker: s.byId.get(re[0]).author, by: me, ...(why ? { why } : {}) }]);
|
|
2513
|
+
hub.kick();
|
|
2514
|
+
roomLog.info({ room: roomId, re: re[0], to: tos.map((t) => roomNameOf(t)), why }, "perceptron: perceive");
|
|
2515
|
+
}
|
|
2516
|
+
else {
|
|
2517
|
+
roomLog.info({ room: roomId, re: re[0] }, "perceptron: perceive (空判决, 不落记录)");
|
|
2518
|
+
}
|
|
2519
|
+
json(res, 200, { ok: true, room: roomId, msg: re[0], to: tos.map((t) => whoKey(t)) });
|
|
2068
2520
|
});
|
|
2069
2521
|
http.register("POST /room/read", async (req, res) => {
|
|
2070
2522
|
const { self, body } = await readPeerBody(req);
|
|
@@ -2112,6 +2564,8 @@ const main = async () => {
|
|
|
2112
2564
|
const { self, body } = await readPeerBody(req);
|
|
2113
2565
|
if (READ_ROOM_FAIL(res, self))
|
|
2114
2566
|
return;
|
|
2567
|
+
if (refuseMonitor(res, self, "room_watch"))
|
|
2568
|
+
return;
|
|
2115
2569
|
const me = roomSelfOf(self);
|
|
2116
2570
|
if (!me) {
|
|
2117
2571
|
json(res, 400, { ok: false, reason: "caller 不在名册上, 没有 uid" });
|
|
@@ -2131,6 +2585,172 @@ const main = async () => {
|
|
|
2131
2585
|
hub.write(r.room, [{ op: "watch", at: Date.now(), room: r.room, who: me, on: b.on !== false }]);
|
|
2132
2586
|
json(res, 200, { ok: true, room: r.room, on: b.on !== false });
|
|
2133
2587
|
});
|
|
2588
|
+
// ── 源 ↔ room 绑定 (multi-source-binding §6): bind / unbind 只是账本 op ──────────
|
|
2589
|
+
/** 本 room 最近一条带 src 的人话 —— room_bind 不给 source 时把「刚接到这条首触」绑进来。
|
|
2590
|
+
* 给了 source 就找那个源最近的一条 (dry-run 的正文 / 发话人证据)。 */
|
|
2591
|
+
const latestSrcRowOf = (room, source = "") => {
|
|
2592
|
+
const s = roomState(room);
|
|
2593
|
+
if (!s)
|
|
2594
|
+
return undefined;
|
|
2595
|
+
for (let i = s.msgs.length - 1; i >= 0; i--) {
|
|
2596
|
+
const m = s.msgs[i];
|
|
2597
|
+
if (m.kind === "say" && m.author.kind === "human" && m.src && (!source || m.src === source))
|
|
2598
|
+
return m;
|
|
2599
|
+
}
|
|
2600
|
+
return undefined;
|
|
2601
|
+
};
|
|
2602
|
+
const latestSrcOf = (room, source = "") => latestSrcRowOf(room, source)?.src ?? "";
|
|
2603
|
+
const bindingCtx = () => ({ cfg, roomOfSource: (s) => roomStore.roomOfSource(s), stateOf: roomState, gate: roomStore.bindingGate() });
|
|
2604
|
+
http.register("POST /room/bind", async (req, res) => {
|
|
2605
|
+
const { self, body } = await readPeerBody(req);
|
|
2606
|
+
if (READ_ROOM_FAIL(res, self))
|
|
2607
|
+
return;
|
|
2608
|
+
if (refuseMonitor(res, self, "room_bind"))
|
|
2609
|
+
return;
|
|
2610
|
+
if (refuseReception(res, "POST /room/bind", self))
|
|
2611
|
+
return;
|
|
2612
|
+
const me = roomSelfOf(self);
|
|
2613
|
+
if (!me) {
|
|
2614
|
+
json(res, 400, { ok: false, reason: "caller 不在名册上, 没有 uid" });
|
|
2615
|
+
return;
|
|
2616
|
+
}
|
|
2617
|
+
const b = body;
|
|
2618
|
+
// 缺省 room = 本轮被唤醒的 room (出口 1: host 把刚接到的首触绑进自己这里)。
|
|
2619
|
+
const target = roomTargetOf(me, undefined, b.room);
|
|
2620
|
+
if (target.error || !target.room) {
|
|
2621
|
+
json(res, target.status ?? 400, { ok: false, reason: target.error ?? target.reason ?? "room required" });
|
|
2622
|
+
return;
|
|
2623
|
+
}
|
|
2624
|
+
const room = target.room;
|
|
2625
|
+
const source = (b.source ?? "").toString().trim() || latestSrcOf(room);
|
|
2626
|
+
// §5.2 dry-run: 只给候选 room + 证据 (daemon 只给证据, 决定权在模型), 不写账本。
|
|
2627
|
+
if (b.dryRun === true) {
|
|
2628
|
+
if (!source) {
|
|
2629
|
+
json(res, 400, { ok: false, reason: "没有可评估的源: 给 source, 或在本 room 里先有一条带源的人话" });
|
|
2630
|
+
return;
|
|
2631
|
+
}
|
|
2632
|
+
const row = latestSrcRowOf(room, source);
|
|
2633
|
+
const rep = bindCandidates({
|
|
2634
|
+
cfg, source, text: row?.text ?? "", asker: row?.author.kind === "human" ? row.author.id : "",
|
|
2635
|
+
states: roomStore.ids().map(roomState).filter((x) => !!x),
|
|
2636
|
+
roomOfSource: (x) => roomStore.roomOfSource(x), now: Date.now(),
|
|
2637
|
+
simMin: cfg.rooms?.binding?.simMin ?? 0.3, busyWindowMin: cfg.rooms?.binding?.busyWindowMin ?? 1440,
|
|
2638
|
+
hostInfoOf: (u) => {
|
|
2639
|
+
const w = wizards.byUid(u);
|
|
2640
|
+
return w ? { name: w.name ?? "", responsibility: w.description ?? "" } : undefined;
|
|
2641
|
+
},
|
|
2642
|
+
});
|
|
2643
|
+
json(res, 200, { ok: true, dryRun: true, source, text: rep.text,
|
|
2644
|
+
candidates: rep.candidates.map((c) => ({ room: c.room, evidence: c.evidence, veto: c.veto, score: Math.round(c.score * 100) / 100 })),
|
|
2645
|
+
...(rep.blocked ? { blocked: rep.blocked } : {}) });
|
|
2646
|
+
return;
|
|
2647
|
+
}
|
|
2648
|
+
const v = planBind({ ...bindingCtx(), room, source, actor: me, ...(b.why ? { why: b.why.toString() } : {}) }, Date.now());
|
|
2649
|
+
if (!v.ok) {
|
|
2650
|
+
json(res, v.status, { ok: false, reason: v.reason });
|
|
2651
|
+
return;
|
|
2652
|
+
}
|
|
2653
|
+
if (!v.already) {
|
|
2654
|
+
try {
|
|
2655
|
+
hub.write(room, [v.op]);
|
|
2656
|
+
}
|
|
2657
|
+
catch (e) {
|
|
2658
|
+
if (e instanceof BindGateClosed) {
|
|
2659
|
+
json(res, 503, { ok: false, reason: "绑定索引对账失败, 暂不接受绑定写: " + (e.message) });
|
|
2660
|
+
return;
|
|
2661
|
+
}
|
|
2662
|
+
json(res, 500, { ok: false, reason: errText(e) });
|
|
2663
|
+
return;
|
|
2664
|
+
}
|
|
2665
|
+
roomLog.info({ room, source, by: me.id }, "room: 源已绑进本 room");
|
|
2666
|
+
}
|
|
2667
|
+
json(res, 200, { ok: true, room, source, ...(v.already ? { already: true } : {}),
|
|
2668
|
+
text: (v.already ? "这个源已经绑在 " + room + ", 不用重复绑。" : "已把 " + source + " 绑进 " + room + ": 之后它的消息落这本账, 这里的回复回它 (帖子 = 评论原帖, 群 = 群消息)。") });
|
|
2669
|
+
});
|
|
2670
|
+
http.register("POST /room/unbind", async (req, res) => {
|
|
2671
|
+
const { self, body } = await readPeerBody(req);
|
|
2672
|
+
if (READ_ROOM_FAIL(res, self))
|
|
2673
|
+
return;
|
|
2674
|
+
if (refuseMonitor(res, self, "room_unbind"))
|
|
2675
|
+
return;
|
|
2676
|
+
if (refuseReception(res, "POST /room/unbind", self))
|
|
2677
|
+
return;
|
|
2678
|
+
const me = roomSelfOf(self);
|
|
2679
|
+
if (!me) {
|
|
2680
|
+
json(res, 400, { ok: false, reason: "caller 不在名册上, 没有 uid" });
|
|
2681
|
+
return;
|
|
2682
|
+
}
|
|
2683
|
+
const b = body;
|
|
2684
|
+
const target = roomTargetOf(me, undefined, b.room);
|
|
2685
|
+
if (target.error || !target.room) {
|
|
2686
|
+
json(res, target.status ?? 400, { ok: false, reason: target.error ?? target.reason ?? "room required" });
|
|
2687
|
+
return;
|
|
2688
|
+
}
|
|
2689
|
+
const room = target.room;
|
|
2690
|
+
const source = (b.source ?? "").toString().trim();
|
|
2691
|
+
const v = planUnbind({ ...bindingCtx(), room, source, actor: me, ...(b.why ? { why: b.why.toString() } : {}) }, Date.now());
|
|
2692
|
+
if (!v.ok) {
|
|
2693
|
+
json(res, v.status, { ok: false, reason: v.reason });
|
|
2694
|
+
return;
|
|
2695
|
+
}
|
|
2696
|
+
try {
|
|
2697
|
+
hub.write(room, [v.op]);
|
|
2698
|
+
}
|
|
2699
|
+
catch (e) {
|
|
2700
|
+
if (e instanceof BindGateClosed) {
|
|
2701
|
+
json(res, 503, { ok: false, reason: "绑定索引对账失败, 暂不接受解绑写: " + (e.message) });
|
|
2702
|
+
return;
|
|
2703
|
+
}
|
|
2704
|
+
json(res, 500, { ok: false, reason: errText(e) });
|
|
2705
|
+
return;
|
|
2706
|
+
}
|
|
2707
|
+
roomLog.info({ room, source, by: me.id }, "room: 源已解绑 (回落恒等, lazy)");
|
|
2708
|
+
json(res, 200, { ok: true, room, source,
|
|
2709
|
+
text: "已解绑 " + source + ": 它的消息回落恒等 (自己的 room / 频道接待处); 帖子源下一条消息时才会按需诞生帖子 room (lazy)。" });
|
|
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 身份不变)。" });
|
|
2753
|
+
});
|
|
2134
2754
|
// ── 新群引导的受控绑定 (onboard_bind): 只有引导化身能调 ────────────────
|
|
2135
2755
|
// 引导的唯一动作面: 校验 (create 只建最后一级 / 父目录必须已在 / 必须在 $HOME 下) 与落盘都在
|
|
2136
2756
|
// daemon, 引导只表达意图。失败 = 4xx 带原因, 引导自己向人追问 (状态机不动)。
|
|
@@ -2142,7 +2762,8 @@ const main = async () => {
|
|
|
2142
2762
|
const b = body;
|
|
2143
2763
|
const plan = planOnboardBind({
|
|
2144
2764
|
caller: wizards.get(self), onboarding: needsOnboarding(cfg, wizards, base),
|
|
2145
|
-
workspace: b.workspace, create: b.create, name: b.name,
|
|
2765
|
+
workspace: b.workspace, create: b.create, name: b.name, roomName: b.roomName,
|
|
2766
|
+
nameTaken: (n) => !!wizards.byName(n),
|
|
2146
2767
|
judge: (input) => judgeOnboarding(wizards, base, input, (t) => m.sessionInfo(t)?.cwd ?? ""),
|
|
2147
2768
|
});
|
|
2148
2769
|
if (!plan.ok) {
|
|
@@ -2150,15 +2771,19 @@ const main = async () => {
|
|
|
2150
2771
|
return;
|
|
2151
2772
|
}
|
|
2152
2773
|
const { verdict } = plan;
|
|
2153
|
-
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)));
|
|
2154
|
-
roomLog.info({ room: base, ...bound }, "onboarding: steward bound (guide tool)");
|
|
2155
|
-
const handed = guideSettleRoom(base, bound);
|
|
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);
|
|
2775
|
+
roomLog.info({ room: base, ...bound, roomName: plan.roomName ?? "" }, "onboarding: steward bound (guide tool)");
|
|
2776
|
+
const handed = guideSettleRoom(base, bound, plan.roomName);
|
|
2777
|
+
settleBoundChannel(base, bound);
|
|
2156
2778
|
if (!handed)
|
|
2157
2779
|
notifyChat(base, renderOnboardingDone(bound)); // 引导不在 room 里 (老流程): 至少回报一句
|
|
2158
2780
|
void reapGuideAfterTurn(self); // 先回成功: 这一轮的话还要说完, 收尸在轮终之后 (或 60s)
|
|
2159
2781
|
json(res, 200, { ok: true, name: bound.name, target: bound.target, workspace: bound.workspace, fresh: bound.fresh,
|
|
2782
|
+
...(bound.instance ? { instance: bound.instance } : {}),
|
|
2783
|
+
...(bound.instanceOpened ? { instanceOpened: true } : {}),
|
|
2160
2784
|
...(handed ? { room: base } : {}),
|
|
2161
|
-
|
|
2785
|
+
...(plan.roomName ? { roomName: plan.roomName } : {}),
|
|
2786
|
+
message: "绑定完成, 引导到此结束: 这一轮不要再说话、不要再调工具; 人的原话与后续要求已经交给管家 ." + (bound.instance || bound.name) + "。" });
|
|
2162
2787
|
});
|
|
2163
2788
|
// ── 出生 / 退役的 room 落账 ──────────────────────────────────────────
|
|
2164
2789
|
/** spawn / clone / delegate 的 room? 参数: 落地的 wizard 以 via:"spawn" 免审入群 (契约 §3)。 */
|
|
@@ -2255,6 +2880,238 @@ const main = async () => {
|
|
|
2255
2880
|
hub.write(room, ops);
|
|
2256
2881
|
return room;
|
|
2257
2882
|
};
|
|
2883
|
+
// ── 频道 / 帖子 room 与 monitor (§2.2 / §2.3) ───────────────────────
|
|
2884
|
+
/** 一个 room 一个 perceptron (原 monitor, 2026-11-24 人定): 门控 = 存在 wizard 成员 (含单管家,
|
|
2885
|
+
* 人二次拍板 9e7dbc47.9)。**不预起 pane** —— 只建身份 + 入座, 首次唤醒由
|
|
2886
|
+
* 泵冷启动 (档位走 steward-model 的 monitor 规则, 不落 CLI 默认), 闲时 pane 可被资源回收。 */
|
|
2887
|
+
/** 一个 room 自己的管家实例 (人 2026-11-23: 不同的 room 要用不同的实例): 频道绑的那个身份在
|
|
2888
|
+
* **这个 room** 的化身 —— 没有就领号新开 (类) / 另落一条同身份记录。绝不把别的 room 的实例
|
|
2889
|
+
* 拉过来当这个 room 的 host。名册 / 绑定缺席 = undefined。会话不在这里起: 第一条人话被唤醒时
|
|
2890
|
+
* 泵会把它冷启动 (一个帖子一个常驻 pane 会顶到上限)。 */
|
|
2891
|
+
const roomStewardOf = (room, channelRoom) => {
|
|
2892
|
+
const identity = stewardIdentityOf(cfg, wizardStore(), channelRoom) ?? "";
|
|
2893
|
+
if (!identity)
|
|
2894
|
+
return undefined;
|
|
2895
|
+
const target = localManifestation(wizardStore(), room, identity);
|
|
2896
|
+
const rec = target ? wizards.get(target) : undefined;
|
|
2897
|
+
return rec?.uid ? { kind: "wizard", id: rec.uid } : undefined;
|
|
2898
|
+
};
|
|
2899
|
+
const ensurePerceptron = (room) => {
|
|
2900
|
+
if (!cfg.wrc.channel.monitor.enabled)
|
|
2901
|
+
return;
|
|
2902
|
+
const st0 = roomState(room);
|
|
2903
|
+
if (!st0)
|
|
2904
|
+
return;
|
|
2905
|
+
if (hasMonitor(st0))
|
|
2906
|
+
return;
|
|
2907
|
+
// 门控 (2026-11-24 人二次拍板 9e7dbc47.9): 只要存在 wizard 成员 (含单管家 room / 频道) 就感知 ——
|
|
2908
|
+
// 独狼管家也要感知「没点名给它的消息是否需要它回应」, 不再按成员数、不回落 host 兜底。
|
|
2909
|
+
// 例外: 单聊 (人私聊 = 直接说给全局管家) / .me 独立对话 / 引导中的群与频道 (人话要落引导化身,
|
|
2910
|
+
// perceptron 会把它抢走)。
|
|
2911
|
+
if (room.startsWith("user:") || room.startsWith("me:"))
|
|
2912
|
+
return;
|
|
2913
|
+
if (needsOnboarding(cfg, wizardStore(), room))
|
|
2914
|
+
return;
|
|
2915
|
+
const channelRoom = channelRoomOf(cfg, room);
|
|
2916
|
+
if (channelRoom && !channelMonitorWanted(cfg, wizardStore(), channelRoom))
|
|
2917
|
+
return;
|
|
2918
|
+
if (!perceptronCandidates(st0).length)
|
|
2919
|
+
return;
|
|
2920
|
+
const target = keyOf(baseOfKey(room), "monitor");
|
|
2921
|
+
const rec = wizards.get(target);
|
|
2922
|
+
wizards.upsert(target, {
|
|
2923
|
+
kind: "monitor",
|
|
2924
|
+
...(rec ? {} : { bornAt: Date.now(), identity: target }),
|
|
2925
|
+
description: "本 room 的 perceptron: 读账本, 结合成员职责判断最后一条人话该由谁回应 (room_activate)",
|
|
2926
|
+
parent: undefined,
|
|
2927
|
+
lead: undefined,
|
|
2928
|
+
leadOf: undefined,
|
|
2929
|
+
});
|
|
2930
|
+
const uid = wizards.get(target)?.uid;
|
|
2931
|
+
if (!uid)
|
|
2932
|
+
return;
|
|
2933
|
+
const st = roomState(room);
|
|
2934
|
+
if (st && !st.members.has(whoKey({ kind: "wizard", id: uid })))
|
|
2935
|
+
hub.write(room, [{ op: "join", at: Date.now(), room, who: { kind: "wizard", id: uid }, ord: st.nextOrd, via: "invite", by: DAEMON, role: "monitor" }]);
|
|
2936
|
+
roomLog.info({ target, room }, "perceptron: 建 room perceptron (懒建, 首次唤醒冷启动)");
|
|
2937
|
+
};
|
|
2938
|
+
/** 频道 room 不存在就开一个 (频道管家已绑定就作 founder —— monitor 需要有人可激活)。
|
|
2939
|
+
* 未绑定期不建 monitor (channel-onboarding 口径①): 否则每条人话都被 monitor 抢走, 引导就哑了。
|
|
2940
|
+
* learnChannelRoom: 未配对过帖子的频道也要被认成频道 —— 引导绑定落 wrc.channel.steward 靠它。 */
|
|
2941
|
+
const ensureChannelRoom = (topicId) => {
|
|
2942
|
+
const room = "chat:" + topicId;
|
|
2943
|
+
learnChannelRoom(cfg, topicId);
|
|
2944
|
+
if (!roomState(room)) {
|
|
2945
|
+
const at = Date.now();
|
|
2946
|
+
const ops = [{ op: "open", at, room, kind: "channel", by: DAEMON }];
|
|
2947
|
+
try {
|
|
2948
|
+
const stw = resolveSteward(cfg, wizardStore(), room, (t) => ((c) => c.runningCwd || c.defaultCwd)(m.getCwd(t)));
|
|
2949
|
+
// 已有化身的才能作 founder (fresh = 记录还没落, 由入站接待自己开)。与 ensureBoundRoom 同一判法。
|
|
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);
|
|
2956
|
+
}
|
|
2957
|
+
return room;
|
|
2958
|
+
};
|
|
2959
|
+
/** 频道引导期: 引导化身入座频道 room 并接住这条人话 (人话落频道 room —— 帖子 room 此刻没有
|
|
2960
|
+
* host, 落那儿等于丢话)。与群引导的 guideTakeover 同形, 只是没有企微占位气泡 (频道 room
|
|
2961
|
+
* 的出站是帖子)。 */
|
|
2962
|
+
const takeChannelGuide = (turn) => {
|
|
2963
|
+
const rec = wizards.get(turn.guide);
|
|
2964
|
+
if (!rec?.uid)
|
|
2965
|
+
return { ok: false, reason: "引导会话不在名册上" };
|
|
2966
|
+
const at = Date.now();
|
|
2967
|
+
const s = roomState(turn.channelRoom);
|
|
2968
|
+
// 旧版本给未绑定频道建过 monitor: 先请它退场, 否则人话只听它的, 引导接不到 (口径①)。
|
|
2969
|
+
const evict = s ? channelMonitorLeaveOps(s, at) : [];
|
|
2970
|
+
if (evict.length) {
|
|
2971
|
+
hub.write(turn.channelRoom, evict);
|
|
2972
|
+
roomLog.info({ room: turn.channelRoom }, "onboarding: 频道引导期请走 monitor");
|
|
2973
|
+
}
|
|
2974
|
+
const join = channelGuideJoinOps(roomState(turn.channelRoom), turn.channelRoom, { kind: "wizard", id: rec.uid }, at);
|
|
2975
|
+
if (join.length)
|
|
2976
|
+
hub.write(turn.channelRoom, join);
|
|
2977
|
+
const v = hub.append(turn.channelRoom, turn.human);
|
|
2978
|
+
return v.ok ? { ok: true } : { ok: false, reason: v.reason };
|
|
2979
|
+
};
|
|
2980
|
+
const channelGuideSpawning = new Set();
|
|
2981
|
+
/** 未绑定频道的人话: 起 (或续) 引导化身, 人话落频道 room 交给它。会话冷启动在后台做 ——
|
|
2982
|
+
* 人话先落账 (起 pane 慢不能丢话); 出生窗口里贴不进去 (还没绑定), 泵会退成可重试,
|
|
2983
|
+
* 起来后这里踢一脚泵立刻投, 不会写成「没有会话 (已被结束)」。 */
|
|
2984
|
+
const channelGuideTurn = (turn) => {
|
|
2985
|
+
const store = wizardStore();
|
|
2986
|
+
if (!store)
|
|
2987
|
+
return;
|
|
2988
|
+
if (!store.get(turn.guide)) {
|
|
2989
|
+
store.upsert(turn.guide, { identity: turn.guide, kind: "worker", description: GUIDE_DESC, workspace: expandHome(cfg.wrc.cwd) });
|
|
2990
|
+
roomLog.info({ room: turn.channelRoom, guide: turn.guide }, "onboarding: 频道引导化身落记录");
|
|
2991
|
+
}
|
|
2992
|
+
if (!m.hasMirrorTarget(turn.guide) && !channelGuideSpawning.has(turn.guide)) {
|
|
2993
|
+
channelGuideSpawning.add(turn.guide);
|
|
2994
|
+
const name = settleName(store, chatNameOf(cfg, turn.guide), turn.guide) || turn.guide;
|
|
2995
|
+
void m.newSession(turn.guide, name, { silent: true, cwd: expandHome(cfg.wrc.cwd) })
|
|
2996
|
+
.then((r) => {
|
|
2997
|
+
if (!r.ok) {
|
|
2998
|
+
roomLog.warn({ guide: turn.guide, reason: r.reason }, "onboarding: 频道引导会话起不来 (人话照样落账, 泵会再试)");
|
|
2999
|
+
return;
|
|
3000
|
+
}
|
|
3001
|
+
m.armCharter(turn.guide, turn.first ? renderGuideOpening() : renderGuideRetry(""));
|
|
3002
|
+
hub.kick(); // 人话在这之前已落账: pane 一绑上就投, 不等 30s 重踢
|
|
3003
|
+
})
|
|
3004
|
+
.catch((err) => roomLog.warn({ guide: turn.guide, err: errText(err) }, "onboarding: 频道引导会话起不来"))
|
|
3005
|
+
.finally(() => channelGuideSpawning.delete(turn.guide));
|
|
3006
|
+
}
|
|
3007
|
+
const r = takeChannelGuide(turn);
|
|
3008
|
+
if (!r.ok)
|
|
3009
|
+
roomLog.warn({ room: turn.channelRoom, guide: turn.guide, reason: r.reason }, "onboarding: 频道引导没接住这条人话");
|
|
3010
|
+
};
|
|
3011
|
+
/** 频道已绑定而引导化身还挂着 (人手改 config / 上个进程死在半路): 收尸 —— 与群 guideGate 开头同款。 */
|
|
3012
|
+
const reapStaleChannelGuide = (channelRoom) => {
|
|
3013
|
+
const guide = guideOf(wizards, channelRoom);
|
|
3014
|
+
if (!guide)
|
|
3015
|
+
return;
|
|
3016
|
+
roomLog.info({ room: channelRoom, guide }, "onboarding: 频道已绑定, 收掉遗留的引导化身");
|
|
3017
|
+
void m.killPane(guide).catch(() => undefined).then(() => { wizardStore()?.drop(guide); });
|
|
3018
|
+
};
|
|
3019
|
+
/** 人话落 room: 频道 room / 帖子 room 都先保证存在; mention / post 原样写进行里。
|
|
3020
|
+
* 未绑定频道先过引导 (口径②④): 引导接一切人话, 绑定后才轮到 monitor / host。 */
|
|
3021
|
+
channelIngest = (e) => {
|
|
3022
|
+
// 帖 / 评论带的图与文件: 与群聊一个口径 —— 图片以 `@path` 随行 (pane 里 CLI 直接 Read),
|
|
3023
|
+
// 文件给一行路径; 账本行同时记 files (rolepage 显示 📎, room_read 可查)。
|
|
3024
|
+
const mediaFiles = [
|
|
3025
|
+
...(e.images ?? []).map((p) => ({ path: p, kind: kindOf(p), name: basename(p) })),
|
|
3026
|
+
...(e.files ?? []).map((f) => ({ path: f.path, kind: kindOf(f.path), name: f.name })),
|
|
3027
|
+
];
|
|
3028
|
+
const text = e.text
|
|
3029
|
+
+ (e.images?.length ? "\n" + e.images.map((p) => "@" + p).join(" ") : "")
|
|
3030
|
+
+ (e.files?.length ? "\n" + e.files.map((f) => "[文件: " + f.path + "]").join("\n") : "");
|
|
3031
|
+
// .me 点名 (人 2026-11-24, 与群聊里 .me 被 resolve 分流同一规矩): 没 @ 机器人也直达说话人的
|
|
3032
|
+
// me —— 行只落他的私有 me-room, **发生地零行** (host / perceptron 看不见这句)。先于引导 /
|
|
3033
|
+
// 绑定: 这句是点给 me 的, 不是频道的新活。me 冷着就顺手起会话 (泵贴不进没绑定的 pane)。
|
|
3034
|
+
const me = meChannelSay({
|
|
3035
|
+
store: wizardStore(), workspace: meWorkspaceOf(sourcePath), state: roomState,
|
|
3036
|
+
write: (room, ops) => { hub.write(room, ops); },
|
|
3037
|
+
append: (room, draft) => hub.append(room, draft),
|
|
3038
|
+
ensureSession: (target) => {
|
|
3039
|
+
const store = wizardStore();
|
|
3040
|
+
if (!store || m.hasMirrorTarget(target))
|
|
3041
|
+
return;
|
|
3042
|
+
// 工作区取记录上的 (meWorkspaceOf 落的那条): 不写 cwd 会落 wrc.cwd —— me 不属于业务仓库。
|
|
3043
|
+
const cwd = identityWorkspaceOf(store, target) || undefined;
|
|
3044
|
+
void m.newSession(target, settleName(store, chatNameOf(cfg, target), target) || target, { silent: true, ...(cwd ? { cwd } : {}) })
|
|
3045
|
+
.catch(() => undefined);
|
|
3046
|
+
},
|
|
3047
|
+
}, { author: e.author, text, files: mediaFiles, src: e.room, ...(e.post ? { post: e.post } : {}) });
|
|
3048
|
+
if (me) {
|
|
3049
|
+
if (!me.ok)
|
|
3050
|
+
roomLog.warn({ room: meRoomId(e.author), src: e.room, msgid: e.msgid, reason: me.reason }, "channel: .me 人话落行被拒");
|
|
3051
|
+
return;
|
|
3052
|
+
}
|
|
3053
|
+
// 绑定优先于引导: 源已绑进某个 room → 这句话落那本账 (引导只管还没归属的频道人话)。
|
|
3054
|
+
const bound = roomStore.roomOfSource(e.room);
|
|
3055
|
+
if (!bound) {
|
|
3056
|
+
const turn = planChannelGuideTurn({ cfg, store: wizardStore(), onboarding, room: e.room }, e);
|
|
3057
|
+
if (turn) {
|
|
3058
|
+
channelGuideTurn(turn);
|
|
3059
|
+
return;
|
|
3060
|
+
}
|
|
3061
|
+
}
|
|
3062
|
+
const chRoom = channelRoomOf(cfg, e.room);
|
|
3063
|
+
if (chRoom) {
|
|
3064
|
+
onboarding.finish(chRoom);
|
|
3065
|
+
reapStaleChannelGuide(chRoom);
|
|
3066
|
+
}
|
|
3067
|
+
// §4.1 源 → room: 绑定优先; 帖子源还没诞生 (没绑、帖子 room 也不在) → 频道 room 的接待处,
|
|
3068
|
+
// 由 host 判定 (§5.1)。行上的 src 写死入口源 —— 重放不再推断, 出站 (P2) 按它回原帖/原群。
|
|
3069
|
+
const room = sourceRoomOf({ source: e.room, roomOfSource: (s) => roomStore.roomOfSource(s), stateOf: roomState, fallback: () => chRoom || undefined });
|
|
3070
|
+
const src = e.room !== room ? e.room : undefined;
|
|
3071
|
+
if (!roomState(room)) {
|
|
3072
|
+
roomLog.warn({ room, src: e.room, msgid: e.msgid }, "channel: room 不存在, 人话没落账本 (自愈: 下一条事件重建)");
|
|
3073
|
+
return;
|
|
3074
|
+
}
|
|
3075
|
+
const v = hub.append(room, {
|
|
3076
|
+
author: { kind: "human", id: e.author }, kind: "say", text, origin: "inbound",
|
|
3077
|
+
...(e.post ? { post: e.post } : {}), ...(e.mention ? { mention: e.mention } : {}),
|
|
3078
|
+
...(src ? { src } : {}), ...(mediaFiles.length ? { files: mediaFiles } : {}),
|
|
3079
|
+
});
|
|
3080
|
+
if (!v.ok)
|
|
3081
|
+
roomLog.warn({ room, src: e.room, msgid: e.msgid, reason: v.reason }, "channel: 人话落行被拒");
|
|
3082
|
+
};
|
|
3083
|
+
/** §4.1 入站源解析 (inbound 的 resolve / send 用): base 是入站发生地 (群 / 帖子群 / 频道)。
|
|
3084
|
+
* - 源已绑进 room R → 落 R, 接待 = R 的 host (不是源自己的类绑定化身);
|
|
3085
|
+
* - 帖子源已诞生 (帖子 room 在) → 落它;
|
|
3086
|
+
* - 帖子源还没诞生 (首触) → 落频道 room, 接待 = 频道 host;
|
|
3087
|
+
* - 普通群 / 恒等路径 → undefined (现行为, stewardReception)。
|
|
3088
|
+
* host 必须是 wizard 且还在名册上; 解析不出就回落恒等 (主流程不因绑定出错)。 */
|
|
3089
|
+
sourceRouteHook = (base) => {
|
|
3090
|
+
if (!base.startsWith("chat:"))
|
|
3091
|
+
return undefined;
|
|
3092
|
+
const bound = roomStore.roomOfSource(base);
|
|
3093
|
+
const ref = postRefOf(cfg, base);
|
|
3094
|
+
const topic = channelOf(cfg, base);
|
|
3095
|
+
if (!bound && !ref && !topic)
|
|
3096
|
+
return undefined;
|
|
3097
|
+
const room = sourceRoomOf({ source: base, roomOfSource: (s) => roomStore.roomOfSource(s), stateOf: roomState,
|
|
3098
|
+
fallback: () => (ref ? ensureChannelRoom(ref.channel) : undefined) });
|
|
3099
|
+
const st = roomState(room);
|
|
3100
|
+
const host = st ? roomHost(st) : undefined;
|
|
3101
|
+
const target = host?.kind === "wizard" ? roomWizardOf(host.id)?.target : undefined;
|
|
3102
|
+
if (!target)
|
|
3103
|
+
return undefined;
|
|
3104
|
+
const src = base !== room ? base : undefined;
|
|
3105
|
+
return { room, target, ...(src ? { src } : {}), ...(ref?.post ? { post: ref.post } : {}) };
|
|
3106
|
+
};
|
|
3107
|
+
channelRoomSeen = (topicId) => { ensureChannelRoom(topicId); };
|
|
3108
|
+
/** 帖子源首触 (§4.1): **不建 room、不开实例** —— 人话由 inbound / channelIngest 落频道 room
|
|
3109
|
+
* 交 host 判定。这里只保证频道 room 在 (首触的人话要有地方落), 并记一行日志。
|
|
3110
|
+
* 帖子 room 的诞生移到 birthPostRoom: host 的 room_bind 之外, 超时兜底 (decideOnFirstTouch) 调。 */
|
|
3111
|
+
channelPostTouched = (topicId, postBase) => {
|
|
3112
|
+
const channelRoom = ensureChannelRoom(topicId);
|
|
3113
|
+
roomLog.info({ room: postBase, channel: channelRoom }, "channel: 帖子源首触 (落频道 room 交 host 判定, 不建帖子 room)");
|
|
3114
|
+
};
|
|
2258
3115
|
/** 定时任务 / plan 提醒的一枪 (cutmap G-1/G-2): kind:"trigger" 行 —— 不镜像, 只唤醒 owner。 */
|
|
2259
3116
|
const fireTaskTrigger = (target, text, ext) => {
|
|
2260
3117
|
const rec = wizards.get(target);
|
|
@@ -2286,7 +3143,12 @@ const main = async () => {
|
|
|
2286
3143
|
isBusy: (target) => m.isBusy(target),
|
|
2287
3144
|
rooms: roomStore.ids,
|
|
2288
3145
|
stateOf: roomState,
|
|
2289
|
-
|
|
3146
|
+
// pane 不在了、会话绑定还在 → 落一条 trigger 行把它叫起来 (2026-11-24): 泵投递时
|
|
3147
|
+
// injectText 探活 gone 会 --resume 重生 pane 再贴。不开预算、不判实例结束。
|
|
3148
|
+
revive: (room, uid, duties, text) => hub.append(room, {
|
|
3149
|
+
author: DAEMON, kind: "trigger", origin: "daemon", sys: "pane-revive",
|
|
3150
|
+
to: [{ kind: "wizard", id: uid }], re: [...duties], text,
|
|
3151
|
+
}, { budget: Number.MAX_SAFE_INTEGER }).ok,
|
|
2290
3152
|
onIdle: (uid) => hub.onIdle(uid),
|
|
2291
3153
|
kick: () => void hub.kick(),
|
|
2292
3154
|
staleMs: () => (cfg.rooms?.watchdog?.staleMin ?? 5) * 60_000,
|
|
@@ -2313,24 +3175,46 @@ const main = async () => {
|
|
|
2313
3175
|
// pump 的注入也算「最后一次事件」: 正在投递的 wizard 不进 stale 名单 (paste 端口的 touch 见 hub ports)。
|
|
2314
3176
|
const watchdogTimer = setInterval(() => void roomWatchdog.scan(), (cfg.rooms?.watchdog?.intervalSec ?? 60) * 1000);
|
|
2315
3177
|
watchdogTimer.unref?.();
|
|
2316
|
-
//
|
|
3178
|
+
// 起于旧控制面 (TCP) 的 pane: 它们的 MCP 只会得到 410 —— 与看门狗同节拍, 空闲的就地 sleepPane
|
|
3179
|
+
// (绑定与身份保留, 下一条注入 --resume 用新启动行重起); 忙的等下一拍。argv 里没有旧痕迹的不碰。
|
|
3180
|
+
const legacyReaper = createLegacyPaneReaper({
|
|
3181
|
+
log: log.child({ mod: "legacy-panes" }),
|
|
3182
|
+
listPanes: async () => {
|
|
3183
|
+
const r = await runTmux(["list-panes", "-a", "-F", "#{pane_id} #{pane_pid}"]);
|
|
3184
|
+
return r.ok ? { ok: true, panes: parsePanePids(r.stdout) } : { ok: false, error: r.stderr.slice(0, 200) };
|
|
3185
|
+
},
|
|
3186
|
+
procs: async () => new Map([...(await procSnapshot())].map(([pid, e]) => [pid, { ppid: e.ppid, cmd: e.cmd }])),
|
|
3187
|
+
bindings: () => m.chatRoster("").flatMap((c) => c.targets).filter((t) => !isInternalKey(t))
|
|
3188
|
+
.flatMap((target) => { const pane = m.sessionInfo(target)?.tmuxPane; return pane ? [{ target, pane }] : []; }),
|
|
3189
|
+
isBusy: (target) => m.isBusy(target),
|
|
3190
|
+
sleepPane: (target) => m.sleepPane(target),
|
|
3191
|
+
});
|
|
3192
|
+
const legacyTimer = setInterval(() => void legacyReaper.scan().catch((e) => log.warn({ err: e.message }, "legacy-panes scan failed")), (cfg.rooms?.watchdog?.intervalSec ?? 60) * 1000);
|
|
3193
|
+
legacyTimer.unref?.();
|
|
3194
|
+
// duty 逾期两级提醒: 与看门狗同节拍, 阈值每轮现读 (hot)。处理人忙 (跑着这一轮 / 停在审批框上)
|
|
3195
|
+
// 就这一轮不催; 下游还有未关 duty 时只催下游 (递归式, 见 shared/room-overdue)。
|
|
2317
3196
|
const overdue = createOverdueScan({
|
|
2318
3197
|
log: roomLog, now: () => Date.now(),
|
|
2319
|
-
thresholds: () => ({ remindMin: cfg.rooms?.overdue?.remindMin ?? 60, groupMin: cfg.rooms?.overdue?.groupMin ?? 120 }),
|
|
3198
|
+
thresholds: () => ({ remindMin: cfg.rooms?.overdue?.remindMin ?? 60, groupMin: cfg.rooms?.overdue?.groupMin ?? 120, backoff: cfg.rooms?.overdue?.backoff, maxReminds: cfg.rooms?.overdue?.maxReminds }),
|
|
2320
3199
|
rooms: roomStore.ids, stateOf: roomState, append: (room, d, extra) => hub.append(room, d, extra),
|
|
2321
3200
|
wizardOf: roomWizardOf, nameOf: roomNameOf, roomLabel,
|
|
3201
|
+
externalOf: (w) => {
|
|
3202
|
+
const name = extNameOf(w);
|
|
3203
|
+
if (!name)
|
|
3204
|
+
return undefined;
|
|
3205
|
+
return { name, owner: external.principals().find((x) => x.name === name)?.owner ?? "" };
|
|
3206
|
+
},
|
|
3207
|
+
isBusy: async (uid) => {
|
|
3208
|
+
const rec = roomWizardOf(uid);
|
|
3209
|
+
return rec ? await m.isBusy(rec.target) : false;
|
|
3210
|
+
},
|
|
2322
3211
|
});
|
|
2323
|
-
const
|
|
2324
|
-
overdue.scan();
|
|
2325
|
-
}
|
|
2326
|
-
|
|
2327
|
-
roomLog.warn({ err: e.message }, "overdue: 扫描失败");
|
|
2328
|
-
} }, (cfg.rooms?.watchdog?.intervalSec ?? 60) * 1000);
|
|
3212
|
+
const overdueScan = () => {
|
|
3213
|
+
overdue.scan().catch((e) => roomLog.warn({ err: e.message }, "overdue: 扫描失败"));
|
|
3214
|
+
};
|
|
3215
|
+
const overdueTimer = setInterval(overdueScan, (cfg.rooms?.watchdog?.intervalSec ?? 60) * 1000);
|
|
2329
3216
|
overdueTimer.unref?.();
|
|
2330
|
-
setTimeout(()
|
|
2331
|
-
overdue.scan();
|
|
2332
|
-
}
|
|
2333
|
-
catch { /* 下一轮再来 */ } }, 20_000).unref?.();
|
|
3217
|
+
setTimeout(overdueScan, 20_000).unref?.();
|
|
2334
3218
|
// ── 新群引导的两端 (契约 §4): 人话落 room → guide 当 founder 说话 → 绑定后交给管家 ────
|
|
2335
3219
|
/** 引导期: 人这句落进本群 room (guide 作 founder, ord=1) 并唤醒它。引导从此只能在 room
|
|
2336
3220
|
* 里说话 (chat_reply), 绑定后那条 duty 连原话一起交给管家。 */
|
|
@@ -2363,9 +3247,30 @@ const main = async () => {
|
|
|
2363
3247
|
roomLog.info({ room, guide: a.guide, msgId: v.row.id }, "onboarding: 人话进了引导 room");
|
|
2364
3248
|
return { ok: true };
|
|
2365
3249
|
};
|
|
3250
|
+
/** 管家实例的 pane: 记录在、pane 没有就起一个, 起来后踢一脚泵 (否则要等 30s 重踢)。
|
|
3251
|
+
* 群落定 (guideSettleRoom) 与频道落定 / boot 兜底共用这一个口子 —— spawning 去重 (同一轮里
|
|
3252
|
+
* 先 guideSettleRoom 再 settleBoundChannel 不会起两次)。**记录在、pane 没有**正是「已被结束」
|
|
3253
|
+
* 的来源: monitor 唤醒时探活 gone (人 2026-11-23 现场)。 */
|
|
3254
|
+
const stewardSpawning = new Set();
|
|
3255
|
+
const spawnStewardPane = (target) => {
|
|
3256
|
+
if (!target)
|
|
3257
|
+
return;
|
|
3258
|
+
if (m.hasMirrorTarget(target)) {
|
|
3259
|
+
hub.kick();
|
|
3260
|
+
return;
|
|
3261
|
+
}
|
|
3262
|
+
if (stewardSpawning.has(target) || channelGuideSpawning.has(target))
|
|
3263
|
+
return;
|
|
3264
|
+
stewardSpawning.add(target);
|
|
3265
|
+
const name = settleName(wizards, chatNameOf(cfg, target), target) || target;
|
|
3266
|
+
void m.newSession(target, name, { silent: true })
|
|
3267
|
+
.then(() => hub.kick())
|
|
3268
|
+
.catch((e) => roomLog.warn({ target, err: errText(e) }, "room: 管家 pane 起不来 (有唤醒时泵会再试)"))
|
|
3269
|
+
.finally(() => stewardSpawning.delete(target));
|
|
3270
|
+
};
|
|
2366
3271
|
/** 引导落定: 管家进 room → 引导名下 duty 全部转给它并唤醒 → 引导离开 → 完成系统行。
|
|
2367
3272
|
* false = 引导不在这个 room 里 (老流程 / 没走过 room), 调用方自己回一句。 */
|
|
2368
|
-
const guideSettleRoom = (base, bound) => {
|
|
3273
|
+
const guideSettleRoom = (base, bound, roomName = "") => {
|
|
2369
3274
|
const s = roomState(base);
|
|
2370
3275
|
const guideTarget = guideOf(wizards, base);
|
|
2371
3276
|
const guide = guideTarget ? roomSelfOf(guideTarget) : undefined;
|
|
@@ -2374,20 +3279,114 @@ const main = async () => {
|
|
|
2374
3279
|
return false;
|
|
2375
3280
|
// roomMirror 给 daemon 的行补 "[wezard] " 前缀, 完成确认自己已经带了一个。
|
|
2376
3281
|
const text = renderOnboardingDone(bound).replace(/^\[wezard\]\s*/, "");
|
|
2377
|
-
const ops = guideHandoffOps(s, { guide, steward, text, now: Date.now() });
|
|
3282
|
+
const ops = guideHandoffOps(s, { guide, steward, text, now: Date.now(), ...(roomName ? { roomName } : {}) });
|
|
2378
3283
|
if (!ops.length)
|
|
2379
3284
|
return false;
|
|
2380
3285
|
hub.write(base, ops);
|
|
2381
3286
|
roomLog.info({ room: base, guide: guideTarget, steward: bound.target, ops: ops.length }, "onboarding: room 交给管家");
|
|
2382
|
-
// 管家会话还没起: 泵贴不进没绑定的 pane ——
|
|
2383
|
-
|
|
2384
|
-
|
|
2385
|
-
|
|
2386
|
-
|
|
2387
|
-
|
|
3287
|
+
// 管家会话还没起: 泵贴不进没绑定的 pane —— 先起一个 (与频道落定 / boot 兜底同一口子)。
|
|
3288
|
+
spawnStewardPane(bound.target);
|
|
3289
|
+
return true;
|
|
3290
|
+
};
|
|
3291
|
+
/** 一个频道 room / 帖子 room 的 host 座位 + monitor: host 一律是**本 room 的**实例
|
|
3292
|
+
* (人 2026-11-23: 不同的 room 要用不同的实例), 没有就领号新开。幂等 —— 落定与 boot 自愈共用。 */
|
|
3293
|
+
const seatChannelRoom = (room, channelRoom) => {
|
|
3294
|
+
const s = roomState(room);
|
|
3295
|
+
if (!s)
|
|
3296
|
+
return;
|
|
3297
|
+
const who = roomStewardOf(room, channelRoom);
|
|
3298
|
+
if (who) {
|
|
3299
|
+
const ops = hostJoinOps(s, who, Date.now());
|
|
3300
|
+
if (ops.length)
|
|
3301
|
+
hub.write(room, ops);
|
|
3302
|
+
}
|
|
3303
|
+
};
|
|
3304
|
+
/** 绑定落在**频道**上 (wrc.channel.steward): 频道 room 与各帖子 room 各坐**自己那个**实例当
|
|
3305
|
+
* host, 各起一个 monitor (口径③)。引导期这两样都没建 (ensureChannelRoom / channelPostBorn 的
|
|
3306
|
+
* bound 闸), 这里是唯一的补建点 —— 普通群 (channelOf 认不出) = 无操作。 */
|
|
3307
|
+
const settleBoundChannel = (base, bound) => {
|
|
3308
|
+
const topicId = channelOf(cfg, base);
|
|
3309
|
+
if (!topicId)
|
|
3310
|
+
return;
|
|
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))
|
|
3325
|
+
return false;
|
|
3326
|
+
const channelRoom = ensureChannelRoom(topicId);
|
|
3327
|
+
if (!channelMonitorWanted(cfg, wizardStore(), channelRoom))
|
|
3328
|
+
return false; // 引导期不诞生, 人话归引导
|
|
3329
|
+
const at = Date.now();
|
|
3330
|
+
const founder = roomStewardOf(postBase, channelRoom);
|
|
3331
|
+
if (!roomState(postBase)) {
|
|
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 }]);
|
|
2388
3341
|
}
|
|
2389
3342
|
return true;
|
|
2390
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) {
|
|
3358
|
+
try {
|
|
3359
|
+
if (birthPostRoom(d.topicId, d.source, DAEMON))
|
|
3360
|
+
roomLog.info({ room: d.source, channel: d.channelRoom, waitedMin: Math.round((Date.now() - d.at) / 60000) }, "binding: 首触超时, 自动另起帖子 room");
|
|
3361
|
+
}
|
|
3362
|
+
catch (e) {
|
|
3363
|
+
roomLog.warn({ room: d.source, err: errText(e) }, "binding: 兜底另起失败 (下一轮再来)");
|
|
3364
|
+
}
|
|
3365
|
+
}
|
|
3366
|
+
};
|
|
3367
|
+
/** §7 boot 补拉: 存量帖子 room 的 host 实例进频道 room。幂等; 只补成员, 不起 pane (cold 等第一次唤醒)。 */
|
|
3368
|
+
const backfillChannelMembers = () => {
|
|
3369
|
+
let seats = [];
|
|
3370
|
+
try {
|
|
3371
|
+
seats = planChannelBackfill({ cfg, rooms: roomStore.ids(), stateOf: roomState,
|
|
3372
|
+
targetOf: (uid) => roomWizardOf(uid)?.target });
|
|
3373
|
+
}
|
|
3374
|
+
catch (e) {
|
|
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)
|
|
3381
|
+
continue;
|
|
3382
|
+
hub.write(seat.channelRoom, [{ op: "join", at: Date.now(), room: seat.channelRoom, who: seat.who, ord: cs.nextOrd, via: "spawn", by: DAEMON }]);
|
|
3383
|
+
roomLog.info({ room: seat.channelRoom, host: seat.target }, "binding: boot 补拉帖子 host 进频道 room");
|
|
3384
|
+
}
|
|
3385
|
+
};
|
|
3386
|
+
// 首触兜底与看门狗同节拍 (阈值每轮现读, hot)。boot 先等启动那一波过去再扫一次。
|
|
3387
|
+
const decideTimer = setInterval(decideOnFirstTouch, (cfg.rooms?.watchdog?.intervalSec ?? 60) * 1000);
|
|
3388
|
+
decideTimer.unref?.();
|
|
3389
|
+
setTimeout(decideOnFirstTouch, 30_000).unref?.();
|
|
2391
3390
|
/** 引导收尸 (绑定后): 工具调用已经回成功, 等它这一轮结束 (或 60s 上限) 再 kill + drop ——
|
|
2392
3391
|
* 半路杀 pane 会把这一轮截断在 CLI 里。它已经 leave 过 room, 所以 drop 不会再产生
|
|
2393
3392
|
* canceled 行 (leaveRooms 对非成员是空操作)。 */
|
|
@@ -2401,7 +3400,14 @@ const main = async () => {
|
|
|
2401
3400
|
roomLog.info({ guide, killed: r.ok, reason: r.reason }, "onboarding: guide reaped after bind");
|
|
2402
3401
|
};
|
|
2403
3402
|
guideInboundHook = guideTakeover;
|
|
2404
|
-
|
|
3403
|
+
// 群引导的落定也走频道补建: base 是频道 room 时, 绑定后要补 host / monitor (口径③);
|
|
3404
|
+
// 普通群 channelOf 认不出, settleBoundChannel 无操作。settleBoundChannel 幂等。
|
|
3405
|
+
guideSettleHook = (base, bound) => {
|
|
3406
|
+
const ok = guideSettleRoom(base, bound);
|
|
3407
|
+
if (ok)
|
|
3408
|
+
settleBoundChannel(base, bound);
|
|
3409
|
+
return ok;
|
|
3410
|
+
};
|
|
2405
3411
|
// rolepage 的 room 历史路由 (room-ui 的第 4 个接线点): 坏账本按「没有这个 room」处理。
|
|
2406
3412
|
setRoomReader({ ids: roomStore.ids, get: (id) => roomState(id) });
|
|
2407
3413
|
// 回填外层引用 (入站包装在 mirror 块之外)。
|
|
@@ -2448,6 +3454,62 @@ const main = async () => {
|
|
|
2448
3454
|
if (rebound)
|
|
2449
3455
|
classLog.info({ rebound }, "steward bindings rewritten to class names");
|
|
2450
3456
|
}
|
|
3457
|
+
// 绑定自愈 (人 2026-11-23: 不同的 room 要用不同的实例): 早先的 bind-existing 把**别的 room
|
|
3458
|
+
// 的实例名**写进了绑定并把那条化身 join 进来当 host —— 绑定改回类名, 各 room 里换成本 room
|
|
3459
|
+
// 的实例 (没有就领号新开)。幂等; dhtpm 群自己那条不动。
|
|
3460
|
+
// **直绑**: 频道表按裸 topic 只对频道 room 自己, chatPolicy 看自己那一条 —— 只用来找
|
|
3461
|
+
// 「该 room 自己该是哪个类」, 帖子 room 按它所属频道查 (channelClassOf)。
|
|
3462
|
+
const boundClassOf = (room) => {
|
|
3463
|
+
const bare = room.startsWith("chat:") ? room.slice("chat:".length) : "";
|
|
3464
|
+
const name = (bare ? (cfg.wrc.channel.steward ?? {})[bare] : "") || appointedSteward(cfg, room);
|
|
3465
|
+
return name ? (wizards.classes?.byName(name)?.id ?? "") : "";
|
|
3466
|
+
};
|
|
3467
|
+
/** 帖子 room 也是 room: 它的 host 必须是**本 room** 的实例 (人 2026-11-23), 类看所属频道。
|
|
3468
|
+
* 老口径「帖子 room 坐频道管家同一个实例」留下的成员也在这里换掉 —— 只在自愈里用, 不给
|
|
3469
|
+
* unspawnedStewards (那里按直绑补 pane, 帖子 room 的实例等第一次唤醒再冷启动)。 */
|
|
3470
|
+
const channelClassOf = (room) => {
|
|
3471
|
+
const topicId = channelOf(cfg, room);
|
|
3472
|
+
const name = topicId ? (cfg.wrc.channel.steward ?? {})[topicId] ?? "" : "";
|
|
3473
|
+
return name ? (wizards.classes?.byName(name)?.id ?? "") : "";
|
|
3474
|
+
};
|
|
3475
|
+
try {
|
|
3476
|
+
const rep = repairStewardInstances({
|
|
3477
|
+
store: wizards, rooms: roomStore.ids(), stateOf: roomState,
|
|
3478
|
+
write: (room, ops) => { hub.write(room, ops); },
|
|
3479
|
+
rewriteBindings: (aliases) => rewriteStewardBindings(cfg, sourcePath, aliases),
|
|
3480
|
+
boundClassOf: (room) => boundClassOf(room) || channelClassOf(room),
|
|
3481
|
+
});
|
|
3482
|
+
if (rep.rebound || rep.rooms || rep.renamed.length)
|
|
3483
|
+
classLog.info({ ...rep }, "steward instances repaired (per-room)");
|
|
3484
|
+
// 自愈只写成员, 起不了会话: 直绑 room 里「记录在、pane 没有」的管家实例这里补起。
|
|
3485
|
+
// 幂等 (有 pane 的不收); 管存量恢复 (频道那个 OliveBrown-2) 与今后任何 pane 丢失的漂移。
|
|
3486
|
+
const spawn = unspawnedStewards({ store: wizards, rooms: roomStore.ids(), stateOf: roomState,
|
|
3487
|
+
boundClassOf, hasPane: (t) => m.hasMirrorTarget(t) });
|
|
3488
|
+
for (const target of spawn)
|
|
3489
|
+
spawnStewardPane(target);
|
|
3490
|
+
if (spawn.length)
|
|
3491
|
+
classLog.info({ spawn }, "steward panes spawned at boot (记录在, pane 没有)");
|
|
3492
|
+
// 已绑定频道的 room 一个 host 都没有 (绑完就崩 / 老数据): 补本 room 的实例 + monitor。
|
|
3493
|
+
for (const room of roomStore.ids()) {
|
|
3494
|
+
const topicId = channelOf(cfg, room);
|
|
3495
|
+
if (!topicId || !(cfg.wrc.channel.steward ?? {})[topicId])
|
|
3496
|
+
continue;
|
|
3497
|
+
const s = roomState(room);
|
|
3498
|
+
if (s && !roomHost(s))
|
|
3499
|
+
seatChannelRoom(room, "chat:" + topicId);
|
|
3500
|
+
}
|
|
3501
|
+
}
|
|
3502
|
+
catch (e) {
|
|
3503
|
+
classLog.warn({ err: errText(e) }, "steward instance repair failed (不影响启动)");
|
|
3504
|
+
}
|
|
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
|
+
}
|
|
2451
3513
|
// v3 §3: 全局管家身份落位 —— home (defaultChat) 的默认会话就是它的锚点化身。
|
|
2452
3514
|
// 新聊天 (还没有任何会话) 的裸消息由它接待 (inbound stewardRoute); 未认领的新装机不造幽灵记录。
|
|
2453
3515
|
const gs = markGlobalSteward(wizards, cfg.defaultChat);
|
|
@@ -2575,8 +3637,8 @@ const main = async () => {
|
|
|
2575
3637
|
cwdOf: (t) => ((c) => c.runningCwd || c.defaultCwd)(m.getCwd(t)),
|
|
2576
3638
|
}));
|
|
2577
3639
|
/** `who` = 这次变动的当事人 (见 hears): 不给 = 聊天自己的事 (改名), 全群都听。 */
|
|
2578
|
-
//
|
|
2579
|
-
const postRoster = (base, except, n, who) => notices.post(chatAudience(m.chatTargets(base), base, except).filter(
|
|
3640
|
+
// 听众只在主角那个聊天里。
|
|
3641
|
+
const postRoster = (base, except, n, who) => notices.post(chatAudience(m.chatTargets(base), base, except).filter(who ? hears(who) : () => true), n);
|
|
2580
3642
|
/** 注册表里的当事人。要在 forget 抹掉记录之前取; 没有记录 = 谁也不告诉。 */
|
|
2581
3643
|
const subjectOf = (w) => (w
|
|
2582
3644
|
? { parent: w.parent, description: w.description }
|
|
@@ -2705,7 +3767,7 @@ const main = async () => {
|
|
|
2705
3767
|
const loadError = tasks.errors()[x.id];
|
|
2706
3768
|
return {
|
|
2707
3769
|
id: x.id,
|
|
2708
|
-
target: x.target ||
|
|
3770
|
+
target: x.target || (cfg.defaultChat ?? "").trim(),
|
|
2709
3771
|
when: describeTrigger(x.trigger),
|
|
2710
3772
|
nextAt: nextFire(x.trigger, sinceOf(st), nowDate),
|
|
2711
3773
|
lastFired: st.lastFired,
|
|
@@ -2733,6 +3795,7 @@ const main = async () => {
|
|
|
2733
3795
|
// 坏账本跳过并留日志 —— 一个坏文件不该让整张图消失。
|
|
2734
3796
|
rooms: roomFacts(roomStore, wizards.all(), {
|
|
2735
3797
|
chatName: (base) => chatNameOf(cfg, base),
|
|
3798
|
+
channelOf: (room) => channelRefOf(cfg, room),
|
|
2736
3799
|
onBroken: (room, err) => log.warn({ mod: "room", room, err: errText(err) }, "room-facts: 坏账本跳过"),
|
|
2737
3800
|
}),
|
|
2738
3801
|
names: nameTable(wizards.all()),
|
|
@@ -2762,8 +3825,8 @@ const main = async () => {
|
|
|
2762
3825
|
});
|
|
2763
3826
|
/** 自己的地址 = 全局名字, 与住在哪个群无关。 */
|
|
2764
3827
|
const selfAddress = (target) => settleName(wizards, chatNameOf(cfg, target), target);
|
|
2765
|
-
const sharedMemory = (scope, key
|
|
2766
|
-
const path = memoryPath(cfg.daemon.stateDir, scope, key
|
|
3828
|
+
const sharedMemory = (scope, key) => {
|
|
3829
|
+
const path = memoryPath(cfg.daemon.stateDir, scope, key);
|
|
2767
3830
|
return clipForCharter(readMemory(path), path);
|
|
2768
3831
|
};
|
|
2769
3832
|
/** 工作区记忆的键: 身份的工作区 (锚点 workspace) 优先, 没写才退回会话所在目录。记忆只与
|
|
@@ -2803,8 +3866,7 @@ const main = async () => {
|
|
|
2803
3866
|
// 最近动过的排前面: 名册只点名前几个, 截掉的该是早就停了的那些。
|
|
2804
3867
|
// 没有 transcript 的冷记录按 bornAt 算, 刚生下还没开口的照样在。
|
|
2805
3868
|
siblings: m.chatTargets(baseOfKey(target))
|
|
2806
|
-
|
|
2807
|
-
.filter((t) => t !== target && sameBot(target, t))
|
|
3869
|
+
.filter((t) => t !== target)
|
|
2808
3870
|
.map((t) => [t, Math.max(lastTouched(t), wizards.get(t)?.bornAt ?? 0)])
|
|
2809
3871
|
.filter(([, at]) => Date.now() - at <= ROSTER_FRESH_MS)
|
|
2810
3872
|
.sort((x, y) => y[1] - x[1])
|
|
@@ -2815,7 +3877,7 @@ const main = async () => {
|
|
|
2815
3877
|
chatMemory: sharedMemory("chat", baseOfKey(target)),
|
|
2816
3878
|
workspaceMemory: (() => {
|
|
2817
3879
|
const cwd = memoryCwdOf(target, o.cwd);
|
|
2818
|
-
return cwd ? sharedMemory("workspace", cwd
|
|
3880
|
+
return cwd ? sharedMemory("workspace", cwd) : "";
|
|
2819
3881
|
})(),
|
|
2820
3882
|
steward: isStewardTarget(cfg, wizards, target),
|
|
2821
3883
|
...((() => {
|
|
@@ -2886,7 +3948,8 @@ const main = async () => {
|
|
|
2886
3948
|
// 宪章是出生快照: 出生时聊天还没名字的会话, 一辈子自报「(未命名)」。
|
|
2887
3949
|
// 补过名 / 改过名的, 这里把新宪章挂到它下一次注入上。
|
|
2888
3950
|
const want = w.name || "(未命名)";
|
|
2889
|
-
|
|
3951
|
+
// 记号单体 🧙 与旧的 man-mage 全序列都能剥 —— 存量 charters/*.md 是旧写法。
|
|
3952
|
+
const had = /名字: \*\*`(?:🧙(?:♂️)? )?([^`]*)`\*\*/.exec(text)?.[1] ?? "";
|
|
2890
3953
|
if (had && had !== want) {
|
|
2891
3954
|
log.child({ mod: "wizard" }).info({ target: w.target, was: had, now: want }, "charter re-armed after identity change");
|
|
2892
3955
|
m.armCharter(w.target);
|
|
@@ -2900,9 +3963,9 @@ const main = async () => {
|
|
|
2900
3963
|
// v3: 身份/种类随行 —— roster 金字塔的普查按 identity 去重, L0 永远收学徒。
|
|
2901
3964
|
identity: wizards.get(target)?.identity || target,
|
|
2902
3965
|
kind: wizards.get(target)?.kind,
|
|
2903
|
-
parent: ((p) => (p
|
|
2904
|
-
ancestors: ancestorsOf(all, target).
|
|
2905
|
-
clones: childrenOf(all, target).
|
|
3966
|
+
parent: ((p) => (p ? briefOf(self, p) : undefined))(wizards.get(target)?.parent),
|
|
3967
|
+
ancestors: ancestorsOf(all, target).map((t) => briefOf(self, t)),
|
|
3968
|
+
clones: childrenOf(all, target).map((w) => briefOf(self, w.target)),
|
|
2906
3969
|
});
|
|
2907
3970
|
const identityOf = (self, target) => {
|
|
2908
3971
|
const rec = wizards.get(target);
|
|
@@ -2953,9 +4016,9 @@ const main = async () => {
|
|
|
2953
4016
|
};
|
|
2954
4017
|
});
|
|
2955
4018
|
const seen = new Set(live.map((r) => r.target));
|
|
2956
|
-
// live 已由 peers (同 base) / foreignPeers
|
|
4019
|
+
// live 已由 peers (同 base) / foreignPeers 收窄。
|
|
2957
4020
|
const cold = all
|
|
2958
|
-
.filter((w) => !seen.has(w.target)
|
|
4021
|
+
.filter((w) => !seen.has(w.target))
|
|
2959
4022
|
.map((w) => ({
|
|
2960
4023
|
...briefOf(self, w.target),
|
|
2961
4024
|
target: w.target,
|
|
@@ -2995,6 +4058,10 @@ const main = async () => {
|
|
|
2995
4058
|
json(res, 400, { ok: false, reason: "cannot resolve caller session" });
|
|
2996
4059
|
return;
|
|
2997
4060
|
}
|
|
4061
|
+
if (refuseMonitor(res, self, "wizard_identity"))
|
|
4062
|
+
return;
|
|
4063
|
+
if (refuseReception(res, "POST /wizard/identity", self, { targetName: stripSigil(String(body.to ?? "")) }))
|
|
4064
|
+
return;
|
|
2998
4065
|
const addressError = unsupportedPeerAddressField(body);
|
|
2999
4066
|
if (addressError) {
|
|
3000
4067
|
json(res, 400, { ok: false, reason: addressError });
|
|
@@ -3013,7 +4080,6 @@ const main = async () => {
|
|
|
3013
4080
|
const callerSteward = !!caller && caller.ordinal !== undefined
|
|
3014
4081
|
&& wizards.classes?.get(identityOfRec(caller))?.role === "steward";
|
|
3015
4082
|
const refusal = identityEditRefusal(victim, {
|
|
3016
|
-
sameBot: sameBot(self, target),
|
|
3017
4083
|
editorIsParent: victim?.parent === self,
|
|
3018
4084
|
editorIsStewardInstance: callerSteward,
|
|
3019
4085
|
});
|
|
@@ -3103,10 +4169,12 @@ const main = async () => {
|
|
|
3103
4169
|
const instances = isInstance && cls ? after : [];
|
|
3104
4170
|
// 类名 (不是实例名 X-N): 响应与 note 都按绑定/寻址用的那个名字说话。
|
|
3105
4171
|
const className = isInstance && cls ? (wizards.classes?.get(cls.id)?.name ?? cls.name) : "";
|
|
4172
|
+
// 「已被占用」按落定名判定: 类实例落定的是类名, 不是 <类名>-<序号> (后者比出来永远不等)。
|
|
4173
|
+
const notice = renameNotice(asked, className || name);
|
|
3106
4174
|
json(res, 200, {
|
|
3107
4175
|
ok: true,
|
|
3108
4176
|
...me,
|
|
3109
|
-
...(
|
|
4177
|
+
...(notice ? { renamed: notice } : {}),
|
|
3110
4178
|
...(isInstance && cls
|
|
3111
4179
|
? {
|
|
3112
4180
|
class: { was: cls.name, name: className, instances: instances.map((w) => w.name) },
|
|
@@ -3266,6 +4334,8 @@ const main = async () => {
|
|
|
3266
4334
|
json(res, 400, { ok: false, reason: "cannot resolve caller session" });
|
|
3267
4335
|
return;
|
|
3268
4336
|
}
|
|
4337
|
+
if (refuseMonitor(res, self, "delegate"))
|
|
4338
|
+
return;
|
|
3269
4339
|
if (refuseGuide(res, self, "delegate"))
|
|
3270
4340
|
return;
|
|
3271
4341
|
const addressError = unsupportedPeerAddressField(body);
|
|
@@ -3366,7 +4436,7 @@ const main = async () => {
|
|
|
3366
4436
|
return { status: target.status ?? 400, body: { ok: false, reason: target.error ?? target.reason ?? "" } };
|
|
3367
4437
|
// lead 的层级规矩随正文带 (宪章是出生快照, 打法只这一件活用得上)。
|
|
3368
4438
|
const body2 = lead ? text + "\n\n" + renderReminder({ wezard: "lead" }, wizards.byUid(who.id)?.lead ? renderLeadPlaybook() : renderLead()) : text;
|
|
3369
|
-
const forOf = ((b.for ?? "").toString()
|
|
4439
|
+
const { for: forOf, note: forNote } = hub.resolveForEx(me.id, (b.for ?? "").toString());
|
|
3370
4440
|
const draft = { author: me, kind: "task", text: body2, to: [who], origin: "tool",
|
|
3371
4441
|
...(forOf ? { for: forOf } : {}),
|
|
3372
4442
|
...(planId ? { planId } : {}) };
|
|
@@ -3378,6 +4448,7 @@ const main = async () => {
|
|
|
3378
4448
|
return { status: placed.status, body: { ok: false, reason: placed.reason } };
|
|
3379
4449
|
const v = placed.verdict;
|
|
3380
4450
|
return { status: 200, body: { ok: true, room: v.row.room, id: v.row.id, event: v.row.id, name: peerAddress(cfg, wizards.byUid(who.id)?.target ?? who.id), queued: true,
|
|
4451
|
+
...(forNote ? { forNote } : {}),
|
|
3381
4452
|
receipt: "已持久化排队; 结论经 chat_reply({re, text, status}) 交代" } };
|
|
3382
4453
|
};
|
|
3383
4454
|
if (d.kind === "existing" && !to && d.row?.target) {
|
|
@@ -3437,6 +4508,10 @@ const main = async () => {
|
|
|
3437
4508
|
json(res, 400, { ok: false, reason: "cannot resolve caller session" });
|
|
3438
4509
|
return;
|
|
3439
4510
|
}
|
|
4511
|
+
if (refuseMonitor(res, self, "wizard_remember"))
|
|
4512
|
+
return;
|
|
4513
|
+
if (refuseReception(res, "POST /wizard/remember", self, { scope: String(body.scope ?? "self") }))
|
|
4514
|
+
return;
|
|
3440
4515
|
const b = body;
|
|
3441
4516
|
const note = (b.note ?? "").toString().trim();
|
|
3442
4517
|
const forget = (b.forget ?? "").toString().trim();
|
|
@@ -3451,10 +4526,8 @@ const main = async () => {
|
|
|
3451
4526
|
json(res, 400, { ok: false, reason: "note 和 forget 至少给一个" });
|
|
3452
4527
|
return;
|
|
3453
4528
|
}
|
|
3454
|
-
|
|
3455
|
-
const
|
|
3456
|
-
const path = memoryPath(cfg.daemon.stateDir, scope, key, bot);
|
|
3457
|
-
const queued = proposeMemory(inboxPath(cfg.daemon.stateDir, scope, key, bot), {
|
|
4529
|
+
const path = memoryPath(cfg.daemon.stateDir, scope, key);
|
|
4530
|
+
const queued = proposeMemory(inboxPath(cfg.daemon.stateDir, scope, key), {
|
|
3458
4531
|
at: Date.now(),
|
|
3459
4532
|
by: selfAddress(self),
|
|
3460
4533
|
...(scope === "workspace" ? { cwd: key } : {}),
|
|
@@ -3561,7 +4634,7 @@ const main = async () => {
|
|
|
3561
4634
|
return { status: 409, body: { ok: false, reason: `${displayName(source)} 没有可 fork 的会话 (还没说过话, 或绑定已失效)` } };
|
|
3562
4635
|
}
|
|
3563
4636
|
const wantChat = (b.chat ?? "").toString().trim();
|
|
3564
|
-
const base = (
|
|
4637
|
+
const base = (wantChat ? chatBaseOf(cfg, wantChat) : baseOfKey(self));
|
|
3565
4638
|
if (!base) {
|
|
3566
4639
|
return { status: 404, body: {
|
|
3567
4640
|
ok: false,
|
|
@@ -3663,7 +4736,7 @@ const main = async () => {
|
|
|
3663
4736
|
if (!dest.room)
|
|
3664
4737
|
dispatchError = dest.error ?? dest.reason ?? "没有落点 room";
|
|
3665
4738
|
else {
|
|
3666
|
-
const forOf = ((b.for ?? "").toString()
|
|
4739
|
+
const forOf = hub.resolveFor(me.id, (b.for ?? "").toString());
|
|
3667
4740
|
const draft = { author: me, kind: "task",
|
|
3668
4741
|
text: task + (b.lead === true ? "\n\n" + renderReminder({ wezard: "lead" }, renderLeadPlaybook()) : ""),
|
|
3669
4742
|
to: [{ kind: "wizard", id: who }], origin: "tool", ...(requestedPlanId ? { planId: requestedPlanId } : {}),
|
|
@@ -3695,6 +4768,10 @@ const main = async () => {
|
|
|
3695
4768
|
json(res, 400, { ok: false, reason: "cannot resolve caller session" });
|
|
3696
4769
|
return;
|
|
3697
4770
|
}
|
|
4771
|
+
if (refuseMonitor(res, self, "spawn_wizard"))
|
|
4772
|
+
return;
|
|
4773
|
+
if (refuseReception(res, "POST /wizard/clone", self, { inherit: !!body.inherit }))
|
|
4774
|
+
return;
|
|
3698
4775
|
if (refuseGuide(res, self, body.inherit ? "clone_wizard" : "spawn_wizard"))
|
|
3699
4776
|
return;
|
|
3700
4777
|
const r = await bearAs(self, body);
|
|
@@ -3722,6 +4799,10 @@ const main = async () => {
|
|
|
3722
4799
|
json(res, 400, { ok: false, reason: "cannot resolve caller session" });
|
|
3723
4800
|
return;
|
|
3724
4801
|
}
|
|
4802
|
+
if (refuseMonitor(res, self, "stop_wizard"))
|
|
4803
|
+
return;
|
|
4804
|
+
if (refuseReception(res, "POST /wizard/stop", self, { targetName: stripSigil(String(body.name ?? "")) }))
|
|
4805
|
+
return;
|
|
3725
4806
|
const addressError = unsupportedPeerAddressField(body);
|
|
3726
4807
|
if (addressError) {
|
|
3727
4808
|
json(res, 400, { ok: false, reason: addressError });
|
|
@@ -3731,7 +4812,7 @@ const main = async () => {
|
|
|
3731
4812
|
const r = resolvePeer(self, addrOf(b));
|
|
3732
4813
|
// 有身份没会话 (冷记录 / 生到一半的僵尸): resolvePeer 够不着它, 但收它不需要
|
|
3733
4814
|
// 会话 —— end 视为早已结束, forget 删掉记录、腾出名字。interrupt 无从谈起。
|
|
3734
|
-
const found = r.ok || r.candidates?.length ? undefined :
|
|
4815
|
+
const found = r.ok || r.candidates?.length ? undefined : wizards.byName(addrOf(b));
|
|
3735
4816
|
const cold = found && !m.chatTargets(baseOfKey(found.target)).includes(found.target) ? found : undefined;
|
|
3736
4817
|
if (cold && found?.kind === "apprentice") {
|
|
3737
4818
|
json(res, 409, { ok: false, target: found.target, reason: "学徒是连续身份 (代表人, 每 bot 实例唯一), 不可结束或退役" });
|
|
@@ -3812,7 +4893,12 @@ const main = async () => {
|
|
|
3812
4893
|
}
|
|
3813
4894
|
// 按件号撤回自己派的那一件 (room 模型): daemon 代写一条 canceled reply 关掉 duty,
|
|
3814
4895
|
// 它此刻正在做的就是这件才按 Esc —— 被打断那一轮的其余 duty 不关 (§3b), 下次唤醒重投。
|
|
3815
|
-
const
|
|
4896
|
+
const turnRef = expandMsgRefs(self, [(b.turn ?? "").toString().trim()]);
|
|
4897
|
+
if (turnRef.error) {
|
|
4898
|
+
json(res, 400, { ok: false, reason: turnRef.error });
|
|
4899
|
+
return;
|
|
4900
|
+
}
|
|
4901
|
+
const turn = turnRef.ids[0] ?? "";
|
|
3816
4902
|
if (!end && turn) {
|
|
3817
4903
|
const roomId = roomStore.roomOfMsg(turn);
|
|
3818
4904
|
const s = roomId ? roomState(roomId) : undefined;
|
|
@@ -3860,6 +4946,19 @@ const main = async () => {
|
|
|
3860
4946
|
retiringWizardTargets.delete(target);
|
|
3861
4947
|
}
|
|
3862
4948
|
});
|
|
4949
|
+
/** 名册里的 tier 跟着实际模型走 (shared/model-tiers): 换过模型 / effort 之后按该后端档位表反查,
|
|
4950
|
+
* 变了才写盘。反查不出 = 这张表里没有这个模型, tier 清掉 —— 聪明度宁可不画, 也不拿别的档位猜。 */
|
|
4951
|
+
const retierOf = (target) => {
|
|
4952
|
+
const info = m.sessionInfo(target);
|
|
4953
|
+
const rec = wizards.get(target);
|
|
4954
|
+
// 模型没记下来 (冷记录 / 只改了 effort): 没有可比的那一项, 不动档位 —— 不拿 effort 猜。
|
|
4955
|
+
if (!info || !rec || !info.model.trim())
|
|
4956
|
+
return undefined;
|
|
4957
|
+
const probe = tierOfModel(cfg, info.cli, info.model, info.effort, rec.tier);
|
|
4958
|
+
if ((rec.tier ?? "") !== (probe.tier ?? ""))
|
|
4959
|
+
wizards.upsert(target, { tier: probe.tier });
|
|
4960
|
+
return probe;
|
|
4961
|
+
};
|
|
3863
4962
|
// 换模型 / effort: 省略名字 = 换自己 (选择器盖在正在跑的这一轮上面照样能开), 点名 =
|
|
3864
4963
|
// 换那个 wizard。与 spawn 时的 `model` 是同一条路 (model-select.ts); effort 走
|
|
3865
4964
|
// `/effort` 档位条的「只本会话」键, 不碰全机默认。两样都给就先模型后档位。
|
|
@@ -3869,6 +4968,8 @@ const main = async () => {
|
|
|
3869
4968
|
json(res, 400, { ok: false, reason: "cannot resolve caller session" });
|
|
3870
4969
|
return;
|
|
3871
4970
|
}
|
|
4971
|
+
if (refuseMonitor(res, self, "set_model"))
|
|
4972
|
+
return;
|
|
3872
4973
|
if (refuseGuide(res, self, "set_model"))
|
|
3873
4974
|
return;
|
|
3874
4975
|
const addressError = unsupportedPeerAddressField(body);
|
|
@@ -3902,6 +5003,8 @@ const main = async () => {
|
|
|
3902
5003
|
const done = model ? await m.setModel(r.target, model, scope) : undefined;
|
|
3903
5004
|
const eff = effort && (done?.ok ?? true) ? await m.setEffort(r.target, effort) : undefined;
|
|
3904
5005
|
const ok = (done?.ok ?? true) && (eff?.ok ?? true);
|
|
5006
|
+
// 聪明度只认 tier: 换过之后按该后端同一张档位表反查, 名册跟着改 (反查不出就清掉, 不猜)。
|
|
5007
|
+
const probe = ok ? retierOf(r.target) : undefined;
|
|
3905
5008
|
json(res, ok ? 200 : 502, {
|
|
3906
5009
|
...done,
|
|
3907
5010
|
ok,
|
|
@@ -3909,6 +5012,7 @@ const main = async () => {
|
|
|
3909
5012
|
name: briefOf(self, r.target).name,
|
|
3910
5013
|
...(done?.ok ? { model: done.applied } : {}),
|
|
3911
5014
|
...(eff?.ok ? { effort: eff.applied } : {}),
|
|
5015
|
+
...(probe ? (probe.tier ? { tier: probe.tier } : { tierUnknown: true }) : {}),
|
|
3912
5016
|
...(eff && !eff.ok ? { reason: [done?.reason, `effort: ${eff.reason}`].filter(Boolean).join("; ") } : {}),
|
|
3913
5017
|
});
|
|
3914
5018
|
});
|
|
@@ -4004,6 +5108,10 @@ const main = async () => {
|
|
|
4004
5108
|
json(res, 400, { ok: false, reason: "cannot resolve caller session" });
|
|
4005
5109
|
return;
|
|
4006
5110
|
}
|
|
5111
|
+
if (refuseMonitor(res, self, "schedule_task"))
|
|
5112
|
+
return;
|
|
5113
|
+
if (refuseReception(res, "POST /tasks/schedule", self))
|
|
5114
|
+
return;
|
|
4007
5115
|
const addressError = unsupportedPeerAddressField(body);
|
|
4008
5116
|
if (addressError) {
|
|
4009
5117
|
json(res, 400, { ok: false, reason: addressError });
|
|
@@ -4034,11 +5142,6 @@ const main = async () => {
|
|
|
4034
5142
|
}
|
|
4035
5143
|
target = r.target;
|
|
4036
5144
|
}
|
|
4037
|
-
// owner = self; resolvePeer 已拦住别的机器人的名字, 这一道是给以后别的取 target 的路兜底。
|
|
4038
|
-
if (!sameBot(self, target)) {
|
|
4039
|
-
json(res, 404, { ok: false, reason: `no wizard named '.${address}' — wizard_roster lists every name` });
|
|
4040
|
-
return;
|
|
4041
|
-
}
|
|
4042
5145
|
// 到点是新建还是续用, 在**排班时**就定死。两条都指向新建:
|
|
4043
5146
|
// · 没点名 wizard —— 定时的 prompt 本就要求零上下文自洽, 没理由挑一个会话挤进去;
|
|
4044
5147
|
// · prompt 自己就在说「建两个 wizard 去干 xxx」—— 这时 name 只是「在谁的聊天/
|
|
@@ -4073,10 +5176,10 @@ const main = async () => {
|
|
|
4073
5176
|
const now = new Date();
|
|
4074
5177
|
const errs = tasks.errors();
|
|
4075
5178
|
const rows = tasks.list()
|
|
4076
|
-
.filter((t) =>
|
|
5179
|
+
.filter((t) => !mineOnly || ownerOf(t) === self)
|
|
4077
5180
|
.map((t) => ({
|
|
4078
5181
|
...renderTask(t, tasks.stateOf(t.id), now, errs[t.id]),
|
|
4079
|
-
address: peerAddress(cfg, t.target ||
|
|
5182
|
+
address: peerAddress(cfg, t.target || cfg.defaultChat.trim()),
|
|
4080
5183
|
owner: peerAddress(cfg, ownerOf(t)),
|
|
4081
5184
|
}));
|
|
4082
5185
|
// 加载失败的那些没有记录可回显, 但必须出现在列表里 —— 否则 wizard 改错了
|
|
@@ -4092,6 +5195,8 @@ const main = async () => {
|
|
|
4092
5195
|
json(res, 400, { ok: false, reason: "cannot resolve caller session" });
|
|
4093
5196
|
return;
|
|
4094
5197
|
}
|
|
5198
|
+
if (refuseReception(res, "POST /tasks/cancel", self))
|
|
5199
|
+
return;
|
|
4095
5200
|
const id = (body.id ?? "").toString().trim();
|
|
4096
5201
|
if (!id) {
|
|
4097
5202
|
json(res, 400, { ok: false, reason: "id required (list_tasks 里那个 id)" });
|
|
@@ -4099,10 +5204,6 @@ const main = async () => {
|
|
|
4099
5204
|
}
|
|
4100
5205
|
// 别的机器人的日程与不存在同形。
|
|
4101
5206
|
const rec = tasks.get(id);
|
|
4102
|
-
if (rec && !sameBot(self, ownerOf(rec))) {
|
|
4103
|
-
json(res, 404, { ok: false, reason: `no schedule with id ${id}` });
|
|
4104
|
-
return;
|
|
4105
|
-
}
|
|
4106
5207
|
const state = tasks.stateOf(id);
|
|
4107
5208
|
const gone = tasks.remove(id);
|
|
4108
5209
|
if (!gone) {
|
|
@@ -4190,11 +5291,10 @@ const main = async () => {
|
|
|
4190
5291
|
return "";
|
|
4191
5292
|
const ask = `${c.reload ? "守护进程 reload 之后, " : ""}需要显式 /new 才能载入新宪章;handoff /clear 保留原进程的系统提示,不会使这次改动生效`;
|
|
4192
5293
|
hits.filter((h) => h.target !== c.self).forEach((h) => notices.post([h.target], `${c.what} 改动了你的宪章 (系统提示, 变了的段: ${h.sections.join(" / ")}); ${ask}`));
|
|
4193
|
-
const shown = hits.filter((h) => sameBot(c.self ?? "", h.target));
|
|
4194
5294
|
const mine = hits.find((h) => h.target === c.self);
|
|
4195
5295
|
return [
|
|
4196
5296
|
"",
|
|
4197
|
-
`⚠ 这次改动进了宪章 (系统提示)。${ask}。受影响 ${
|
|
5297
|
+
`⚠ 这次改动进了宪章 (系统提示)。${ask}。受影响 ${hits.length} 个: ${hits.map((h) => displayName(h.target)).join(" ")}`,
|
|
4198
5298
|
...(mine ? [`**你自己也在其中** (变了的段: ${mine.sections.join(" / ")})`] : []),
|
|
4199
5299
|
].join("\n");
|
|
4200
5300
|
};
|
|
@@ -4220,8 +5320,6 @@ const main = async () => {
|
|
|
4220
5320
|
return { r, note: Promise.resolve(fail(e)) };
|
|
4221
5321
|
}
|
|
4222
5322
|
};
|
|
4223
|
-
/** 配置的调用方: 只认 sessionId / pane, 不回落 defaultChat (同 config_set 的 caller)。认不出 = "" (主机器人)。 */
|
|
4224
|
-
const configCaller = (b) => (b.sessionId?.trim() && m.targetForSession(b.sessionId.trim())) || (b.tmuxPane?.trim() && m.targetForPane(b.tmuxPane.trim())) || "";
|
|
4225
5323
|
// POST /config/get —— `path` (可空) 拿渲染好的配置文本。
|
|
4226
5324
|
http.register("POST /config/get", async (req, res) => {
|
|
4227
5325
|
const body = (await readBody(req));
|
|
@@ -4229,12 +5327,10 @@ const main = async () => {
|
|
|
4229
5327
|
json(res, 400, { ok: false, reason: "key is unsupported; use path" });
|
|
4230
5328
|
return;
|
|
4231
5329
|
}
|
|
4232
|
-
const seen = cfgSeenBy(cfg, configCaller(body));
|
|
4233
5330
|
// chatPolicy.<聊天名>… 换成它指向的 principal 再查 (同 config_set 的 pinChatKeys); 认不出的原样查。
|
|
4234
|
-
// 名字按调用方看得见的表解析: 别的机器人的聊天名认不出, principal 写法在 seen 里也查无此键。
|
|
4235
5331
|
const p = parsePath(body.path);
|
|
4236
|
-
const base = p[0] === "chatPolicy" && p[1] ? chatBaseOf(
|
|
4237
|
-
const r = configGet(
|
|
5332
|
+
const base = p[0] === "chatPolicy" && p[1] ? chatBaseOf(cfg, p[1]) : "";
|
|
5333
|
+
const r = configGet(cfg, sourcePath, base ? ["chatPolicy", base, ...p.slice(2)].join(".") : body.path, configEvidence);
|
|
4238
5334
|
json(res, r.ok ? 200 : 400, r);
|
|
4239
5335
|
});
|
|
4240
5336
|
// POST /config/set —— 口令门见 `guarded`。分级在这里而不在 hook: `card` 项由守护进程
|
|
@@ -4247,7 +5343,9 @@ const main = async () => {
|
|
|
4247
5343
|
return;
|
|
4248
5344
|
}
|
|
4249
5345
|
const body = raw;
|
|
4250
|
-
|
|
5346
|
+
if (refuseReception(res, "POST /config/set", resolveSelf(body)))
|
|
5347
|
+
return;
|
|
5348
|
+
const ask = pinChatKeys(cfg, body);
|
|
4251
5349
|
if ("ok" in ask) {
|
|
4252
5350
|
json(res, 400, ask);
|
|
4253
5351
|
return;
|
|
@@ -4274,6 +5372,8 @@ const main = async () => {
|
|
|
4274
5372
|
return now;
|
|
4275
5373
|
patchJsonc(sourcePath, [{ path: now.jsonPath, value: now.value }]);
|
|
4276
5374
|
applyHot(cfg, now);
|
|
5375
|
+
// 新加的调用方在第一次调用之前就要有口令文件可读 (agent 拿不到口令就发不出请求)。
|
|
5376
|
+
external.syncTokens();
|
|
4277
5377
|
return now;
|
|
4278
5378
|
}, (now) => now.ok ? { what: `\`config_set ${now.path.join(".")}\``, self: caller, byHuman, reload: now.apply === "reload", after: charterUnder(now) } : undefined);
|
|
4279
5379
|
return now.ok ? { ...now, charter: await note } : now;
|
|
@@ -4353,9 +5453,6 @@ const main = async () => {
|
|
|
4353
5453
|
// 才把这句话直接投进它那一轮 —— 「在已有会话里继续」是要求出来的, 不是默认。
|
|
4354
5454
|
scheduledTaskInject = async (target, text, opts) => {
|
|
4355
5455
|
const { taskId, fresh, quiet } = opts;
|
|
4356
|
-
const owner = ((r) => (r ? ownerOf(r) : target))(tasks.get(taskId));
|
|
4357
|
-
if (!sameBot(owner, target))
|
|
4358
|
-
return { ok: false, reason: `日程 ${taskId} 的目标与排班者归不同的企微机器人, 不跨机器人放枪` };
|
|
4359
5456
|
// 已有会话的一枪 = 一条 trigger 行 (cutmap G-1): 不镜像, 只唤醒 owner;
|
|
4360
5457
|
// 唤醒一律等它本轮结束 (泵自己等), 不再顺延 / quiet 旁路转发 —— 它的结论只经
|
|
4361
5458
|
// chat_reply / chat_say 进 room, 终句零语义 (契约 §5)。
|
|
@@ -4526,7 +5623,7 @@ const main = async () => {
|
|
|
4526
5623
|
refsOf: (md) => {
|
|
4527
5624
|
// cwd 候选: 提议里带的 (提议者可能早收工了) + 在场绑定的; 再正向算出 md 比对。
|
|
4528
5625
|
const cwds = [...new Set([...proposedCwds(stateDir), ...boundTargets().map((t) => memoryCwdOf(t))].filter(Boolean))];
|
|
4529
|
-
const cwd = cwdOfMd(stateDir, md, cwds
|
|
5626
|
+
const cwd = cwdOfMd(stateDir, md, cwds);
|
|
4530
5627
|
if (!cwd)
|
|
4531
5628
|
return [];
|
|
4532
5629
|
return [...PROJECT_DOCS.map((f) => join(cwd, f)), ...projectDirsFor(cwd).map((d) => join(d.dir, "memory", "MEMORY.md"))].filter((f) => existsSync(f));
|
|
@@ -4565,7 +5662,7 @@ const main = async () => {
|
|
|
4565
5662
|
// gate 里的 `sh` 默认就在目标 wizard 此刻的工作区跑 —— 任务文件里不必写死绝对路径。
|
|
4566
5663
|
cwdOf: (t) => { const c = bridge.getCwd(t); return c.runningCwd || c.pendingCwd || c.defaultCwd; },
|
|
4567
5664
|
// 没写 target 的日程兜底到排班者那个机器人的默认聊天 (副机器人没配就不放枪, 不冒用主机器人)。
|
|
4568
|
-
fallbackTarget: (t) =>
|
|
5665
|
+
fallbackTarget: (t) => cfg.defaultChat.trim(),
|
|
4569
5666
|
});
|
|
4570
5667
|
// 共享记忆整理 — daemon 内建, 不进任务表 / 日程, 不出任何气泡。
|
|
4571
5668
|
const steward = stewardRun
|