pi-web-ui 0.114.2 → 0.115.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +55 -1
- package/bin/pi-web-ui.mjs +69 -7
- package/dist/server/agent-service-daemon.js +440 -32
- package/dist/server/agent-service.js +878 -383
- package/dist/server/canvas/canvas-dispatch.js +13 -1
- package/dist/server/client-state.js +25 -0
- package/dist/server/communicate-tool.js +2 -0
- package/dist/server/context-usage.js +105 -0
- package/dist/server/conversation-communication.js +14 -0
- package/dist/server/conversation-identity.js +27 -0
- package/dist/server/device-center/approval-summary.js +31 -0
- package/dist/server/device-center/bot-catalog.js +21 -7
- package/dist/server/device-center/bot-execution.js +72 -9
- package/dist/server/device-center/bot-presets.js +46 -0
- package/dist/server/device-center/collab-service.js +328 -10
- package/dist/server/device-center/collab-tool.js +738 -12
- package/dist/server/device-center/connector.js +359 -23
- package/dist/server/device-center/desktop-page.js +22 -16
- package/dist/server/device-center/device-integration.js +595 -0
- package/dist/server/device-center/execution-guides.js +32 -0
- package/dist/server/device-center/execution-instructions.js +19 -0
- package/dist/server/device-center/execution-settings.js +100 -0
- package/dist/server/device-center/execution-system-prompt.js +38 -0
- package/dist/server/device-center/execution-workspace.js +20 -0
- package/dist/server/device-center/executor.js +389 -40
- package/dist/server/device-center/file-sync-paths.js +171 -0
- package/dist/server/device-center/file-sync.js +180 -91
- package/dist/server/device-center/group-context-delta.js +37 -0
- package/dist/server/device-center/group-context-message.js +208 -0
- package/dist/server/device-center/group-context.js +109 -0
- package/dist/server/device-center/group-events.js +136 -0
- package/dist/server/device-center/group-plan-guard.js +138 -0
- package/dist/server/device-center/hub-conversations.js +178 -0
- package/dist/server/device-center/hub-deliveries.js +277 -0
- package/dist/server/device-center/hub-integration.js +451 -0
- package/dist/server/device-center/hub.js +1544 -80
- package/dist/server/device-center/human-interaction.js +232 -0
- package/dist/server/device-center/integration-errors.js +25 -0
- package/dist/server/device-center/local-hub.js +18 -0
- package/dist/server/device-center/local.js +356 -40
- package/dist/server/device-center/main.js +11 -1
- package/dist/server/device-center/path-portal.js +11 -3
- package/dist/server/device-center/relay.js +364 -35
- package/dist/server/device-center/report-metadata.js +66 -0
- package/dist/server/device-center/report-upload.js +63 -0
- package/dist/server/device-center/runtime.js +549 -41
- package/dist/server/device-center/store.js +66 -3
- package/dist/server/device-center/task-context-budget.js +161 -0
- package/dist/server/device-center/task-journal.js +385 -0
- package/dist/server/device-center/task-plan.js +33 -0
- package/dist/server/device-center/task-progress.js +141 -0
- package/dist/server/device-center/task-recovery.js +452 -0
- package/dist/server/device-center/task-report-outbox.js +216 -0
- package/dist/server/device-center/task-report.js +384 -0
- package/dist/server/device-center/task-scheduler.js +400 -0
- package/dist/server/device-center/task-state.js +333 -0
- package/dist/server/device-center/transfer-stream.js +1006 -0
- package/dist/server/device-center/transfers.js +815 -8
- package/dist/server/dispatch-domain-handlers.js +21 -3
- package/dist/server/dsh/dsh-agent-service.js +6 -0
- package/dist/server/goal-service.js +10 -5
- package/dist/server/index.js +89 -13
- package/dist/server/message-deletion.js +40 -0
- package/dist/server/message-window.js +9 -0
- package/dist/server/patch-executable-lookup.js +396 -0
- package/dist/server/payload-limits.js +2 -0
- package/dist/server/plugin-llm.js +100 -9
- package/dist/server/plugins.js +1 -0
- package/dist/server/preset-fields.js +24 -0
- package/dist/server/preset-share.js +2 -0
- package/dist/server/prompt-base-store.js +85 -0
- package/dist/server/prompt-composer.js +5 -2
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/protocol.js +2 -2
- package/dist/server/remote-ssh-service.js +22 -9
- package/dist/server/resolve-global-sdk.js +2 -0
- package/dist/server/session-search.js +1 -1
- package/dist/server/settings-service.js +90 -39
- package/dist/server/skill-content-filler.js +29 -8
- package/dist/server/skill-tool.js +12 -3
- package/dist/server/subagent-helpers.js +4 -1
- package/dist/server/subagents.js +50 -36
- package/dist/server/tool-host-factories.js +1 -0
- package/dist/server/universal/universal-session.js +5 -0
- package/dist/server/webui-context.js +25 -5
- package/docs/README.md +94 -0
- package/docs/device-center.md +100 -12
- package/docs/dsh-engine.md +10 -10
- package/extensions/webui.ts +43 -1
- package/package.json +1 -1
- package/themes/aetheris.css +5 -0
- package/themes/ayu-light.css +6 -0
- package/themes/bases/flow-base.css +68 -68
- package/themes/catppuccin-latte.css +6 -0
- package/themes/catppuccin.css +6 -0
- package/themes/claude-code-dark.css +5 -0
- package/themes/codex.css +6 -0
- package/themes/cyberpunk.css +6 -0
- package/themes/dark-teal.css +6 -1
- package/themes/dazzle.css +6 -0
- package/themes/everforest-light.css +6 -0
- package/themes/flow-light.css +8 -1
- package/themes/flow.css +6 -1
- package/themes/geist.css +6 -0
- package/themes/gruvbox-light.css +6 -0
- package/themes/kanagawa-lotus.css +6 -0
- package/themes/md-preview.css +6 -0
- package/themes/mist.css +6 -0
- package/themes/nord.css +6 -0
- package/themes/one-dark.css +6 -0
- package/themes/paper.css +6 -0
- package/themes/rose-pine-dawn.css +6 -0
- package/themes/sakura.css +6 -0
- package/themes/solarized-light.css +6 -0
- package/themes/tokyo-night.css +6 -0
- package/themes/translucent.css +6 -0
- package/themes/transparent.css +6 -0
- package/themes/vs-code-dark.css +5 -0
- package/themes/wallpaper-flow.css +5 -1
- package/themes/wallpaper-obsidian.css +6 -0
- package/themes/white.css +6 -0
- package/themes/zhujian-dark.css +6 -1
- package/themes/zhujian.css +6 -1
- package/themes/zhupi-dark.css +6 -1
- package/themes/zhupi.css +6 -1
- package/web/dist/.build-assets.json +1 -1
- package/web/dist/assets/BgTasksModal-BYzPgmoq.js +1 -0
- package/web/dist/assets/BgTasksModal-ni0VTmAQ.js +1 -0
- package/web/dist/assets/{CanvasStudio-B3W6b_rA.js → CanvasStudio-BCUeEf25.js} +3 -3
- package/web/dist/assets/{CanvasStudio-Csv1Sj1-.js → CanvasStudio-DNmDNBod.js} +3 -3
- package/web/dist/assets/DeviceCenter-BcBhRgL6.js +3 -0
- package/web/dist/assets/DeviceCenter-CmL5FZmt.js +3 -0
- package/web/dist/assets/DeviceGroups-CLdpdnI7.js +1 -0
- package/web/dist/assets/DeviceGroups-CgBaDPrD.js +1 -0
- package/web/dist/assets/Dropdown-CGXD0DfT.js +1 -0
- package/web/dist/assets/FilePreview-B8iqnBjy.js +2 -0
- package/web/dist/assets/FilePreview-BqviZKCN.js +2 -0
- package/web/dist/assets/GlobalSearchModal-mevF-ySi.js +1 -0
- package/web/dist/assets/GlobalSearchModal-qL99FN_F.js +1 -0
- package/web/dist/assets/GroupConversation-B88Yy-lt.js +3 -0
- package/web/dist/assets/GroupConversation-BwP5NVOE.js +3 -0
- package/web/dist/assets/HintTip-LHwkS2jV.js +1 -0
- package/web/dist/assets/ModelConfigModal-Do3Fe3jH.js +2 -0
- package/web/dist/assets/PiSetupModal-DE5-gEtI.js +1 -0
- package/web/dist/assets/ProviderOAuthControls-6UMARucA.js +1 -0
- package/web/dist/assets/SCMPanel-Hi6QqC1Q.js +2 -0
- package/web/dist/assets/SCMPanel-ezY_ZtCu.js +2 -0
- package/web/dist/assets/SettingsModal-6HgeEsJ8.js +20 -0
- package/web/dist/assets/SettingsModal-CF-7MwqS.js +20 -0
- package/web/dist/assets/TerminalPanel-CTp_BZ4S.js +3 -0
- package/web/dist/assets/TerminalPanel-CkYxC-Gh.js +3 -0
- package/web/dist/assets/TuiOverlayModal-1cRLP8IF.js +1 -0
- package/web/dist/assets/TuiOverlayModal-2xlptqWX.js +1 -0
- package/web/dist/assets/app-globals-DZNa9v8u.js +325 -0
- package/web/dist/assets/canvas-client-Bye9nSFO.js +1 -0
- package/web/dist/assets/{desktop-YguLbrX1.js → desktop-kjBoE3Nu.js} +1 -1
- package/web/dist/assets/group-view-state-CGCzYF8k.js +1 -0
- package/web/dist/assets/index-CsFs_HMb.css +1 -0
- package/web/dist/assets/index-DHeeHS_l.js +85 -0
- package/web/dist/assets/index-DTZch8uz.js +85 -0
- package/web/dist/assets/plugin-host-C8mNgghx.js +1 -0
- package/web/dist/assets/remote-ssh-client-CeP3CLUW.js +1 -0
- package/web/dist/assets/theme-BXGpyTMh.js +1 -0
- package/web/dist/index.html +10 -9
- package/web/dist/sw.js +1 -1
- package/web/dist/assets/BgTasksModal-BIlQ89vr.js +0 -1
- package/web/dist/assets/BgTasksModal-Ck2sjlPM.js +0 -1
- package/web/dist/assets/DeviceCenter-BQdDcO8A.js +0 -3
- package/web/dist/assets/DeviceCenter-CHRKL0Vy.js +0 -3
- package/web/dist/assets/DeviceGroups-D2rogxEN.js +0 -1
- package/web/dist/assets/Dropdown-ZLS04O8p.js +0 -1
- package/web/dist/assets/FilePreview-B9xoU6ON.js +0 -2
- package/web/dist/assets/FilePreview-DUQpVZkH.js +0 -2
- package/web/dist/assets/GlobalSearchModal-BXEGvUZq.js +0 -1
- package/web/dist/assets/GlobalSearchModal-CnVPmfOI.js +0 -1
- package/web/dist/assets/GroupConversation-CyIpQzDd.js +0 -1
- package/web/dist/assets/GroupConversation-DgYV3uYS.js +0 -1
- package/web/dist/assets/ModelConfigModal-DDZccDYt.js +0 -2
- package/web/dist/assets/PiSetupModal-DHbqfx8T.js +0 -1
- package/web/dist/assets/ProviderOAuthControls-C-MK36Dk.js +0 -1
- package/web/dist/assets/SCMPanel-imYI2Ecw.js +0 -2
- package/web/dist/assets/SCMPanel-sVZcV7dR.js +0 -2
- package/web/dist/assets/SettingsModal-Xw1Yoi3_.js +0 -20
- package/web/dist/assets/SettingsModal-mb4e34-0.js +0 -20
- package/web/dist/assets/TerminalPanel-CLkJJvxg.js +0 -3
- package/web/dist/assets/TerminalPanel-DpcIellm.js +0 -3
- package/web/dist/assets/TuiOverlayModal-4-fFAZe7.js +0 -1
- package/web/dist/assets/TuiOverlayModal-DCu01lks.js +0 -1
- package/web/dist/assets/app-globals-DcyO0UPi.js +0 -1
- package/web/dist/assets/fi-DaSO0Q-m.js +0 -325
- package/web/dist/assets/index-Cdh3sibd.js +0 -85
- package/web/dist/assets/index-DDZMv6LO.css +0 -1
- package/web/dist/assets/index-DWw_SxRq.js +0 -85
- package/web/dist/assets/plugin-host-BRBg6zmQ.js +0 -1
- package/web/dist/assets/theme-DDl-Oy1b.js +0 -1
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import { planGroupContext } from "./group-context-delta.js";
|
|
2
|
+
export const GROUP_CONTEXT_CUSTOM_TYPE = "device-group-context";
|
|
3
|
+
/** Pure measurement of a planner result; does not change coverage or drop rows. */
|
|
4
|
+
export function extractGroupContextMetrics(current, delivered, payload, mode, requestOnly = false) {
|
|
5
|
+
const sourceBytes = current.messages.reduce((bytes, row) => bytes + Buffer.byteLength(row.text, "utf8"), 0);
|
|
6
|
+
const deliveredBytes = delivered.reduce((bytes, row) => bytes + Buffer.byteLength(row.text, "utf8"), 0);
|
|
7
|
+
const payloadBytes = Buffer.byteLength(payload, "utf8");
|
|
8
|
+
return {
|
|
9
|
+
version: 1,
|
|
10
|
+
sourceMessages: current.messages.length,
|
|
11
|
+
sourceBytes,
|
|
12
|
+
deliveredMessages: delivered.length,
|
|
13
|
+
deliveredBytes,
|
|
14
|
+
omittedDuplicateMessages: current.messages.length - delivered.length,
|
|
15
|
+
omittedDuplicateBytes: sourceBytes - deliveredBytes,
|
|
16
|
+
payloadBytes,
|
|
17
|
+
mode,
|
|
18
|
+
requestOnly,
|
|
19
|
+
repairMessages: requestOnly ? delivered.length : 0,
|
|
20
|
+
repairBytes: requestOnly ? payloadBytes : 0,
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
const METRIC_SESSION_LIMIT = 50;
|
|
24
|
+
const METRIC_SAMPLE_LIMIT = 100;
|
|
25
|
+
const metricSessions = new Map();
|
|
26
|
+
/** Process-local bounded diagnostics only; never used as delivery evidence. */
|
|
27
|
+
export function recordGroupContextMetrics(sessionId, metrics) {
|
|
28
|
+
const samples = metricSessions.get(sessionId) ?? [];
|
|
29
|
+
// Explicit scalar projection prevents extra caller properties retaining content/credentials.
|
|
30
|
+
samples.push({
|
|
31
|
+
version: 1,
|
|
32
|
+
sourceMessages: metrics.sourceMessages,
|
|
33
|
+
sourceBytes: metrics.sourceBytes,
|
|
34
|
+
deliveredMessages: metrics.deliveredMessages,
|
|
35
|
+
deliveredBytes: metrics.deliveredBytes,
|
|
36
|
+
omittedDuplicateMessages: metrics.omittedDuplicateMessages,
|
|
37
|
+
omittedDuplicateBytes: metrics.omittedDuplicateBytes,
|
|
38
|
+
payloadBytes: metrics.payloadBytes,
|
|
39
|
+
mode: metrics.mode,
|
|
40
|
+
requestOnly: metrics.requestOnly,
|
|
41
|
+
repairMessages: metrics.repairMessages,
|
|
42
|
+
repairBytes: metrics.repairBytes,
|
|
43
|
+
});
|
|
44
|
+
if (samples.length > METRIC_SAMPLE_LIMIT)
|
|
45
|
+
samples.shift();
|
|
46
|
+
metricSessions.delete(sessionId);
|
|
47
|
+
metricSessions.set(sessionId, samples);
|
|
48
|
+
if (metricSessions.size > METRIC_SESSION_LIMIT)
|
|
49
|
+
metricSessions.delete(metricSessions.keys().next().value);
|
|
50
|
+
}
|
|
51
|
+
/** Detached chronological snapshot; old sessions/samples may have been evicted. */
|
|
52
|
+
export function getGroupContextMetrics(sessionId) {
|
|
53
|
+
return {
|
|
54
|
+
version: 1,
|
|
55
|
+
processLocal: true,
|
|
56
|
+
sampleLimit: METRIC_SAMPLE_LIMIT,
|
|
57
|
+
sampleCount: metricSessions.get(sessionId)?.length ?? 0,
|
|
58
|
+
durableDeliveries: (metricSessions.get(sessionId) ?? []).filter((sample) => !sample.requestOnly).length,
|
|
59
|
+
requests: (metricSessions.get(sessionId) ?? []).filter((sample) => sample.requestOnly).length,
|
|
60
|
+
// Inspection stays small enough for tool receipts; counters cover the retained 100 samples.
|
|
61
|
+
lastSample: metricSessions.get(sessionId)?.at(-1) ? { ...metricSessions.get(sessionId).at(-1) } : null,
|
|
62
|
+
samples: (metricSessions.get(sessionId) ?? []).slice(-10).map((sample) => ({ ...sample })),
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
function record(value) {
|
|
66
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
67
|
+
}
|
|
68
|
+
function nullableString(value) {
|
|
69
|
+
return value === null || typeof value === "string";
|
|
70
|
+
}
|
|
71
|
+
function position(value) {
|
|
72
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
73
|
+
}
|
|
74
|
+
function historyMessage(value) {
|
|
75
|
+
if (!record(value) || !record(value.sender))
|
|
76
|
+
return false;
|
|
77
|
+
return (typeof value.id === "string" &&
|
|
78
|
+
typeof value.text === "string" &&
|
|
79
|
+
(value.sender.type === "human" || value.sender.type === "bot") &&
|
|
80
|
+
typeof value.sender.id === "string" &&
|
|
81
|
+
typeof value.sender.name === "string" &&
|
|
82
|
+
typeof value.createdAt === "number" &&
|
|
83
|
+
Number.isFinite(value.createdAt) &&
|
|
84
|
+
(value.targetBotIds === undefined ||
|
|
85
|
+
(Array.isArray(value.targetBotIds) && value.targetBotIds.every((id) => typeof id === "string"))) &&
|
|
86
|
+
position(value.textStart) &&
|
|
87
|
+
position(value.textEnd) &&
|
|
88
|
+
position(value.fullTextLength) &&
|
|
89
|
+
value.textStart <= value.textEnd &&
|
|
90
|
+
value.textEnd <= value.fullTextLength &&
|
|
91
|
+
value.text.length === value.textEnd - value.textStart);
|
|
92
|
+
}
|
|
93
|
+
function taskContext(value) {
|
|
94
|
+
return (record(value) &&
|
|
95
|
+
typeof value.roomId === "string" &&
|
|
96
|
+
typeof value.roomName === "string" &&
|
|
97
|
+
(value.primaryBotId === undefined || typeof value.primaryBotId === "string") &&
|
|
98
|
+
Array.isArray(value.members) &&
|
|
99
|
+
value.members.every((member) => record(member) && typeof member.id === "string" && typeof member.name === "string") &&
|
|
100
|
+
nullableString(value.throughMessageId) &&
|
|
101
|
+
nullableString(value.nextBefore) &&
|
|
102
|
+
typeof value.truncated === "boolean" &&
|
|
103
|
+
position(value.retentionLimit) &&
|
|
104
|
+
value.retentionLimit > 0 &&
|
|
105
|
+
Array.isArray(value.messages) &&
|
|
106
|
+
value.messages.every(historyMessage));
|
|
107
|
+
}
|
|
108
|
+
function parseContext(content) {
|
|
109
|
+
// Custom messages can store either a string or text blocks. Images and other blocks
|
|
110
|
+
// cannot establish exact JSON delivery evidence; details never reach the model.
|
|
111
|
+
if (Array.isArray(content)) {
|
|
112
|
+
if (!content.every((block) => record(block) && block.type === "text" && typeof block.text === "string"))
|
|
113
|
+
return undefined;
|
|
114
|
+
content = content.map((block) => block.text).join("");
|
|
115
|
+
}
|
|
116
|
+
if (typeof content !== "string")
|
|
117
|
+
return undefined;
|
|
118
|
+
try {
|
|
119
|
+
const parsed = JSON.parse(content);
|
|
120
|
+
return taskContext(parsed) ? parsed : undefined;
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
123
|
+
return undefined;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
function metadata(context) {
|
|
127
|
+
return JSON.stringify([
|
|
128
|
+
context.roomId,
|
|
129
|
+
context.roomName,
|
|
130
|
+
context.primaryBotId,
|
|
131
|
+
context.members.map((member) => [member.id, member.name]),
|
|
132
|
+
context.throughMessageId,
|
|
133
|
+
context.nextBefore,
|
|
134
|
+
context.truncated,
|
|
135
|
+
context.retentionLimit,
|
|
136
|
+
]);
|
|
137
|
+
}
|
|
138
|
+
function coverage(current, messages, botId, request = false) {
|
|
139
|
+
let previous;
|
|
140
|
+
let metadataPresent = false;
|
|
141
|
+
const retained = new Set();
|
|
142
|
+
const currentIds = new Set(current.messages.map((message) => message.id));
|
|
143
|
+
for (const message of messages) {
|
|
144
|
+
if (!record(message) || message.role !== "custom" || message.customType !== GROUP_CONTEXT_CUSTOM_TYPE)
|
|
145
|
+
continue;
|
|
146
|
+
// Request repairs are never durable delivery evidence.
|
|
147
|
+
if (!request && record(message.details) && message.details.requestOnly === true)
|
|
148
|
+
continue;
|
|
149
|
+
if (botId !== undefined &&
|
|
150
|
+
(!record(message.details) || message.details.version !== 1 || message.details.botId !== botId))
|
|
151
|
+
continue;
|
|
152
|
+
const context = parseContext(message.content);
|
|
153
|
+
if (!context || context.roomId !== current.roomId)
|
|
154
|
+
continue;
|
|
155
|
+
if (metadata(context) === metadata(current))
|
|
156
|
+
metadataPresent = true;
|
|
157
|
+
// Keep at most the current window's exact chunks, rather than accumulating the
|
|
158
|
+
// full session history. Let the planner define chunk equality in one place.
|
|
159
|
+
const candidates = context.messages.filter((row) => currentIds.has(row.id));
|
|
160
|
+
const missing = new Set(planGroupContext(current, { ...context, throughMessageId: null, messages: candidates }).messages);
|
|
161
|
+
for (const row of current.messages)
|
|
162
|
+
if (!missing.has(row))
|
|
163
|
+
retained.add(row);
|
|
164
|
+
previous = { ...context, messages: [...retained] };
|
|
165
|
+
}
|
|
166
|
+
return { previous, metadataPresent };
|
|
167
|
+
}
|
|
168
|
+
/** Only active projected custom-message content establishes durable delivery coverage. */
|
|
169
|
+
export function groupContextMessage(current, messages, botId) {
|
|
170
|
+
const planned = planGroupContext(current, coverage(current, messages, botId).previous);
|
|
171
|
+
const content = JSON.stringify(planned);
|
|
172
|
+
return {
|
|
173
|
+
customType: GROUP_CONTEXT_CUSTOM_TYPE,
|
|
174
|
+
content,
|
|
175
|
+
display: false,
|
|
176
|
+
details: {
|
|
177
|
+
version: 1,
|
|
178
|
+
...(botId === undefined ? {} : { botId }),
|
|
179
|
+
metrics: extractGroupContextMetrics(current, planned.messages, content, planned.delivery.mode),
|
|
180
|
+
},
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
/** Repair the final request after SDK compaction/routing, without altering the transcript.
|
|
184
|
+
* Anchor continuity is irrelevant here: actual exact chunk coverage determines missing rows.
|
|
185
|
+
*/
|
|
186
|
+
export function repairGroupContextRequest(current, messages, botId) {
|
|
187
|
+
const { previous, metadataPresent } = coverage(current, messages, botId, true);
|
|
188
|
+
const missing = planGroupContext(current, previous && { ...previous, throughMessageId: null }).messages;
|
|
189
|
+
if (missing.length === 0 && metadataPresent)
|
|
190
|
+
return messages;
|
|
191
|
+
return [...messages, requestMessage(current, missing, botId, previous ? "delta" : "snapshot")];
|
|
192
|
+
}
|
|
193
|
+
function requestMessage(current, missing, botId, mode) {
|
|
194
|
+
const content = JSON.stringify({ ...current, messages: missing, delivery: { mode } });
|
|
195
|
+
return {
|
|
196
|
+
role: "custom",
|
|
197
|
+
customType: GROUP_CONTEXT_CUSTOM_TYPE,
|
|
198
|
+
content,
|
|
199
|
+
display: false,
|
|
200
|
+
timestamp: Date.now(),
|
|
201
|
+
details: {
|
|
202
|
+
version: 1,
|
|
203
|
+
botId,
|
|
204
|
+
requestOnly: true,
|
|
205
|
+
metrics: extractGroupContextMetrics(current, missing, content, mode, true),
|
|
206
|
+
},
|
|
207
|
+
};
|
|
208
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
export const GROUP_RETENTION_LIMIT = 500;
|
|
2
|
+
export const GROUP_CONTEXT_BYTES = 24 * 1024;
|
|
3
|
+
const PAGE_BYTES = 24 * 1024;
|
|
4
|
+
function project(message, start = 0, end = message.text.length) {
|
|
5
|
+
return {
|
|
6
|
+
id: message.id,
|
|
7
|
+
text: message.text.slice(start, end),
|
|
8
|
+
sender: { type: message.sender.type, id: message.sender.id, name: message.sender.name },
|
|
9
|
+
createdAt: message.createdAt,
|
|
10
|
+
...(message.targetBotIds ? { targetBotIds: message.targetBotIds } : {}),
|
|
11
|
+
textStart: start,
|
|
12
|
+
textEnd: end,
|
|
13
|
+
fullTextLength: message.text.length,
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
function cursor(roomId, id, end) {
|
|
17
|
+
return Buffer.from(JSON.stringify([roomId, id, end])).toString("base64url");
|
|
18
|
+
}
|
|
19
|
+
function invalidCursor() {
|
|
20
|
+
throw Object.assign(new Error("History cursor expired or invalid; read the latest page again"), { status: 409 });
|
|
21
|
+
}
|
|
22
|
+
/** Stable message anchors survive appends. Clear/retention makes old anchors fail explicitly.
|
|
23
|
+
* Oversized messages are paged in reverse text chunks, without dropping their middle. */
|
|
24
|
+
export function groupHistoryPage(roomId, messages, before, budget = PAGE_BYTES) {
|
|
25
|
+
const rows = messages.filter((message) => message.roomId === roomId);
|
|
26
|
+
let index = rows.length - 1;
|
|
27
|
+
let end = rows[index]?.text.length ?? 0;
|
|
28
|
+
if (before !== undefined) {
|
|
29
|
+
let value;
|
|
30
|
+
try {
|
|
31
|
+
if (before.length > 256 || !/^[A-Za-z0-9_-]+$/.test(before))
|
|
32
|
+
invalidCursor();
|
|
33
|
+
value = JSON.parse(Buffer.from(before, "base64url").toString("utf8"));
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
invalidCursor();
|
|
37
|
+
}
|
|
38
|
+
if (!Array.isArray(value) ||
|
|
39
|
+
value.length !== 3 ||
|
|
40
|
+
value[0] !== roomId ||
|
|
41
|
+
typeof value[1] !== "string" ||
|
|
42
|
+
!Number.isSafeInteger(value[2]))
|
|
43
|
+
invalidCursor();
|
|
44
|
+
index = rows.findIndex((message) => message.id === value[1]);
|
|
45
|
+
if (index < 0 || value[2] < 0 || value[2] > rows[index].text.length)
|
|
46
|
+
invalidCursor();
|
|
47
|
+
end = value[2];
|
|
48
|
+
if (end === 0) {
|
|
49
|
+
index--;
|
|
50
|
+
end = rows[index]?.text.length ?? 0;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
const page = {
|
|
54
|
+
roomId,
|
|
55
|
+
messages: [],
|
|
56
|
+
nextBefore: null,
|
|
57
|
+
truncated: false,
|
|
58
|
+
retentionLimit: GROUP_RETENTION_LIMIT,
|
|
59
|
+
};
|
|
60
|
+
const fits = (items) => Buffer.byteLength(JSON.stringify({ ...page, messages: items, nextBefore: "x".repeat(256), truncated: true })) <=
|
|
61
|
+
budget;
|
|
62
|
+
while (index >= 0) {
|
|
63
|
+
const row = rows[index];
|
|
64
|
+
const item = project(row, 0, end);
|
|
65
|
+
if (fits([item, ...page.messages])) {
|
|
66
|
+
page.messages.unshift(item);
|
|
67
|
+
index--;
|
|
68
|
+
end = rows[index]?.text.length ?? 0;
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
if (page.messages.length)
|
|
72
|
+
break;
|
|
73
|
+
// Keep the latest suffix of a large row; subsequent pages return every earlier chunk.
|
|
74
|
+
let low = 0, high = end;
|
|
75
|
+
while (low < high) {
|
|
76
|
+
const mid = Math.floor((low + high) / 2);
|
|
77
|
+
if (fits([project(row, mid, end)]))
|
|
78
|
+
high = mid;
|
|
79
|
+
else
|
|
80
|
+
low = mid + 1;
|
|
81
|
+
}
|
|
82
|
+
let start = low;
|
|
83
|
+
// Never divide a UTF-16 surrogate pair across chunks.
|
|
84
|
+
if (start > 0 && /[\uDC00-\uDFFF]/.test(row.text[start] ?? ""))
|
|
85
|
+
start++;
|
|
86
|
+
if (start >= end || !fits([project(row, start, end)]))
|
|
87
|
+
throw new Error("History metadata exceeds page budget");
|
|
88
|
+
page.messages.unshift(project(row, start, end));
|
|
89
|
+
end = start;
|
|
90
|
+
break;
|
|
91
|
+
}
|
|
92
|
+
if (index >= 0) {
|
|
93
|
+
page.nextBefore = cursor(roomId, rows[index].id, end);
|
|
94
|
+
page.truncated = true;
|
|
95
|
+
}
|
|
96
|
+
return page;
|
|
97
|
+
}
|
|
98
|
+
/** Captured at dispatch, before any parallel recipient can publish a response. */
|
|
99
|
+
export function groupTaskContext(room, bots, messages) {
|
|
100
|
+
const members = room.botIds.map((id) => ({ id, name: bots.find((bot) => bot.id === id)?.name ?? id }));
|
|
101
|
+
const metadata = {
|
|
102
|
+
roomName: room.name,
|
|
103
|
+
...(room.primaryBotId && room.botIds.includes(room.primaryBotId) ? { primaryBotId: room.primaryBotId } : {}),
|
|
104
|
+
members,
|
|
105
|
+
throughMessageId: messages.filter((message) => message.roomId === room.id).at(-1)?.id ?? null,
|
|
106
|
+
};
|
|
107
|
+
const page = groupHistoryPage(room.id, messages, undefined, GROUP_CONTEXT_BYTES - Buffer.byteLength(JSON.stringify(metadata)) - 64);
|
|
108
|
+
return { ...page, ...metadata };
|
|
109
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { projectTaskActivity, validTaskProgress } from "./task-progress.js";
|
|
2
|
+
/** Ephemeral progress, separate from durable task reports. Slow consumers reconnect. */
|
|
3
|
+
export function createGroupEvents(store, journalManager) {
|
|
4
|
+
let closed = false;
|
|
5
|
+
const progress = new Map();
|
|
6
|
+
const clients = new Set();
|
|
7
|
+
const pendingAppends = new Set();
|
|
8
|
+
const journalFailures = new Map();
|
|
9
|
+
function send(res, event, data) {
|
|
10
|
+
if (!res.destroyed && !res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`))
|
|
11
|
+
res.destroy();
|
|
12
|
+
}
|
|
13
|
+
const unsubscribe = store.subscribe(() => {
|
|
14
|
+
const state = store.snapshot();
|
|
15
|
+
for (const [id, p] of progress)
|
|
16
|
+
if (!state.tasks.some((t) => t.id === id && t.status === "running" && t.attemptId === p.attemptId))
|
|
17
|
+
progress.delete(id);
|
|
18
|
+
for (const c of clients) {
|
|
19
|
+
if (!state.rooms.some((r) => r.id === c.roomId && r.accountId === c.accountId) ||
|
|
20
|
+
(c.deviceId && !state.devices.some((d) => d.id === c.deviceId && d.accountId === c.accountId)))
|
|
21
|
+
c.res.end();
|
|
22
|
+
else
|
|
23
|
+
send(c.res, "invalidate", {});
|
|
24
|
+
}
|
|
25
|
+
});
|
|
26
|
+
return {
|
|
27
|
+
invalidate(roomId) {
|
|
28
|
+
const room = store.snapshot().rooms.find((item) => item.id === roomId);
|
|
29
|
+
if (!room)
|
|
30
|
+
return;
|
|
31
|
+
for (const client of clients)
|
|
32
|
+
if (client.roomId === roomId && client.accountId === room.accountId)
|
|
33
|
+
send(client.res, "invalidate", {});
|
|
34
|
+
},
|
|
35
|
+
connect(accountId, roomId, res, deviceId) {
|
|
36
|
+
if (!store.snapshot().rooms.some((r) => r.id === roomId && r.accountId === accountId)) {
|
|
37
|
+
res.sendStatus(404);
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
if (clients.size >= 128 || [...clients].filter((c) => c.accountId === accountId).length >= 16) {
|
|
41
|
+
res.sendStatus(429);
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
res.set({ "Content-Type": "text/event-stream", "Cache-Control": "no-store", "X-Accel-Buffering": "no" });
|
|
45
|
+
res.flushHeaders();
|
|
46
|
+
const client = { accountId, roomId, res, deviceId };
|
|
47
|
+
clients.add(client);
|
|
48
|
+
send(res, "invalidate", {});
|
|
49
|
+
const state = store.snapshot();
|
|
50
|
+
for (const p of progress.values())
|
|
51
|
+
if (state.tasks.some((t) => t.id === p.taskId && t.roomId === roomId))
|
|
52
|
+
send(res, "progress", p);
|
|
53
|
+
const timer = setInterval(() => send(res, "ping", {}), 15000);
|
|
54
|
+
timer.unref();
|
|
55
|
+
res.once("close", () => {
|
|
56
|
+
clearInterval(timer);
|
|
57
|
+
clients.delete(client);
|
|
58
|
+
});
|
|
59
|
+
},
|
|
60
|
+
accept(deviceId, event) {
|
|
61
|
+
if (closed || !validTaskProgress(event))
|
|
62
|
+
return;
|
|
63
|
+
const state = store.snapshot();
|
|
64
|
+
const device = state.devices.find((d) => d.id === deviceId);
|
|
65
|
+
const task = state.tasks.find((t) => t.id === event.taskId &&
|
|
66
|
+
t.deviceId === deviceId &&
|
|
67
|
+
t.botId === event.botId &&
|
|
68
|
+
t.attemptId === event.attemptId &&
|
|
69
|
+
t.accountId === device?.accountId &&
|
|
70
|
+
t.status === "running");
|
|
71
|
+
if (!task ||
|
|
72
|
+
!state.bots.some((b) => b.id === task.botId &&
|
|
73
|
+
b.enabled &&
|
|
74
|
+
b.deviceId === deviceId &&
|
|
75
|
+
b.accountId === task.accountId &&
|
|
76
|
+
b.revision === task.botRevision) ||
|
|
77
|
+
!state.rooms.some((r) => r.id === task.roomId && r.accountId === task.accountId && r.botIds.includes(task.botId)))
|
|
78
|
+
return;
|
|
79
|
+
const previous = progress.get(task.id);
|
|
80
|
+
if (previous && previous.attemptId === event.attemptId && previous.sequence >= event.sequence)
|
|
81
|
+
return;
|
|
82
|
+
if (!previous && progress.size >= 1024)
|
|
83
|
+
return;
|
|
84
|
+
const p = {
|
|
85
|
+
...projectTaskActivity(event),
|
|
86
|
+
taskId: task.id,
|
|
87
|
+
botId: task.botId,
|
|
88
|
+
attemptId: event.attemptId,
|
|
89
|
+
sequence: event.sequence,
|
|
90
|
+
};
|
|
91
|
+
progress.set(task.id, p);
|
|
92
|
+
// Persist progress into durable journal
|
|
93
|
+
if (journalManager && !closed) {
|
|
94
|
+
const appendPromise = journalManager
|
|
95
|
+
.append(task.id, {
|
|
96
|
+
botId: task.botId,
|
|
97
|
+
attemptId: event.attemptId,
|
|
98
|
+
type: "progress",
|
|
99
|
+
phase: p.phase === "model" ? "running" : p.phase === "tool" ? "running" : "waiting",
|
|
100
|
+
toolName: p.toolName,
|
|
101
|
+
output: p.text,
|
|
102
|
+
summary: p.toolName ? `Running tool ${p.toolName}` : p.text,
|
|
103
|
+
}, { roomId: task.roomId, accountId: task.accountId })
|
|
104
|
+
.catch((err) => {
|
|
105
|
+
const key = `${task.id}:${event.attemptId}`;
|
|
106
|
+
if (journalFailures.size >= 128) {
|
|
107
|
+
const oldest = journalFailures.keys().next().value;
|
|
108
|
+
if (oldest)
|
|
109
|
+
journalFailures.delete(oldest);
|
|
110
|
+
}
|
|
111
|
+
journalFailures.set(key, err?.message ?? "Journal disk append failed");
|
|
112
|
+
});
|
|
113
|
+
pendingAppends.add(appendPromise);
|
|
114
|
+
appendPromise.finally(() => pendingAppends.delete(appendPromise));
|
|
115
|
+
}
|
|
116
|
+
for (const c of clients)
|
|
117
|
+
if (c.accountId === task.accountId && c.roomId === task.roomId)
|
|
118
|
+
send(c.res, "progress", p);
|
|
119
|
+
},
|
|
120
|
+
isJournalUnavailable(taskId, attemptId) {
|
|
121
|
+
return journalFailures.has(`${taskId}:${attemptId}`);
|
|
122
|
+
},
|
|
123
|
+
async close() {
|
|
124
|
+
closed = true;
|
|
125
|
+
unsubscribe();
|
|
126
|
+
for (const c of clients)
|
|
127
|
+
c.res.end();
|
|
128
|
+
clients.clear();
|
|
129
|
+
progress.clear();
|
|
130
|
+
if (pendingAppends.size > 0) {
|
|
131
|
+
await Promise.allSettled(Array.from(pendingAppends));
|
|
132
|
+
pendingAppends.clear();
|
|
133
|
+
}
|
|
134
|
+
},
|
|
135
|
+
};
|
|
136
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* server/device-center/group-plan-guard.ts
|
|
3
|
+
*
|
|
4
|
+
* 群任务计划模式(Plan Mode)服务端硬门禁与审批状态机。
|
|
5
|
+
*
|
|
6
|
+
* 核心原则:
|
|
7
|
+
* 1. 事实单源:复用 server/plan-mode.ts 的只读白名单判定(readOnlyToolCallAllowed)
|
|
8
|
+
* 与 bash 只读语法校验(bashCommandIsReadOnly / bashCommandHasSupportedSyntax)。
|
|
9
|
+
* 2. 严格闭门门禁(Fail-Closed):除明确白名单中的只读工具外,其余未知工具(含第三方插件)
|
|
10
|
+
* 在计划模式下全部拦截拒绝,绝不默认放行。
|
|
11
|
+
* 3. device_collab 动作细分:只允许只读动作(read_history/context_metrics 等),
|
|
12
|
+
* 写文件(sync_files)、派发与交付等写动作一律硬拦截。
|
|
13
|
+
* 4. 服务端原子校验:计划批准仅允许从 "ready" 转移至 "approved",拒绝 draft 或重复批准。
|
|
14
|
+
*/
|
|
15
|
+
import { validateTaskPlan } from "./task-plan.js";
|
|
16
|
+
import { isConversationTool } from "../conversation-tool-names.js";
|
|
17
|
+
import { readOnlyToolCallAllowed, PLAN_MODE_BLOCKED_TOOL_NAMES, planModeDenial, bashCommandIsReadOnly, bashCommandHasSupportedSyntax, } from "../plan-mode.js";
|
|
18
|
+
/** device_collab 允许在计划模式下调用的安全只读 action 白名单 */
|
|
19
|
+
const DEVICE_COLLAB_READ_ONLY_ACTIONS = new Set([
|
|
20
|
+
"read_history",
|
|
21
|
+
"context_metrics",
|
|
22
|
+
"execution_guide",
|
|
23
|
+
"conversation_read",
|
|
24
|
+
"current_task",
|
|
25
|
+
"transfer_preview",
|
|
26
|
+
]);
|
|
27
|
+
/** bash 类工具名 */
|
|
28
|
+
const BASH_TOOL_NAMES = new Set(["bash", "terminal_bash", "command"]);
|
|
29
|
+
/**
|
|
30
|
+
* 判断工具在计划模式下的目录注册期是否应被直接隐藏
|
|
31
|
+
*/
|
|
32
|
+
export function isGroupToolForbiddenInPlanCatalog(toolName, isPlanOnly) {
|
|
33
|
+
if (!isPlanOnly)
|
|
34
|
+
return false;
|
|
35
|
+
const name = (toolName || "").trim().toLowerCase();
|
|
36
|
+
return PLAN_MODE_BLOCKED_TOOL_NAMES.has(name) && !isConversationTool(name);
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* 校验群任务执行时的工具调用是否被计划模式拦截
|
|
40
|
+
* @returns undefined 表示放行;返回 PlanModeDenial 表示被硬门禁拦截
|
|
41
|
+
*/
|
|
42
|
+
export function checkGroupTaskPlanGuard(toolName, params, isPlanOnly) {
|
|
43
|
+
if (!isPlanOnly) {
|
|
44
|
+
return undefined; // 非计划模式任务不施加此门禁
|
|
45
|
+
}
|
|
46
|
+
const name = (toolName || "").trim().toLowerCase();
|
|
47
|
+
// This is execution authorization; catalog filtering uses its own explicit API.
|
|
48
|
+
params ??= {};
|
|
49
|
+
// 1. plan_update 允许用于制定和更新计划本身
|
|
50
|
+
if (name === "plan_update") {
|
|
51
|
+
const steps = params && typeof params === "object" ? params.steps : undefined;
|
|
52
|
+
if (!validateTaskPlan({ state: "ready", steps }))
|
|
53
|
+
return {
|
|
54
|
+
kind: "write-tool",
|
|
55
|
+
reason: "群计划模式:步骤须为 1–32 条,ID 唯一、标题非空、状态合法,且不得超过字段长度限制。",
|
|
56
|
+
reasonEn: "Group plan mode: require 1–32 steps with unique IDs, nonempty titles, valid statuses and bounded field lengths.",
|
|
57
|
+
};
|
|
58
|
+
return undefined;
|
|
59
|
+
}
|
|
60
|
+
// 2. device_collab 工具动作级细分拦截
|
|
61
|
+
if (name === "device_collab") {
|
|
62
|
+
const p = params && typeof params === "object" ? params : {};
|
|
63
|
+
const action = typeof p.action === "string" ? p.action.trim().toLowerCase() : "";
|
|
64
|
+
if (DEVICE_COLLAB_READ_ONLY_ACTIONS.has(action)) {
|
|
65
|
+
return undefined;
|
|
66
|
+
}
|
|
67
|
+
return {
|
|
68
|
+
kind: "write-tool",
|
|
69
|
+
reason: `群计划模式:禁止调用 device_collab(action="${action || "unknown"}")。计划阶段仅允许只读调研动作。`,
|
|
70
|
+
reasonEn: `Group plan mode: device_collab(action="${action || "unknown"}") is prohibited. Only read-only actions are permitted during planning.`,
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
// 3. bash / 终端命令只读检查
|
|
74
|
+
if (BASH_TOOL_NAMES.has(name)) {
|
|
75
|
+
const p = params && typeof params === "object" ? params : {};
|
|
76
|
+
const cmd = typeof p.command === "string" ? p.command : typeof p.cmd === "string" ? p.cmd : "";
|
|
77
|
+
if (!cmd.trim()) {
|
|
78
|
+
return {
|
|
79
|
+
kind: "bash",
|
|
80
|
+
reason: "群计划模式:空命令不可用。调研请用只读命令。",
|
|
81
|
+
reasonEn: "Group plan mode: empty command unavailable. Run read-only commands for research.",
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
if (bashCommandIsReadOnly(cmd) && bashCommandHasSupportedSyntax(cmd)) {
|
|
85
|
+
return undefined;
|
|
86
|
+
}
|
|
87
|
+
return {
|
|
88
|
+
kind: "bash",
|
|
89
|
+
reason: `群计划模式:命令 "${cmd.slice(0, 80)}" 包含写操作或不受支持的复杂语法,已拦截。请使用只读命令或把改动列入计划。`,
|
|
90
|
+
reasonEn: `Group plan mode: command "${cmd.slice(0, 80)}" contains write operations or unsupported syntax. Use read-only commands or record changes in the plan.`,
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
// 4. 复用宿主已有的通用计划门禁判定
|
|
94
|
+
const generalDenial = planModeDenial(name, params);
|
|
95
|
+
if (generalDenial) {
|
|
96
|
+
return generalDenial;
|
|
97
|
+
}
|
|
98
|
+
// 5. 严格闭门门禁:白名单判定
|
|
99
|
+
if (readOnlyToolCallAllowed(name, params)) {
|
|
100
|
+
return undefined;
|
|
101
|
+
}
|
|
102
|
+
// 未在白名单中的未知工具(含第三方插件)一律拦截
|
|
103
|
+
return {
|
|
104
|
+
kind: "bypass-tool",
|
|
105
|
+
reason: `群计划模式:工具 "${name}" 未在只读白名单中,已被硬门禁拦截。请使用只读工具进行调研。`,
|
|
106
|
+
reasonEn: `Group plan mode: tool "${name}" is not in the read-only allowlist and has been blocked. Use read-only tools for research.`,
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* 服务端原子批准群任务计划
|
|
111
|
+
* 只有处于 ready 状态且具有步骤的计划才能被批准;draft 或已 approved 明确拒绝
|
|
112
|
+
*/
|
|
113
|
+
export function atomicApproveGroupPlan(current, approver = "user", now = Date.now()) {
|
|
114
|
+
if (!current) {
|
|
115
|
+
return { ok: false, error: "No plan found to approve" };
|
|
116
|
+
}
|
|
117
|
+
if (current.state === "approved") {
|
|
118
|
+
return { ok: false, error: "Plan has already been approved" };
|
|
119
|
+
}
|
|
120
|
+
if (current.state === "draft") {
|
|
121
|
+
return { ok: false, error: "Plan is still in draft state and cannot be approved yet" };
|
|
122
|
+
}
|
|
123
|
+
if (current.state !== "ready") {
|
|
124
|
+
return { ok: false, error: `Invalid plan state for approval: ${current.state}` };
|
|
125
|
+
}
|
|
126
|
+
if (!Array.isArray(current.steps) || current.steps.length === 0) {
|
|
127
|
+
return { ok: false, error: "Plan contains no steps and cannot be approved" };
|
|
128
|
+
}
|
|
129
|
+
return {
|
|
130
|
+
ok: true,
|
|
131
|
+
plan: {
|
|
132
|
+
...current,
|
|
133
|
+
state: "approved",
|
|
134
|
+
approvedAt: now,
|
|
135
|
+
approvedBy: approver,
|
|
136
|
+
},
|
|
137
|
+
};
|
|
138
|
+
}
|