@gakr-gakr/matrix 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +285 -0
- package/SPEC-SUPPORT.md +116 -0
- package/api.ts +38 -0
- package/auth-presence.ts +56 -0
- package/autobot.plugin.json +28 -0
- package/channel-plugin-api.ts +3 -0
- package/cli-metadata.ts +11 -0
- package/contract-api.ts +17 -0
- package/doctor-contract-api.ts +1 -0
- package/helper-api.ts +3 -0
- package/index.ts +55 -0
- package/package.json +101 -0
- package/plugin-entry.handlers.runtime.ts +1 -0
- package/runtime-api.ts +72 -0
- package/runtime-heavy-api.ts +1 -0
- package/runtime-setter-api.ts +3 -0
- package/secret-contract-api.ts +5 -0
- package/setup-entry.ts +17 -0
- package/setup-plugin-api.ts +3 -0
- package/src/account-selection.ts +223 -0
- package/src/actions.ts +346 -0
- package/src/approval-auth.ts +25 -0
- package/src/approval-handler.runtime.ts +595 -0
- package/src/approval-ids.ts +6 -0
- package/src/approval-native.ts +348 -0
- package/src/approval-reaction-auth.ts +45 -0
- package/src/approval-reactions.ts +313 -0
- package/src/auth-precedence.ts +61 -0
- package/src/channel-account-paths.ts +97 -0
- package/src/channel.runtime.ts +17 -0
- package/src/channel.setup.ts +48 -0
- package/src/channel.ts +667 -0
- package/src/cli-metadata.ts +19 -0
- package/src/cli.ts +2298 -0
- package/src/config-adapter.ts +41 -0
- package/src/config-schema.ts +159 -0
- package/src/config-ui-hints.ts +56 -0
- package/src/directory-live.ts +238 -0
- package/src/doctor-contract.ts +287 -0
- package/src/doctor.ts +262 -0
- package/src/env-vars.ts +92 -0
- package/src/exec-approval-resolver.ts +23 -0
- package/src/exec-approvals.ts +293 -0
- package/src/group-mentions.ts +41 -0
- package/src/legacy-crypto-inspector-availability.ts +60 -0
- package/src/legacy-crypto.ts +531 -0
- package/src/legacy-state.ts +156 -0
- package/src/matrix/account-config.ts +175 -0
- package/src/matrix/accounts.ts +194 -0
- package/src/matrix/actions/client.ts +31 -0
- package/src/matrix/actions/devices.ts +34 -0
- package/src/matrix/actions/limits.ts +6 -0
- package/src/matrix/actions/messages.ts +129 -0
- package/src/matrix/actions/pins.ts +63 -0
- package/src/matrix/actions/polls.ts +109 -0
- package/src/matrix/actions/profile.ts +37 -0
- package/src/matrix/actions/reactions.ts +59 -0
- package/src/matrix/actions/room.ts +71 -0
- package/src/matrix/actions/summary.ts +88 -0
- package/src/matrix/actions/types.ts +63 -0
- package/src/matrix/actions/verification.ts +589 -0
- package/src/matrix/actions.ts +37 -0
- package/src/matrix/active-client.ts +26 -0
- package/src/matrix/async-lock.ts +18 -0
- package/src/matrix/backup-health.ts +124 -0
- package/src/matrix/client/config-runtime-api.ts +9 -0
- package/src/matrix/client/config-secret-input.runtime.ts +1 -0
- package/src/matrix/client/config.ts +853 -0
- package/src/matrix/client/create-client.ts +105 -0
- package/src/matrix/client/env-auth.ts +95 -0
- package/src/matrix/client/file-sync-store.ts +289 -0
- package/src/matrix/client/logging.ts +140 -0
- package/src/matrix/client/migration-snapshot.runtime.ts +1 -0
- package/src/matrix/client/private-network-host.ts +1 -0
- package/src/matrix/client/runtime.ts +4 -0
- package/src/matrix/client/shared.ts +316 -0
- package/src/matrix/client/storage.ts +543 -0
- package/src/matrix/client/types.ts +50 -0
- package/src/matrix/client/url-validation.ts +76 -0
- package/src/matrix/client-bootstrap.ts +173 -0
- package/src/matrix/client.ts +23 -0
- package/src/matrix/config-paths.ts +31 -0
- package/src/matrix/config-update.ts +292 -0
- package/src/matrix/credentials-read.ts +207 -0
- package/src/matrix/credentials-write.runtime.ts +35 -0
- package/src/matrix/credentials.ts +95 -0
- package/src/matrix/deps.ts +309 -0
- package/src/matrix/device-health.ts +31 -0
- package/src/matrix/direct-management.ts +349 -0
- package/src/matrix/direct-room.ts +128 -0
- package/src/matrix/draft-stream.ts +225 -0
- package/src/matrix/encryption-guidance.ts +24 -0
- package/src/matrix/errors.ts +21 -0
- package/src/matrix/format.ts +426 -0
- package/src/matrix/legacy-crypto-inspector.ts +95 -0
- package/src/matrix/media-errors.ts +20 -0
- package/src/matrix/media-text.ts +162 -0
- package/src/matrix/monitor/access-state.ts +145 -0
- package/src/matrix/monitor/ack-config.ts +27 -0
- package/src/matrix/monitor/allowlist.ts +92 -0
- package/src/matrix/monitor/auto-join.ts +86 -0
- package/src/matrix/monitor/config.ts +569 -0
- package/src/matrix/monitor/context-summary.ts +43 -0
- package/src/matrix/monitor/direct.ts +296 -0
- package/src/matrix/monitor/events.ts +397 -0
- package/src/matrix/monitor/handler.ts +2271 -0
- package/src/matrix/monitor/inbound-dedupe.ts +267 -0
- package/src/matrix/monitor/index.ts +540 -0
- package/src/matrix/monitor/legacy-crypto-restore.ts +139 -0
- package/src/matrix/monitor/location.ts +108 -0
- package/src/matrix/monitor/media.ts +119 -0
- package/src/matrix/monitor/mentions.ts +256 -0
- package/src/matrix/monitor/reaction-events.ts +197 -0
- package/src/matrix/monitor/recent-invite.ts +30 -0
- package/src/matrix/monitor/replies.ts +136 -0
- package/src/matrix/monitor/reply-context.ts +92 -0
- package/src/matrix/monitor/room-history.ts +301 -0
- package/src/matrix/monitor/room-info.ts +126 -0
- package/src/matrix/monitor/rooms.ts +52 -0
- package/src/matrix/monitor/route.ts +179 -0
- package/src/matrix/monitor/runtime-api.ts +28 -0
- package/src/matrix/monitor/startup-verification.ts +237 -0
- package/src/matrix/monitor/startup.ts +218 -0
- package/src/matrix/monitor/status.ts +120 -0
- package/src/matrix/monitor/sync-lifecycle.ts +91 -0
- package/src/matrix/monitor/task-runner.ts +38 -0
- package/src/matrix/monitor/test-events.ts +21 -0
- package/src/matrix/monitor/thread-context.ts +108 -0
- package/src/matrix/monitor/threads.ts +85 -0
- package/src/matrix/monitor/types.ts +30 -0
- package/src/matrix/monitor/verification-events.ts +643 -0
- package/src/matrix/monitor/verification-utils.ts +46 -0
- package/src/matrix/outbound-media-runtime.ts +1 -0
- package/src/matrix/poll-summary.ts +110 -0
- package/src/matrix/poll-types.ts +429 -0
- package/src/matrix/probe.runtime.ts +4 -0
- package/src/matrix/probe.ts +97 -0
- package/src/matrix/profile.ts +184 -0
- package/src/matrix/reaction-common.ts +147 -0
- package/src/matrix/sdk/crypto-bootstrap.ts +438 -0
- package/src/matrix/sdk/crypto-facade.ts +242 -0
- package/src/matrix/sdk/crypto-node.runtime.ts +17 -0
- package/src/matrix/sdk/crypto-runtime.ts +14 -0
- package/src/matrix/sdk/decrypt-bridge.ts +410 -0
- package/src/matrix/sdk/event-helpers.ts +83 -0
- package/src/matrix/sdk/http-client.ts +87 -0
- package/src/matrix/sdk/idb-persistence-lock.ts +51 -0
- package/src/matrix/sdk/idb-persistence.ts +286 -0
- package/src/matrix/sdk/logger.ts +108 -0
- package/src/matrix/sdk/read-response-with-limit.ts +19 -0
- package/src/matrix/sdk/recovery-key-store.ts +453 -0
- package/src/matrix/sdk/timeout-abort-signal.ts +1 -0
- package/src/matrix/sdk/transport-runtime-api.ts +18 -0
- package/src/matrix/sdk/transport.ts +352 -0
- package/src/matrix/sdk/types.ts +245 -0
- package/src/matrix/sdk/verification-manager.ts +795 -0
- package/src/matrix/sdk/verification-status.ts +23 -0
- package/src/matrix/sdk.ts +2152 -0
- package/src/matrix/send/client.ts +93 -0
- package/src/matrix/send/formatting.ts +189 -0
- package/src/matrix/send/media.ts +244 -0
- package/src/matrix/send/targets.ts +104 -0
- package/src/matrix/send/types.ts +131 -0
- package/src/matrix/send.ts +660 -0
- package/src/matrix/session-store-metadata.ts +108 -0
- package/src/matrix/startup-abort.ts +44 -0
- package/src/matrix/subagent-hooks.ts +308 -0
- package/src/matrix/sync-state.ts +27 -0
- package/src/matrix/target-ids.ts +79 -0
- package/src/matrix/thread-bindings-shared.ts +206 -0
- package/src/matrix/thread-bindings.ts +580 -0
- package/src/matrix-migration.runtime.ts +9 -0
- package/src/migration-config.ts +243 -0
- package/src/migration-snapshot-backup.ts +116 -0
- package/src/migration-snapshot.ts +53 -0
- package/src/onboarding.ts +775 -0
- package/src/outbound.ts +248 -0
- package/src/plugin-entry.runtime.js +115 -0
- package/src/plugin-entry.runtime.ts +70 -0
- package/src/profile-update.ts +71 -0
- package/src/record-shared.ts +3 -0
- package/src/resolve-targets.ts +175 -0
- package/src/resolver.runtime.ts +5 -0
- package/src/resolver.ts +21 -0
- package/src/runtime-api.ts +106 -0
- package/src/runtime.ts +13 -0
- package/src/secret-contract.ts +174 -0
- package/src/session-route.ts +126 -0
- package/src/setup-bootstrap.ts +102 -0
- package/src/setup-config.ts +222 -0
- package/src/setup-contract.ts +90 -0
- package/src/setup-core.ts +146 -0
- package/src/setup-dm-policy.ts +15 -0
- package/src/setup-surface.ts +4 -0
- package/src/startup-maintenance.ts +114 -0
- package/src/storage-paths.ts +92 -0
- package/src/thread-binding-api.ts +23 -0
- package/src/tool-actions.runtime.ts +1 -0
- package/src/tool-actions.ts +498 -0
- package/src/types.ts +257 -0
- package/subagent-hooks-api.ts +31 -0
- package/test-api.ts +21 -0
- package/thread-binding-api.ts +4 -0
- package/thread-bindings-runtime.ts +4 -0
- package/tsconfig.json +16 -0
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
import { KeyedAsyncQueue } from "autobot/plugin-sdk/keyed-async-queue";
|
|
2
|
+
import { normalizeOptionalString } from "autobot/plugin-sdk/string-coerce-runtime";
|
|
3
|
+
import { inspectMatrixDirectRoomEvidence } from "./direct-room.js";
|
|
4
|
+
import type { MatrixClient } from "./sdk.js";
|
|
5
|
+
import { EventType, type MatrixDirectAccountData } from "./send/types.js";
|
|
6
|
+
import { isMatrixQualifiedUserId } from "./target-ids.js";
|
|
7
|
+
|
|
8
|
+
export type MatrixDirectRoomCandidate = {
|
|
9
|
+
roomId: string;
|
|
10
|
+
joinedMembers: string[] | null;
|
|
11
|
+
strict: boolean;
|
|
12
|
+
explicit: boolean;
|
|
13
|
+
source: "account-data" | "joined";
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export type MatrixDirectRoomInspection = {
|
|
17
|
+
selfUserId: string | null;
|
|
18
|
+
remoteUserId: string;
|
|
19
|
+
mappedRoomIds: string[];
|
|
20
|
+
mappedRooms: MatrixDirectRoomCandidate[];
|
|
21
|
+
discoveredStrictRoomIds: string[];
|
|
22
|
+
activeRoomId: string | null;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export type MatrixDirectRoomRepairResult = MatrixDirectRoomInspection & {
|
|
26
|
+
createdRoomId: string | null;
|
|
27
|
+
changed: boolean;
|
|
28
|
+
directContentBefore: MatrixDirectAccountData;
|
|
29
|
+
directContentAfter: MatrixDirectAccountData;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
export type MatrixDirectRoomPromotionResult =
|
|
33
|
+
| {
|
|
34
|
+
classifyAsDirect: true;
|
|
35
|
+
repaired: boolean;
|
|
36
|
+
roomId: string;
|
|
37
|
+
reason: "promoted" | "already-mapped" | "repair-failed";
|
|
38
|
+
}
|
|
39
|
+
| {
|
|
40
|
+
classifyAsDirect: false;
|
|
41
|
+
repaired: false;
|
|
42
|
+
reason: "not-strict" | "local-explicit-false";
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
type MatrixDirectRoomMappingWriteResult = {
|
|
46
|
+
changed: boolean;
|
|
47
|
+
directContentBefore: MatrixDirectAccountData;
|
|
48
|
+
directContentAfter: MatrixDirectAccountData;
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
const DIRECT_ACCOUNT_DATA_QUEUE_KEY = EventType.Direct;
|
|
52
|
+
const directAccountDataWriteQueues = new WeakMap<MatrixClient, KeyedAsyncQueue>();
|
|
53
|
+
|
|
54
|
+
async function readMatrixDirectAccountData(client: MatrixClient): Promise<MatrixDirectAccountData> {
|
|
55
|
+
try {
|
|
56
|
+
const direct = (await client.getAccountData(EventType.Direct)) as MatrixDirectAccountData;
|
|
57
|
+
return direct && typeof direct === "object" && !Array.isArray(direct) ? direct : {};
|
|
58
|
+
} catch {
|
|
59
|
+
return {};
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function normalizeRemoteUserId(remoteUserId: string): string {
|
|
64
|
+
const normalized = normalizeOptionalString(remoteUserId) ?? "";
|
|
65
|
+
if (!isMatrixQualifiedUserId(normalized)) {
|
|
66
|
+
throw new Error(`Matrix user IDs must be fully qualified (got "${remoteUserId}")`);
|
|
67
|
+
}
|
|
68
|
+
return normalized;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function normalizeMappedRoomIds(direct: MatrixDirectAccountData, remoteUserId: string): string[] {
|
|
72
|
+
const current = direct[remoteUserId];
|
|
73
|
+
if (!Array.isArray(current)) {
|
|
74
|
+
return [];
|
|
75
|
+
}
|
|
76
|
+
const seen = new Set<string>();
|
|
77
|
+
const normalized: string[] = [];
|
|
78
|
+
for (const value of current) {
|
|
79
|
+
const roomId = normalizeOptionalString(value) ?? "";
|
|
80
|
+
if (!roomId || seen.has(roomId)) {
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
seen.add(roomId);
|
|
84
|
+
normalized.push(roomId);
|
|
85
|
+
}
|
|
86
|
+
return normalized;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function normalizeRoomIdList(values: readonly string[]): string[] {
|
|
90
|
+
const seen = new Set<string>();
|
|
91
|
+
const normalized: string[] = [];
|
|
92
|
+
for (const value of values) {
|
|
93
|
+
const roomId = value.trim();
|
|
94
|
+
if (!roomId || seen.has(roomId)) {
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
seen.add(roomId);
|
|
98
|
+
normalized.push(roomId);
|
|
99
|
+
}
|
|
100
|
+
return normalized;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function hasMatrixDirectRoomMappings(params: {
|
|
104
|
+
directContent: MatrixDirectAccountData;
|
|
105
|
+
remoteUserId: string;
|
|
106
|
+
roomIds: readonly string[];
|
|
107
|
+
}): boolean {
|
|
108
|
+
const current = normalizeMappedRoomIds(params.directContent, params.remoteUserId);
|
|
109
|
+
const next = normalizeRoomIdList([...params.roomIds, ...current]);
|
|
110
|
+
return current.length === next.length && current.every((roomId, index) => roomId === next[index]);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function resolveDirectAccountDataWriteQueue(client: MatrixClient): KeyedAsyncQueue {
|
|
114
|
+
const existing = directAccountDataWriteQueues.get(client);
|
|
115
|
+
if (existing) {
|
|
116
|
+
return existing;
|
|
117
|
+
}
|
|
118
|
+
const created = new KeyedAsyncQueue();
|
|
119
|
+
directAccountDataWriteQueues.set(client, created);
|
|
120
|
+
return created;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async function writeMatrixDirectRoomMappings(params: {
|
|
124
|
+
client: MatrixClient;
|
|
125
|
+
remoteUserId: string;
|
|
126
|
+
roomIds: readonly string[];
|
|
127
|
+
}): Promise<MatrixDirectRoomMappingWriteResult> {
|
|
128
|
+
return await resolveDirectAccountDataWriteQueue(params.client).enqueue(
|
|
129
|
+
DIRECT_ACCOUNT_DATA_QUEUE_KEY,
|
|
130
|
+
async () => {
|
|
131
|
+
const directContentBefore = await readMatrixDirectAccountData(params.client);
|
|
132
|
+
const directContentAfter = buildNextDirectContent({
|
|
133
|
+
directContent: directContentBefore,
|
|
134
|
+
remoteUserId: params.remoteUserId,
|
|
135
|
+
roomIds: params.roomIds,
|
|
136
|
+
});
|
|
137
|
+
const changed = !hasMatrixDirectRoomMappings({
|
|
138
|
+
directContent: directContentBefore,
|
|
139
|
+
remoteUserId: params.remoteUserId,
|
|
140
|
+
roomIds: params.roomIds,
|
|
141
|
+
});
|
|
142
|
+
if (changed) {
|
|
143
|
+
await params.client.setAccountData(EventType.Direct, directContentAfter);
|
|
144
|
+
}
|
|
145
|
+
return {
|
|
146
|
+
changed,
|
|
147
|
+
directContentBefore,
|
|
148
|
+
directContentAfter,
|
|
149
|
+
};
|
|
150
|
+
},
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async function classifyDirectRoomCandidate(params: {
|
|
155
|
+
client: MatrixClient;
|
|
156
|
+
roomId: string;
|
|
157
|
+
remoteUserId: string;
|
|
158
|
+
selfUserId: string | null;
|
|
159
|
+
source: "account-data" | "joined";
|
|
160
|
+
}): Promise<MatrixDirectRoomCandidate> {
|
|
161
|
+
const evidence = await inspectMatrixDirectRoomEvidence({
|
|
162
|
+
client: params.client,
|
|
163
|
+
roomId: params.roomId,
|
|
164
|
+
remoteUserId: params.remoteUserId,
|
|
165
|
+
selfUserId: params.selfUserId,
|
|
166
|
+
});
|
|
167
|
+
return {
|
|
168
|
+
roomId: params.roomId,
|
|
169
|
+
joinedMembers: evidence.joinedMembers,
|
|
170
|
+
strict:
|
|
171
|
+
evidence.strict && (params.source === "account-data" || evidence.memberStateFlag !== false),
|
|
172
|
+
explicit:
|
|
173
|
+
evidence.strict &&
|
|
174
|
+
(params.source === "account-data" || evidence.memberStateFlag !== false) &&
|
|
175
|
+
(params.source === "account-data" || evidence.viaMemberState),
|
|
176
|
+
source: params.source,
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function buildNextDirectContent(params: {
|
|
181
|
+
directContent: MatrixDirectAccountData;
|
|
182
|
+
remoteUserId: string;
|
|
183
|
+
roomIds: readonly string[];
|
|
184
|
+
}): MatrixDirectAccountData {
|
|
185
|
+
const current = normalizeMappedRoomIds(params.directContent, params.remoteUserId);
|
|
186
|
+
const nextRooms = normalizeRoomIdList([...params.roomIds, ...current]);
|
|
187
|
+
return {
|
|
188
|
+
...params.directContent,
|
|
189
|
+
[params.remoteUserId]: nextRooms,
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export async function persistMatrixDirectRoomMapping(params: {
|
|
194
|
+
client: MatrixClient;
|
|
195
|
+
remoteUserId: string;
|
|
196
|
+
roomId: string;
|
|
197
|
+
}): Promise<boolean> {
|
|
198
|
+
const remoteUserId = normalizeRemoteUserId(params.remoteUserId);
|
|
199
|
+
return (
|
|
200
|
+
await writeMatrixDirectRoomMappings({
|
|
201
|
+
client: params.client,
|
|
202
|
+
remoteUserId,
|
|
203
|
+
roomIds: [params.roomId],
|
|
204
|
+
})
|
|
205
|
+
).changed;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
export async function promoteMatrixDirectRoomCandidate(params: {
|
|
209
|
+
client: MatrixClient;
|
|
210
|
+
remoteUserId: string;
|
|
211
|
+
roomId: string;
|
|
212
|
+
selfUserId?: string | null;
|
|
213
|
+
}): Promise<MatrixDirectRoomPromotionResult> {
|
|
214
|
+
const remoteUserId = normalizeRemoteUserId(params.remoteUserId);
|
|
215
|
+
const evidence = await inspectMatrixDirectRoomEvidence({
|
|
216
|
+
client: params.client,
|
|
217
|
+
roomId: params.roomId,
|
|
218
|
+
remoteUserId,
|
|
219
|
+
selfUserId: params.selfUserId,
|
|
220
|
+
});
|
|
221
|
+
if (!evidence.strict) {
|
|
222
|
+
return {
|
|
223
|
+
classifyAsDirect: false,
|
|
224
|
+
repaired: false,
|
|
225
|
+
reason: "not-strict",
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
if (evidence.memberStateFlag === false) {
|
|
229
|
+
return {
|
|
230
|
+
classifyAsDirect: false,
|
|
231
|
+
repaired: false,
|
|
232
|
+
reason: "local-explicit-false",
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
try {
|
|
237
|
+
const repaired = await persistMatrixDirectRoomMapping({
|
|
238
|
+
client: params.client,
|
|
239
|
+
remoteUserId,
|
|
240
|
+
roomId: params.roomId,
|
|
241
|
+
});
|
|
242
|
+
return {
|
|
243
|
+
classifyAsDirect: true,
|
|
244
|
+
repaired,
|
|
245
|
+
roomId: params.roomId,
|
|
246
|
+
reason: repaired ? "promoted" : "already-mapped",
|
|
247
|
+
};
|
|
248
|
+
} catch {
|
|
249
|
+
return {
|
|
250
|
+
classifyAsDirect: true,
|
|
251
|
+
repaired: false,
|
|
252
|
+
roomId: params.roomId,
|
|
253
|
+
reason: "repair-failed",
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
export async function inspectMatrixDirectRooms(params: {
|
|
259
|
+
client: MatrixClient;
|
|
260
|
+
remoteUserId: string;
|
|
261
|
+
}): Promise<MatrixDirectRoomInspection> {
|
|
262
|
+
const remoteUserId = normalizeRemoteUserId(params.remoteUserId);
|
|
263
|
+
const selfUserId =
|
|
264
|
+
normalizeOptionalString(await params.client.getUserId().catch(() => null)) ?? null;
|
|
265
|
+
const directContent = await readMatrixDirectAccountData(params.client);
|
|
266
|
+
const mappedRoomIds = normalizeMappedRoomIds(directContent, remoteUserId);
|
|
267
|
+
const mappedRooms = await Promise.all(
|
|
268
|
+
mappedRoomIds.map(
|
|
269
|
+
async (roomId) =>
|
|
270
|
+
await classifyDirectRoomCandidate({
|
|
271
|
+
client: params.client,
|
|
272
|
+
roomId,
|
|
273
|
+
remoteUserId,
|
|
274
|
+
selfUserId,
|
|
275
|
+
source: "account-data",
|
|
276
|
+
}),
|
|
277
|
+
),
|
|
278
|
+
);
|
|
279
|
+
const mappedStrict = mappedRooms.find((room) => room.strict);
|
|
280
|
+
|
|
281
|
+
let joinedRooms: string[] = [];
|
|
282
|
+
if (typeof params.client.getJoinedRooms === "function") {
|
|
283
|
+
try {
|
|
284
|
+
const resolved = await params.client.getJoinedRooms();
|
|
285
|
+
joinedRooms = Array.isArray(resolved) ? resolved : [];
|
|
286
|
+
} catch {
|
|
287
|
+
joinedRooms = [];
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
const discoveredStrictRooms: MatrixDirectRoomCandidate[] = [];
|
|
291
|
+
for (const roomId of normalizeRoomIdList(joinedRooms)) {
|
|
292
|
+
if (mappedRoomIds.includes(roomId)) {
|
|
293
|
+
continue;
|
|
294
|
+
}
|
|
295
|
+
const candidate = await classifyDirectRoomCandidate({
|
|
296
|
+
client: params.client,
|
|
297
|
+
roomId,
|
|
298
|
+
remoteUserId,
|
|
299
|
+
selfUserId,
|
|
300
|
+
source: "joined",
|
|
301
|
+
});
|
|
302
|
+
if (candidate.strict) {
|
|
303
|
+
discoveredStrictRooms.push(candidate);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
const discoveredStrictRoomIds = discoveredStrictRooms.map((room) => room.roomId);
|
|
307
|
+
const discoveredExplicit = discoveredStrictRooms.find((room) => room.explicit);
|
|
308
|
+
|
|
309
|
+
return {
|
|
310
|
+
selfUserId,
|
|
311
|
+
remoteUserId,
|
|
312
|
+
mappedRoomIds,
|
|
313
|
+
mappedRooms,
|
|
314
|
+
discoveredStrictRoomIds,
|
|
315
|
+
activeRoomId:
|
|
316
|
+
mappedStrict?.roomId ?? discoveredExplicit?.roomId ?? discoveredStrictRoomIds[0] ?? null,
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
export async function repairMatrixDirectRooms(params: {
|
|
321
|
+
client: MatrixClient;
|
|
322
|
+
remoteUserId: string;
|
|
323
|
+
encrypted?: boolean;
|
|
324
|
+
}): Promise<MatrixDirectRoomRepairResult> {
|
|
325
|
+
const remoteUserId = normalizeRemoteUserId(params.remoteUserId);
|
|
326
|
+
const inspected = await inspectMatrixDirectRooms({
|
|
327
|
+
client: params.client,
|
|
328
|
+
remoteUserId,
|
|
329
|
+
});
|
|
330
|
+
const activeRoomId =
|
|
331
|
+
inspected.activeRoomId ??
|
|
332
|
+
(await params.client.createDirectRoom(remoteUserId, {
|
|
333
|
+
encrypted: params.encrypted === true,
|
|
334
|
+
}));
|
|
335
|
+
const createdRoomId = inspected.activeRoomId ? null : activeRoomId;
|
|
336
|
+
const mappingWrite = await writeMatrixDirectRoomMappings({
|
|
337
|
+
client: params.client,
|
|
338
|
+
remoteUserId,
|
|
339
|
+
roomIds: [activeRoomId, ...inspected.discoveredStrictRoomIds],
|
|
340
|
+
});
|
|
341
|
+
return {
|
|
342
|
+
...inspected,
|
|
343
|
+
activeRoomId,
|
|
344
|
+
createdRoomId,
|
|
345
|
+
changed: mappingWrite.changed,
|
|
346
|
+
directContentBefore: mappingWrite.directContentBefore,
|
|
347
|
+
directContentAfter: mappingWrite.directContentAfter,
|
|
348
|
+
};
|
|
349
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import type { MatrixClient } from "./sdk.js";
|
|
2
|
+
|
|
3
|
+
function trimMaybeString(value: unknown): string | null {
|
|
4
|
+
if (typeof value !== "string") {
|
|
5
|
+
return null;
|
|
6
|
+
}
|
|
7
|
+
const trimmed = value.trim();
|
|
8
|
+
return trimmed.length > 0 ? trimmed : null;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function normalizeJoinedMatrixMembers(joinedMembers: unknown): string[] {
|
|
12
|
+
if (!Array.isArray(joinedMembers)) {
|
|
13
|
+
return [];
|
|
14
|
+
}
|
|
15
|
+
return joinedMembers
|
|
16
|
+
.map((entry) => trimMaybeString(entry))
|
|
17
|
+
.filter((entry): entry is string => Boolean(entry));
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function isStrictDirectMembership(params: {
|
|
21
|
+
selfUserId?: string | null;
|
|
22
|
+
remoteUserId?: string | null;
|
|
23
|
+
joinedMembers?: readonly string[] | null;
|
|
24
|
+
}): boolean {
|
|
25
|
+
const selfUserId = trimMaybeString(params.selfUserId);
|
|
26
|
+
const remoteUserId = trimMaybeString(params.remoteUserId);
|
|
27
|
+
const joinedMembers = params.joinedMembers ?? [];
|
|
28
|
+
return Boolean(
|
|
29
|
+
selfUserId &&
|
|
30
|
+
remoteUserId &&
|
|
31
|
+
joinedMembers.length === 2 &&
|
|
32
|
+
joinedMembers.includes(selfUserId) &&
|
|
33
|
+
joinedMembers.includes(remoteUserId),
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export async function readJoinedMatrixMembers(
|
|
38
|
+
client: MatrixClient,
|
|
39
|
+
roomId: string,
|
|
40
|
+
): Promise<string[] | null> {
|
|
41
|
+
try {
|
|
42
|
+
return normalizeJoinedMatrixMembers(await client.getJoinedRoomMembers(roomId));
|
|
43
|
+
} catch {
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export async function hasDirectMatrixMemberFlag(
|
|
49
|
+
client: MatrixClient,
|
|
50
|
+
roomId: string,
|
|
51
|
+
userId?: string | null,
|
|
52
|
+
): Promise<boolean | null> {
|
|
53
|
+
const normalizedUserId = trimMaybeString(userId);
|
|
54
|
+
if (!normalizedUserId) {
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
try {
|
|
58
|
+
const state = await client.getRoomStateEvent(roomId, "m.room.member", normalizedUserId);
|
|
59
|
+
// Return true if is_direct is explicitly true, false if explicitly false, null if absent
|
|
60
|
+
if (state?.is_direct === true) {
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
if (state?.is_direct === false) {
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
// is_direct field is absent from the membership event
|
|
67
|
+
return null;
|
|
68
|
+
} catch {
|
|
69
|
+
// API/network error - treat as unavailable
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export type MatrixDirectRoomEvidence = {
|
|
75
|
+
joinedMembers: string[] | null;
|
|
76
|
+
strict: boolean;
|
|
77
|
+
viaMemberState: boolean;
|
|
78
|
+
memberStateFlag: boolean | null;
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
export async function inspectMatrixDirectRoomEvidence(params: {
|
|
82
|
+
client: MatrixClient;
|
|
83
|
+
roomId: string;
|
|
84
|
+
remoteUserId: string;
|
|
85
|
+
selfUserId?: string | null;
|
|
86
|
+
}): Promise<MatrixDirectRoomEvidence> {
|
|
87
|
+
const selfUserId =
|
|
88
|
+
params.selfUserId !== undefined
|
|
89
|
+
? trimMaybeString(params.selfUserId)
|
|
90
|
+
: trimMaybeString(await params.client.getUserId().catch(() => null));
|
|
91
|
+
const joinedMembers = await readJoinedMatrixMembers(params.client, params.roomId);
|
|
92
|
+
const strict = isStrictDirectMembership({
|
|
93
|
+
selfUserId,
|
|
94
|
+
remoteUserId: params.remoteUserId,
|
|
95
|
+
joinedMembers,
|
|
96
|
+
});
|
|
97
|
+
if (!strict) {
|
|
98
|
+
return {
|
|
99
|
+
joinedMembers,
|
|
100
|
+
strict: false,
|
|
101
|
+
viaMemberState: false,
|
|
102
|
+
memberStateFlag: null,
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
const memberStateFlag = await hasDirectMatrixMemberFlag(params.client, params.roomId, selfUserId);
|
|
106
|
+
return {
|
|
107
|
+
joinedMembers,
|
|
108
|
+
strict,
|
|
109
|
+
viaMemberState: memberStateFlag === true,
|
|
110
|
+
memberStateFlag,
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export async function isStrictDirectRoom(params: {
|
|
115
|
+
client: MatrixClient;
|
|
116
|
+
roomId: string;
|
|
117
|
+
remoteUserId: string;
|
|
118
|
+
selfUserId?: string | null;
|
|
119
|
+
}): Promise<boolean> {
|
|
120
|
+
return (
|
|
121
|
+
await inspectMatrixDirectRoomEvidence({
|
|
122
|
+
client: params.client,
|
|
123
|
+
roomId: params.roomId,
|
|
124
|
+
remoteUserId: params.remoteUserId,
|
|
125
|
+
selfUserId: params.selfUserId,
|
|
126
|
+
})
|
|
127
|
+
).strict;
|
|
128
|
+
}
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import { createDraftStreamLoop } from "autobot/plugin-sdk/channel-lifecycle";
|
|
2
|
+
import type { CoreConfig } from "../types.js";
|
|
3
|
+
import type { MatrixClient } from "./sdk.js";
|
|
4
|
+
import { editMessageMatrix, prepareMatrixSingleText, sendSingleTextMessageMatrix } from "./send.js";
|
|
5
|
+
import { MsgType } from "./send/types.js";
|
|
6
|
+
|
|
7
|
+
const DEFAULT_THROTTLE_MS = 1000;
|
|
8
|
+
type MatrixDraftPreviewMode = "partial" | "quiet";
|
|
9
|
+
|
|
10
|
+
function resolveDraftPreviewOptions(mode: MatrixDraftPreviewMode): {
|
|
11
|
+
msgtype: typeof MsgType.Text | typeof MsgType.Notice;
|
|
12
|
+
includeMentions?: boolean;
|
|
13
|
+
} {
|
|
14
|
+
if (mode === "quiet") {
|
|
15
|
+
return {
|
|
16
|
+
msgtype: MsgType.Notice,
|
|
17
|
+
includeMentions: false,
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
return {
|
|
21
|
+
msgtype: MsgType.Text,
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export type MatrixDraftStream = {
|
|
26
|
+
/** Update the draft with the latest accumulated text for the current block. */
|
|
27
|
+
update: (text: string) => void;
|
|
28
|
+
/** Ensure the last pending update has been sent. */
|
|
29
|
+
flush: () => Promise<void>;
|
|
30
|
+
/** Flush and mark this block as done. Returns the event ID if a message was sent. */
|
|
31
|
+
stop: () => Promise<string | undefined>;
|
|
32
|
+
/** Cancel pending draft updates without creating a new preview event. */
|
|
33
|
+
discardPending: () => Promise<void>;
|
|
34
|
+
/** Clear the MSC4357 live marker in place when the draft is kept as final text. */
|
|
35
|
+
finalizeLive: () => Promise<boolean>;
|
|
36
|
+
/** Reset state for the next text block (after tool calls). */
|
|
37
|
+
reset: () => void;
|
|
38
|
+
/** The event ID of the current draft message, if any. */
|
|
39
|
+
eventId: () => string | undefined;
|
|
40
|
+
/** True when the provided text matches the last rendered draft payload. */
|
|
41
|
+
matchesPreparedText: (text: string) => boolean;
|
|
42
|
+
/** True when preview streaming must fall back to normal final delivery. */
|
|
43
|
+
mustDeliverFinalNormally: () => boolean;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
export function createMatrixDraftStream(params: {
|
|
47
|
+
roomId: string;
|
|
48
|
+
client: MatrixClient;
|
|
49
|
+
cfg: CoreConfig;
|
|
50
|
+
mode?: MatrixDraftPreviewMode;
|
|
51
|
+
threadId?: string;
|
|
52
|
+
replyToId?: string;
|
|
53
|
+
/** When true, reset() restores the original replyToId instead of clearing it. */
|
|
54
|
+
preserveReplyId?: boolean;
|
|
55
|
+
accountId?: string;
|
|
56
|
+
log?: (message: string) => void;
|
|
57
|
+
}): MatrixDraftStream {
|
|
58
|
+
const { roomId, client, cfg, threadId, accountId, log } = params;
|
|
59
|
+
const preview = resolveDraftPreviewOptions(params.mode ?? "partial");
|
|
60
|
+
// MSC4357 live markers are only useful for "partial" mode where users see
|
|
61
|
+
// the draft evolve. "quiet" mode uses m.notice for background previews
|
|
62
|
+
// where a streaming animation would be unexpected.
|
|
63
|
+
const useLive = params.mode !== "quiet";
|
|
64
|
+
|
|
65
|
+
let currentEventId: string | undefined;
|
|
66
|
+
let lastSentText = "";
|
|
67
|
+
let stopped = false;
|
|
68
|
+
let sendFailed = false;
|
|
69
|
+
let finalizeInPlaceBlocked = false;
|
|
70
|
+
let liveFinalized = false;
|
|
71
|
+
let replyToId = params.replyToId;
|
|
72
|
+
|
|
73
|
+
const sendOrEdit = async (text: string): Promise<boolean> => {
|
|
74
|
+
const trimmed = text.trimEnd();
|
|
75
|
+
if (!trimmed) {
|
|
76
|
+
return false;
|
|
77
|
+
}
|
|
78
|
+
const preparedText = prepareMatrixSingleText(trimmed, { cfg, accountId });
|
|
79
|
+
if (!preparedText.fitsInSingleEvent) {
|
|
80
|
+
finalizeInPlaceBlocked = true;
|
|
81
|
+
if (!currentEventId) {
|
|
82
|
+
sendFailed = true;
|
|
83
|
+
}
|
|
84
|
+
stopped = true;
|
|
85
|
+
log?.(
|
|
86
|
+
`draft-stream: preview exceeded single-event limit (${preparedText.convertedText.length} > ${preparedText.singleEventLimit})`,
|
|
87
|
+
);
|
|
88
|
+
return false;
|
|
89
|
+
}
|
|
90
|
+
if (sendFailed) {
|
|
91
|
+
return false;
|
|
92
|
+
}
|
|
93
|
+
if (preparedText.trimmedText === lastSentText) {
|
|
94
|
+
return true;
|
|
95
|
+
}
|
|
96
|
+
try {
|
|
97
|
+
if (!currentEventId) {
|
|
98
|
+
const result = await sendSingleTextMessageMatrix(roomId, preparedText.trimmedText, {
|
|
99
|
+
client,
|
|
100
|
+
cfg,
|
|
101
|
+
replyToId,
|
|
102
|
+
threadId,
|
|
103
|
+
accountId,
|
|
104
|
+
msgtype: preview.msgtype,
|
|
105
|
+
includeMentions: preview.includeMentions,
|
|
106
|
+
live: useLive,
|
|
107
|
+
});
|
|
108
|
+
currentEventId = result.messageId;
|
|
109
|
+
lastSentText = preparedText.trimmedText;
|
|
110
|
+
log?.(`draft-stream: created message ${currentEventId}${useLive ? " (MSC4357 live)" : ""}`);
|
|
111
|
+
} else {
|
|
112
|
+
await editMessageMatrix(roomId, currentEventId, preparedText.trimmedText, {
|
|
113
|
+
client,
|
|
114
|
+
cfg,
|
|
115
|
+
threadId,
|
|
116
|
+
accountId,
|
|
117
|
+
msgtype: preview.msgtype,
|
|
118
|
+
includeMentions: preview.includeMentions,
|
|
119
|
+
live: useLive,
|
|
120
|
+
});
|
|
121
|
+
lastSentText = preparedText.trimmedText;
|
|
122
|
+
}
|
|
123
|
+
return true;
|
|
124
|
+
} catch (err) {
|
|
125
|
+
log?.(`draft-stream: send/edit failed: ${String(err)}`);
|
|
126
|
+
const isPreviewLimitError =
|
|
127
|
+
err instanceof Error && err.message.startsWith("Matrix single-message text exceeds limit");
|
|
128
|
+
if (isPreviewLimitError) {
|
|
129
|
+
finalizeInPlaceBlocked = true;
|
|
130
|
+
}
|
|
131
|
+
if (!currentEventId) {
|
|
132
|
+
sendFailed = true;
|
|
133
|
+
}
|
|
134
|
+
stopped = true;
|
|
135
|
+
return false;
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
const loop = createDraftStreamLoop({
|
|
140
|
+
throttleMs: DEFAULT_THROTTLE_MS,
|
|
141
|
+
isStopped: () => stopped,
|
|
142
|
+
sendOrEditStreamMessage: sendOrEdit,
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
log?.(`draft-stream: ready (throttleMs=${DEFAULT_THROTTLE_MS})`);
|
|
146
|
+
|
|
147
|
+
const finalizeLive = async (): Promise<boolean> => {
|
|
148
|
+
// Send a final edit without the MSC4357 live marker to signal that
|
|
149
|
+
// the stream is complete. Supporting clients will stop the streaming
|
|
150
|
+
// animation and display the final content.
|
|
151
|
+
if (useLive && !liveFinalized && currentEventId && lastSentText) {
|
|
152
|
+
liveFinalized = true;
|
|
153
|
+
try {
|
|
154
|
+
await editMessageMatrix(roomId, currentEventId, lastSentText, {
|
|
155
|
+
client,
|
|
156
|
+
cfg,
|
|
157
|
+
threadId,
|
|
158
|
+
accountId,
|
|
159
|
+
msgtype: preview.msgtype,
|
|
160
|
+
includeMentions: preview.includeMentions,
|
|
161
|
+
live: false,
|
|
162
|
+
});
|
|
163
|
+
log?.(`draft-stream: finalized ${currentEventId} (MSC4357 stream ended)`);
|
|
164
|
+
return true;
|
|
165
|
+
} catch (err) {
|
|
166
|
+
log?.(`draft-stream: finalize edit failed: ${String(err)}`);
|
|
167
|
+
// If the finalize edit fails, the live marker remains on the last
|
|
168
|
+
// successful edit. Flag the stream so callers can fall back to
|
|
169
|
+
// normal final delivery or redaction instead of leaving the message
|
|
170
|
+
// stuck in a "still streaming" state for MSC4357 clients.
|
|
171
|
+
finalizeInPlaceBlocked = true;
|
|
172
|
+
return false;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return true;
|
|
176
|
+
};
|
|
177
|
+
|
|
178
|
+
const stop = async (): Promise<string | undefined> => {
|
|
179
|
+
// Flush before marking stopped so the loop can drain pending text.
|
|
180
|
+
await loop.flush();
|
|
181
|
+
stopped = true;
|
|
182
|
+
return currentEventId;
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
const discardPending = async (): Promise<void> => {
|
|
186
|
+
stopped = true;
|
|
187
|
+
loop.stop();
|
|
188
|
+
await loop.waitForInFlight();
|
|
189
|
+
};
|
|
190
|
+
|
|
191
|
+
const reset = (): void => {
|
|
192
|
+
// Clear reply context unless preserveReplyId is set (replyToMode "all"),
|
|
193
|
+
// in which case subsequent blocks should keep replying to the original.
|
|
194
|
+
replyToId = params.preserveReplyId ? params.replyToId : undefined;
|
|
195
|
+
currentEventId = undefined;
|
|
196
|
+
lastSentText = "";
|
|
197
|
+
stopped = false;
|
|
198
|
+
sendFailed = false;
|
|
199
|
+
finalizeInPlaceBlocked = false;
|
|
200
|
+
liveFinalized = false;
|
|
201
|
+
loop.resetPending();
|
|
202
|
+
loop.resetThrottleWindow();
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
return {
|
|
206
|
+
update: (text: string) => {
|
|
207
|
+
if (stopped) {
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
loop.update(text);
|
|
211
|
+
},
|
|
212
|
+
flush: loop.flush,
|
|
213
|
+
stop,
|
|
214
|
+
discardPending,
|
|
215
|
+
finalizeLive,
|
|
216
|
+
reset,
|
|
217
|
+
eventId: () => currentEventId,
|
|
218
|
+
matchesPreparedText: (text: string) =>
|
|
219
|
+
prepareMatrixSingleText(text, {
|
|
220
|
+
cfg,
|
|
221
|
+
accountId,
|
|
222
|
+
}).trimmedText === lastSentText,
|
|
223
|
+
mustDeliverFinalNormally: () => sendFailed || finalizeInPlaceBlocked,
|
|
224
|
+
};
|
|
225
|
+
}
|