@kodelyth/matrix 2026.5.39 → 2026.6.1

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.
Files changed (117) hide show
  1. package/dist/account-selection-Y50DNJ2l.js +158 -0
  2. package/dist/active-client-CmFdvPdO.js +20 -0
  3. package/dist/api.js +12 -0
  4. package/dist/approval-handler.runtime-BIi4fL0R.js +377 -0
  5. package/dist/approval-ids-BGHK7PnZ.js +7 -0
  6. package/dist/approval-reaction-auth-CL0-nCNV.js +27 -0
  7. package/dist/approval-reactions-nDm2x-K5.js +162 -0
  8. package/dist/async-lock-SsmtFXtt.js +19 -0
  9. package/dist/auth-presence.js +26 -0
  10. package/dist/backup-health-3BHbHxyd.js +60 -0
  11. package/dist/channel-C0kCyTNB.js +1380 -0
  12. package/dist/channel-plugin-api.js +2 -0
  13. package/dist/channel.runtime-CdrdEN-0.js +250 -0
  14. package/dist/cli-FtY6Nuzw.js +1338 -0
  15. package/dist/cli-metadata-Dkwua7CB.js +22 -0
  16. package/dist/cli-metadata.js +2 -0
  17. package/dist/client-BnohYygh.js +25 -0
  18. package/dist/client-PhrTwuC4.js +30 -0
  19. package/dist/client-bootstrap-Mcj8ChJ5.js +114 -0
  20. package/dist/config-paths-DVvt6vM3.js +114 -0
  21. package/dist/config-schema-BMGOlhdI.js +308 -0
  22. package/dist/config-secret-input.runtime-Dv_4Br_f.js +2 -0
  23. package/dist/contract-api.js +8 -0
  24. package/dist/create-client-J0htTaRj.js +64 -0
  25. package/dist/credentials-B7GsBbgQ.js +56 -0
  26. package/dist/credentials-read-8fE4qoWs.js +112 -0
  27. package/dist/credentials-write.runtime-BibplB4Y.js +17 -0
  28. package/dist/crypto-node.runtime-D9qxgRPa.js +12 -0
  29. package/dist/crypto-runtime-1pKW4O2F.js +1214 -0
  30. package/dist/deps-DVpDS81G.js +208 -0
  31. package/dist/device-health-Ct2wDSPG.js +16 -0
  32. package/dist/directory-live-i3T8uORc.js +150 -0
  33. package/dist/doctor-contract-BLzYHl_9.js +246 -0
  34. package/dist/doctor-contract-api.js +2 -0
  35. package/dist/doctor-diR5gE7D.js +153 -0
  36. package/dist/draft-stream-HpPJ_VJt.js +143 -0
  37. package/dist/encryption-guidance-BNEgckrZ.js +15 -0
  38. package/dist/env-auth-UFiTGkDM.js +63 -0
  39. package/dist/env-vars-EQKQv-FE.js +63 -0
  40. package/dist/errors-BETj3zr9.js +17 -0
  41. package/dist/exec-approval-resolver-BxPorU_t.js +15 -0
  42. package/dist/helper-api.js +4 -0
  43. package/dist/http-client-DoQgbQsU.js +331 -0
  44. package/dist/index.js +46 -0
  45. package/dist/legacy-crypto-inspector-zK0hDCbt.js +41 -0
  46. package/dist/legacy-crypto-restore-DSFIXuDo.js +85 -0
  47. package/dist/logging-Df7aPD1z.js +99 -0
  48. package/dist/matrix-migration.runtime-BNoT1Prt.js +525 -0
  49. package/dist/media-text-ZhGA8Pcs.js +146 -0
  50. package/dist/messages-CRA9WGg0.js +140 -0
  51. package/dist/migration-snapshot-backup-BR-xD7Ew.js +69 -0
  52. package/dist/migration-snapshot.runtime-BLcy_Nvw.js +2 -0
  53. package/dist/monitor-DQm7_13y.js +4331 -0
  54. package/dist/plugin-entry.handlers.runtime.js +51 -0
  55. package/dist/probe.runtime-CjJS53Kz.js +3 -0
  56. package/dist/profile-update-DqkPgZ1P.js +68 -0
  57. package/dist/reaction-common-CmVLzP-u.js +71 -0
  58. package/dist/reaction-events-D0nUJuZV.js +121 -0
  59. package/dist/record-shared-DGvSFn5M.js +2 -0
  60. package/dist/resolve-targets-ChECUzD2.js +140 -0
  61. package/dist/resolver.runtime-hdY3n0GO.js +5 -0
  62. package/dist/rolldown-runtime-DUslC3ob.js +14 -0
  63. package/dist/route-xRKj_ESW.js +161 -0
  64. package/dist/runtime-B-Fyrmxo.js +8 -0
  65. package/dist/runtime-api-BYXXkxq2.js +24 -0
  66. package/dist/runtime-api.js +25 -0
  67. package/dist/runtime-heavy-api.js +3 -0
  68. package/dist/runtime-lwTSy9Yt.js +6 -0
  69. package/dist/runtime-setter-api.js +2 -0
  70. package/dist/sdk-Jhq7mLtD.js +1704 -0
  71. package/dist/secret-contract-DEMcDsjl.js +120 -0
  72. package/dist/secret-contract-api.js +2 -0
  73. package/dist/send-CJunc6QM.js +1517 -0
  74. package/dist/setup-bootstrap-rJ0qZWPe.js +62 -0
  75. package/dist/setup-core-BEYoXF3J.js +677 -0
  76. package/dist/setup-entry.js +19 -0
  77. package/dist/setup-plugin-api.js +43 -0
  78. package/dist/setup-surface-c28ON6jq.js +537 -0
  79. package/dist/shared-D6MFMnpG.js +642 -0
  80. package/dist/startup-abort-B2J3MU_h.js +109 -0
  81. package/dist/startup-verification-CkD4Cwce.js +132 -0
  82. package/dist/storage-nyO0DOFE.js +281 -0
  83. package/dist/storage-paths-BTAketfg.js +52 -0
  84. package/dist/subagent-hooks-api-Dr_xnMRG.js +170 -0
  85. package/dist/subagent-hooks-api.js +2 -0
  86. package/dist/sync-state-Bx0gPaGA.js +12 -0
  87. package/dist/target-ids-Bsazo8si.js +77 -0
  88. package/dist/test-api.js +4 -0
  89. package/dist/thread-binding-api-IGU0-L70.js +17 -0
  90. package/dist/thread-binding-api.js +2 -0
  91. package/dist/thread-bindings-FjAZmDUP.js +352 -0
  92. package/dist/thread-bindings-runtime.js +2 -0
  93. package/dist/thread-bindings-shared-fvfP7jVs.js +97 -0
  94. package/dist/timeout-abort-signal-DpSHDHhR.js +2 -0
  95. package/dist/tool-actions.runtime-Cbo7YcYZ.js +532 -0
  96. package/dist/url-validation-DlrXNjAE.js +36 -0
  97. package/dist/verification-7tDPRpJU.js +345 -0
  98. package/package.json +19 -7
  99. package/api.js +0 -7
  100. package/auth-presence.js +0 -7
  101. package/channel-plugin-api.js +0 -7
  102. package/cli-metadata.js +0 -7
  103. package/contract-api.js +0 -7
  104. package/doctor-contract-api.js +0 -7
  105. package/helper-api.js +0 -7
  106. package/index.js +0 -7
  107. package/plugin-entry.handlers.runtime.js +0 -7
  108. package/runtime-api.js +0 -7
  109. package/runtime-heavy-api.js +0 -7
  110. package/runtime-setter-api.js +0 -7
  111. package/secret-contract-api.js +0 -7
  112. package/setup-entry.js +0 -7
  113. package/setup-plugin-api.js +0 -7
  114. package/subagent-hooks-api.js +0 -7
  115. package/test-api.js +0 -7
  116. package/thread-binding-api.js +0 -7
  117. package/thread-bindings-runtime.js +0 -7
@@ -0,0 +1,158 @@
1
+ import { n as listMatrixEnvAccountIds, t as getMatrixScopedEnvVarNames } from "./env-vars-EQKQv-FE.js";
2
+ import { t as isRecord } from "./record-shared-DGvSFn5M.js";
3
+ import { DEFAULT_ACCOUNT_ID, normalizeAccountId, normalizeOptionalAccountId } from "klaw/plugin-sdk/account-id";
4
+ import { normalizeOptionalString } from "klaw/plugin-sdk/string-coerce-runtime";
5
+ import { listCombinedAccountIds, listConfiguredAccountIds, resolveListedDefaultAccountId, resolveNormalizedAccountEntry } from "klaw/plugin-sdk/account-core";
6
+ import { hasConfiguredSecretInput } from "klaw/plugin-sdk/secret-input-runtime";
7
+ //#region extensions/matrix/src/auth-precedence.ts
8
+ const MATRIX_DEFAULT_ACCOUNT_AUTH_ONLY_FIELDS = new Set([
9
+ "userId",
10
+ "accessToken",
11
+ "password",
12
+ "deviceId"
13
+ ]);
14
+ function resolveMatrixStringSourceValue(value) {
15
+ return typeof value === "string" ? value : "";
16
+ }
17
+ function shouldAllowBaseAuthFallback(accountId, field) {
18
+ return normalizeAccountId(accountId) === DEFAULT_ACCOUNT_ID || !MATRIX_DEFAULT_ACCOUNT_AUTH_ONLY_FIELDS.has(field);
19
+ }
20
+ function resolveMatrixAccountStringValues(params) {
21
+ const fields = [
22
+ "homeserver",
23
+ "userId",
24
+ "accessToken",
25
+ "password",
26
+ "deviceId",
27
+ "deviceName"
28
+ ];
29
+ const resolved = {};
30
+ for (const field of fields) resolved[field] = resolveMatrixStringSourceValue(params.account?.[field]) || resolveMatrixStringSourceValue(params.scopedEnv?.[field]) || (shouldAllowBaseAuthFallback(params.accountId, field) ? resolveMatrixStringSourceValue(params.channel?.[field]) || resolveMatrixStringSourceValue(params.globalEnv?.[field]) : "");
31
+ return resolved;
32
+ }
33
+ //#endregion
34
+ //#region extensions/matrix/src/account-selection.ts
35
+ function readConfiguredMatrixString(value) {
36
+ return normalizeOptionalString(value) ?? "";
37
+ }
38
+ function readConfiguredMatrixSecretSource(value) {
39
+ return hasConfiguredSecretInput(value) ? "configured" : "";
40
+ }
41
+ function resolveMatrixChannelStringSources(entry) {
42
+ if (!entry) return {};
43
+ return {
44
+ homeserver: readConfiguredMatrixString(entry.homeserver),
45
+ userId: readConfiguredMatrixString(entry.userId),
46
+ accessToken: readConfiguredMatrixSecretSource(entry.accessToken),
47
+ password: readConfiguredMatrixSecretSource(entry.password),
48
+ deviceId: readConfiguredMatrixString(entry.deviceId),
49
+ deviceName: readConfiguredMatrixString(entry.deviceName)
50
+ };
51
+ }
52
+ function readEnvMatrixString(env, key) {
53
+ return normalizeOptionalString(env[key]) ?? "";
54
+ }
55
+ function resolveScopedMatrixEnvStringSources(accountId, env) {
56
+ const keys = getMatrixScopedEnvVarNames(accountId);
57
+ return {
58
+ homeserver: readEnvMatrixString(env, keys.homeserver),
59
+ userId: readEnvMatrixString(env, keys.userId),
60
+ accessToken: readEnvMatrixString(env, keys.accessToken),
61
+ password: readEnvMatrixString(env, keys.password),
62
+ deviceId: readEnvMatrixString(env, keys.deviceId),
63
+ deviceName: readEnvMatrixString(env, keys.deviceName)
64
+ };
65
+ }
66
+ function resolveGlobalMatrixEnvStringSources(env) {
67
+ return {
68
+ homeserver: readEnvMatrixString(env, "MATRIX_HOMESERVER"),
69
+ userId: readEnvMatrixString(env, "MATRIX_USER_ID"),
70
+ accessToken: readEnvMatrixString(env, "MATRIX_ACCESS_TOKEN"),
71
+ password: readEnvMatrixString(env, "MATRIX_PASSWORD"),
72
+ deviceId: readEnvMatrixString(env, "MATRIX_DEVICE_ID"),
73
+ deviceName: readEnvMatrixString(env, "MATRIX_DEVICE_NAME")
74
+ };
75
+ }
76
+ function hasUsableResolvedMatrixAuth(values) {
77
+ return Boolean(values.homeserver && (values.accessToken || values.userId));
78
+ }
79
+ function hasFreshResolvedMatrixAuth(values) {
80
+ return Boolean(values.homeserver && (values.accessToken || values.userId && values.password));
81
+ }
82
+ function resolveEffectiveMatrixAccountSources(params) {
83
+ const normalizedAccountId = normalizeAccountId(params.accountId);
84
+ return resolveMatrixAccountStringValues({
85
+ accountId: normalizedAccountId,
86
+ scopedEnv: resolveScopedMatrixEnvStringSources(normalizedAccountId, params.env),
87
+ channel: resolveMatrixChannelStringSources(params.channel),
88
+ globalEnv: resolveGlobalMatrixEnvStringSources(params.env)
89
+ });
90
+ }
91
+ function hasUsableEffectiveMatrixAccountSource(params) {
92
+ return hasUsableResolvedMatrixAuth(resolveEffectiveMatrixAccountSources(params));
93
+ }
94
+ function hasFreshEffectiveMatrixAccountSource(params) {
95
+ return hasFreshResolvedMatrixAuth(resolveEffectiveMatrixAccountSources(params));
96
+ }
97
+ function hasConfiguredDefaultMatrixAccountSource(params) {
98
+ return hasFreshEffectiveMatrixAccountSource({
99
+ channel: params.channel,
100
+ accountId: DEFAULT_ACCOUNT_ID,
101
+ env: params.env
102
+ });
103
+ }
104
+ function resolveMatrixChannelConfig(cfg) {
105
+ return isRecord(cfg.channels?.matrix) ? cfg.channels.matrix : null;
106
+ }
107
+ function findMatrixAccountEntry(cfg, accountId) {
108
+ const channel = resolveMatrixChannelConfig(cfg);
109
+ if (!channel) return null;
110
+ const accounts = isRecord(channel.accounts) ? channel.accounts : null;
111
+ if (!accounts) return null;
112
+ const entry = resolveNormalizedAccountEntry(accounts, accountId, normalizeAccountId);
113
+ return isRecord(entry) ? entry : null;
114
+ }
115
+ function resolveConfiguredMatrixAccountIds(cfg, env = process.env) {
116
+ const channel = resolveMatrixChannelConfig(cfg);
117
+ const configuredAccountIds = listConfiguredAccountIds({
118
+ accounts: channel && isRecord(channel.accounts) ? channel.accounts : void 0,
119
+ normalizeAccountId
120
+ });
121
+ if (hasConfiguredDefaultMatrixAccountSource({
122
+ channel,
123
+ env
124
+ })) configuredAccountIds.push(DEFAULT_ACCOUNT_ID);
125
+ return listCombinedAccountIds({
126
+ configuredAccountIds,
127
+ additionalAccountIds: listMatrixEnvAccountIds(env).filter((accountId) => normalizeAccountId(accountId) === DEFAULT_ACCOUNT_ID ? hasConfiguredDefaultMatrixAccountSource({
128
+ channel,
129
+ env
130
+ }) : hasUsableEffectiveMatrixAccountSource({
131
+ channel,
132
+ accountId,
133
+ env
134
+ })),
135
+ fallbackAccountIdWhenEmpty: channel ? DEFAULT_ACCOUNT_ID : void 0
136
+ });
137
+ }
138
+ function resolveMatrixDefaultOrOnlyAccountId(cfg, env = process.env) {
139
+ const channel = resolveMatrixChannelConfig(cfg);
140
+ if (!channel) return DEFAULT_ACCOUNT_ID;
141
+ const configuredDefault = normalizeOptionalAccountId(typeof channel.defaultAccount === "string" ? channel.defaultAccount : void 0);
142
+ return resolveListedDefaultAccountId({
143
+ accountIds: resolveConfiguredMatrixAccountIds(cfg, env),
144
+ configuredDefaultAccountId: configuredDefault,
145
+ ambiguousFallbackAccountId: DEFAULT_ACCOUNT_ID
146
+ });
147
+ }
148
+ function requiresExplicitMatrixDefaultAccount(cfg, env = process.env) {
149
+ const channel = resolveMatrixChannelConfig(cfg);
150
+ if (!channel) return false;
151
+ const configuredAccountIds = resolveConfiguredMatrixAccountIds(cfg, env);
152
+ if (configuredAccountIds.length <= 1) return false;
153
+ if (configuredAccountIds.includes(DEFAULT_ACCOUNT_ID)) return false;
154
+ const configuredDefault = normalizeOptionalAccountId(typeof channel.defaultAccount === "string" ? channel.defaultAccount : void 0);
155
+ return !(configuredDefault && configuredAccountIds.includes(configuredDefault));
156
+ }
157
+ //#endregion
158
+ export { resolveMatrixDefaultOrOnlyAccountId as a, resolveMatrixChannelConfig as i, requiresExplicitMatrixDefaultAccount as n, resolveMatrixAccountStringValues as o, resolveConfiguredMatrixAccountIds as r, findMatrixAccountEntry as t };
@@ -0,0 +1,20 @@
1
+ import { DEFAULT_ACCOUNT_ID, normalizeAccountId } from "klaw/plugin-sdk/account-id";
2
+ //#region extensions/matrix/src/matrix/active-client.ts
3
+ const activeClients = /* @__PURE__ */ new Map();
4
+ function resolveAccountKey(accountId) {
5
+ return normalizeAccountId(accountId) || DEFAULT_ACCOUNT_ID;
6
+ }
7
+ function setActiveMatrixClient(client, accountId) {
8
+ const key = resolveAccountKey(accountId);
9
+ if (!client) {
10
+ activeClients.delete(key);
11
+ return;
12
+ }
13
+ activeClients.set(key, client);
14
+ }
15
+ function getActiveMatrixClient(accountId) {
16
+ const key = resolveAccountKey(accountId);
17
+ return activeClients.get(key) ?? null;
18
+ }
19
+ //#endregion
20
+ export { setActiveMatrixClient as n, getActiveMatrixClient as t };
package/dist/api.js ADDED
@@ -0,0 +1,12 @@
1
+ import { d as setMatrixThreadBindingIdleTimeoutBySessionKey, n as getMatrixThreadBindingManager, p as setMatrixThreadBindingMaxAgeBySessionKey, s as resetMatrixThreadBindingsForTests } from "./thread-bindings-shared-fvfP7jVs.js";
2
+ import { a as resolveMatrixDefaultOrOnlyAccountId, i as resolveMatrixChannelConfig, n as requiresExplicitMatrixDefaultAccount, r as resolveConfiguredMatrixAccountIds, t as findMatrixAccountEntry } from "./account-selection-Y50DNJ2l.js";
3
+ import { n as listMatrixEnvAccountIds, r as resolveMatrixEnvAccountToken, t as getMatrixScopedEnvVarNames } from "./env-vars-EQKQv-FE.js";
4
+ import { a as resolveMatrixCredentialsPath, c as resolveMatrixLegacyFlatStoreRoot, i as resolveMatrixCredentialsFilename, l as sanitizeMatrixPathSegment, n as resolveMatrixAccountStorageRoot, o as resolveMatrixHomeserverKey, r as resolveMatrixCredentialsDir, s as resolveMatrixLegacyFlatStoragePaths, t as hashMatrixAccessToken } from "./storage-paths-BTAketfg.js";
5
+ import { n as matrixSetupAdapter, t as createMatrixSetupWizardProxy } from "./setup-core-BEYoXF3J.js";
6
+ import { t as matrixPlugin } from "./channel-C0kCyTNB.js";
7
+ import { n as matrixOnboardingAdapter } from "./setup-surface-c28ON6jq.js";
8
+ import { t as createMatrixThreadBindingManager } from "./thread-bindings-FjAZmDUP.js";
9
+ //#region extensions/matrix/api.ts
10
+ const matrixSessionBindingAdapterChannels = ["matrix"];
11
+ //#endregion
12
+ export { createMatrixSetupWizardProxy, createMatrixThreadBindingManager, findMatrixAccountEntry, getMatrixScopedEnvVarNames, getMatrixThreadBindingManager, hashMatrixAccessToken, listMatrixEnvAccountIds, matrixOnboardingAdapter, matrixOnboardingAdapter as matrixSetupWizard, matrixPlugin, matrixSessionBindingAdapterChannels, matrixSetupAdapter, requiresExplicitMatrixDefaultAccount, resetMatrixThreadBindingsForTests, resolveConfiguredMatrixAccountIds, resolveMatrixAccountStorageRoot, resolveMatrixChannelConfig, resolveMatrixCredentialsDir, resolveMatrixCredentialsFilename, resolveMatrixCredentialsPath, resolveMatrixDefaultOrOnlyAccountId, resolveMatrixEnvAccountToken, resolveMatrixHomeserverKey, resolveMatrixLegacyFlatStoragePaths, resolveMatrixLegacyFlatStoreRoot, sanitizeMatrixPathSegment, setMatrixThreadBindingIdleTimeoutBySessionKey, setMatrixThreadBindingMaxAgeBySessionKey };
@@ -0,0 +1,377 @@
1
+ import { a as resolveMatrixTargetIdentity } from "./target-ids-Bsazo8si.js";
2
+ import { g as resolveMatrixAccount } from "./setup-core-BEYoXF3J.js";
3
+ import { _ as shouldHandleMatrixApprovalRequest, g as isMatrixAnyApprovalClientEnabled } from "./channel-C0kCyTNB.js";
4
+ import { a as sendMessageMatrix, i as reactMatrixMessage, p as repairMatrixDirectRooms, s as sendSingleTextMessageMatrix } from "./send-CJunc6QM.js";
5
+ import { a as unregisterMatrixApprovalReactionTarget, n as listMatrixApprovalReactionBindings, r as registerMatrixApprovalReactionTarget, t as buildMatrixApprovalReactionHint } from "./approval-reactions-nDm2x-K5.js";
6
+ import { n as editMatrixMessage, t as deleteMatrixMessage } from "./messages-CRA9WGg0.js";
7
+ import { listMessageReceiptPlatformIds, resolveMessageReceiptPrimaryId } from "klaw/plugin-sdk/channel-message";
8
+ import { buildChannelApprovalNativeTargetKey } from "klaw/plugin-sdk/approval-native-runtime";
9
+ import { setTimeout } from "node:timers/promises";
10
+ import { createChannelApprovalNativeRuntimeAdapter } from "klaw/plugin-sdk/approval-handler-runtime";
11
+ import { buildExecApprovalPendingReplyPayload, buildPluginApprovalPendingReplyPayload } from "klaw/plugin-sdk/approval-reply-runtime";
12
+ import { buildPluginApprovalResolvedReplyPayload } from "klaw/plugin-sdk/approval-runtime";
13
+ //#region extensions/matrix/src/approval-handler.runtime.ts
14
+ const MATRIX_APPROVAL_METADATA_KEY = "com.klaw.approval";
15
+ const MATRIX_APPROVAL_DELIVERY_ATTEMPTS = 3;
16
+ const MATRIX_APPROVAL_DELIVERY_RETRY_DELAY_MS = 250;
17
+ function resolveHandlerContext(params) {
18
+ const context = params.context;
19
+ const accountId = params.accountId?.trim() || "";
20
+ if (!context?.client || !accountId) return null;
21
+ return {
22
+ accountId,
23
+ context
24
+ };
25
+ }
26
+ function normalizePendingMessageIds(entry) {
27
+ return Array.from(new Set(entry.platformMessageIds.map((messageId) => messageId.trim()).filter(Boolean)));
28
+ }
29
+ function normalizeReactionTargetRef(params) {
30
+ const roomId = params.roomId.trim();
31
+ const eventId = params.eventId.trim();
32
+ if (!roomId || !eventId) return null;
33
+ return {
34
+ roomId,
35
+ eventId
36
+ };
37
+ }
38
+ function normalizeThreadId(value) {
39
+ return (value == null ? "" : String(value).trim()) || void 0;
40
+ }
41
+ function isSingleMatrixMessageLimitError(error) {
42
+ return error instanceof Error && error.message.includes("Matrix single-message text exceeds limit");
43
+ }
44
+ async function retryMatrixApprovalDelivery(operation, params = {}) {
45
+ let lastError;
46
+ for (let attempt = 1; attempt <= MATRIX_APPROVAL_DELIVERY_ATTEMPTS; attempt += 1) try {
47
+ return await operation();
48
+ } catch (error) {
49
+ lastError = error;
50
+ if (attempt === MATRIX_APPROVAL_DELIVERY_ATTEMPTS || params.shouldRetry?.(error) === false) break;
51
+ await setTimeout(MATRIX_APPROVAL_DELIVERY_RETRY_DELAY_MS * attempt);
52
+ }
53
+ throw lastError;
54
+ }
55
+ async function prepareTarget(params) {
56
+ const resolved = resolveHandlerContext(params);
57
+ if (!resolved) return null;
58
+ const target = resolveMatrixTargetIdentity(params.rawTarget.to);
59
+ if (!target) return null;
60
+ const threadId = normalizeThreadId(params.rawTarget.threadId);
61
+ if (target.kind === "user") {
62
+ const account = resolveMatrixAccount({
63
+ cfg: params.cfg,
64
+ accountId: resolved.accountId
65
+ });
66
+ const repairDirectRooms = resolved.context.deps?.repairDirectRooms ?? repairMatrixDirectRooms;
67
+ const repaired = await retryMatrixApprovalDelivery(async () => await repairDirectRooms({
68
+ client: resolved.context.client,
69
+ remoteUserId: target.id,
70
+ encrypted: account.config.encryption === true
71
+ }));
72
+ if (!repaired.activeRoomId) return null;
73
+ return {
74
+ to: `room:${repaired.activeRoomId}`,
75
+ roomId: repaired.activeRoomId,
76
+ threadId
77
+ };
78
+ }
79
+ return {
80
+ to: `room:${target.id}`,
81
+ roomId: target.id,
82
+ threadId
83
+ };
84
+ }
85
+ function buildMatrixApprovalMetadata(params) {
86
+ const base = {
87
+ version: 1,
88
+ type: "approval.request",
89
+ id: params.view.approvalId,
90
+ state: "pending",
91
+ kind: params.view.approvalKind,
92
+ phase: params.view.phase,
93
+ title: params.view.title,
94
+ expiresAtMs: params.view.expiresAtMs,
95
+ metadata: params.view.metadata,
96
+ allowedDecisions: Array.from(params.allowedDecisions),
97
+ actions: params.view.actions.map((action) => ({
98
+ decision: action.decision,
99
+ label: action.label,
100
+ style: action.style,
101
+ command: action.command
102
+ })),
103
+ ...params.view.description != null ? { description: params.view.description } : {}
104
+ };
105
+ if (params.view.approvalKind === "plugin") return {
106
+ ...base,
107
+ kind: "plugin",
108
+ severity: params.view.severity,
109
+ ...params.view.agentId != null ? { agentId: params.view.agentId } : {},
110
+ ...params.view.pluginId != null ? { pluginId: params.view.pluginId } : {},
111
+ ...params.view.toolName != null ? { toolName: params.view.toolName } : {}
112
+ };
113
+ return {
114
+ ...base,
115
+ kind: "exec",
116
+ commandText: params.view.commandText,
117
+ ...params.view.ask != null ? { ask: params.view.ask } : {},
118
+ ...params.view.agentId != null ? { agentId: params.view.agentId } : {},
119
+ ...params.view.commandPreview != null ? { commandPreview: params.view.commandPreview } : {},
120
+ ...params.view.cwd != null ? { cwd: params.view.cwd } : {},
121
+ ...params.view.envKeys != null ? { envKeys: params.view.envKeys } : {},
122
+ ...params.view.host != null ? { host: params.view.host } : {},
123
+ ...params.view.nodeId != null ? { nodeId: params.view.nodeId } : {},
124
+ ...params.view.sessionKey != null ? { sessionKey: params.view.sessionKey } : {}
125
+ };
126
+ }
127
+ function buildPendingApprovalContent(params) {
128
+ const allowedDecisions = params.view.actions.map((action) => action.decision);
129
+ const payload = params.view.approvalKind === "plugin" ? buildPluginApprovalPendingReplyPayload({
130
+ request: {
131
+ id: params.view.approvalId,
132
+ request: {
133
+ title: params.view.title,
134
+ description: params.view.description ?? "",
135
+ severity: params.view.severity,
136
+ toolName: params.view.toolName ?? void 0,
137
+ pluginId: params.view.pluginId ?? void 0,
138
+ agentId: params.view.agentId ?? void 0
139
+ },
140
+ createdAtMs: 0,
141
+ expiresAtMs: params.view.expiresAtMs
142
+ },
143
+ nowMs: params.nowMs,
144
+ allowedDecisions
145
+ }) : buildExecApprovalPendingReplyPayload({
146
+ approvalId: params.view.approvalId,
147
+ approvalSlug: params.view.approvalId.slice(0, 8),
148
+ approvalCommandId: params.view.approvalId,
149
+ ask: params.view.ask ?? void 0,
150
+ agentId: params.view.agentId ?? void 0,
151
+ allowedDecisions,
152
+ command: params.view.commandText,
153
+ cwd: params.view.cwd ?? void 0,
154
+ host: params.view.host === "node" ? "node" : "gateway",
155
+ nodeId: params.view.nodeId ?? void 0,
156
+ sessionKey: params.view.sessionKey ?? void 0,
157
+ expiresAtMs: params.view.expiresAtMs,
158
+ nowMs: params.nowMs
159
+ });
160
+ const hint = buildMatrixApprovalReactionHint(allowedDecisions);
161
+ const text = payload.text ?? "";
162
+ return {
163
+ approvalId: params.view.approvalId,
164
+ text: hint ? text ? `${hint}\n\n${text}` : hint : text,
165
+ allowedDecisions,
166
+ extraContent: { [MATRIX_APPROVAL_METADATA_KEY]: buildMatrixApprovalMetadata({
167
+ view: params.view,
168
+ allowedDecisions
169
+ }) }
170
+ };
171
+ }
172
+ function buildResolvedApprovalText(view) {
173
+ if (view.approvalKind === "plugin") return buildPluginApprovalResolvedReplyPayload({ resolved: {
174
+ id: view.approvalId,
175
+ decision: view.decision,
176
+ resolvedBy: view.resolvedBy ?? void 0,
177
+ ts: 0
178
+ } }).text ?? "";
179
+ return [
180
+ `Exec approval: ${view.decision === "allow-once" ? "Allowed once" : view.decision === "allow-always" ? "Allowed always" : "Denied"}`,
181
+ "",
182
+ "Command",
183
+ buildMarkdownCodeBlock(view.commandText)
184
+ ].join("\n");
185
+ }
186
+ function buildMarkdownCodeBlock(text) {
187
+ const longestFence = Math.max(...Array.from(text.matchAll(/`+/g), (match) => match[0].length), 0);
188
+ const fence = "`".repeat(Math.max(3, longestFence + 1));
189
+ return [
190
+ fence,
191
+ text,
192
+ fence
193
+ ].join("\n");
194
+ }
195
+ const matrixApprovalNativeRuntime = createChannelApprovalNativeRuntimeAdapter({
196
+ eventKinds: ["exec", "plugin"],
197
+ availability: {
198
+ isConfigured: ({ cfg, accountId, context }) => {
199
+ const resolved = resolveHandlerContext({
200
+ cfg,
201
+ accountId,
202
+ context
203
+ });
204
+ if (!resolved) return false;
205
+ return isMatrixAnyApprovalClientEnabled({
206
+ cfg,
207
+ accountId: resolved.accountId
208
+ });
209
+ },
210
+ shouldHandle: ({ cfg, accountId, request, context }) => {
211
+ const resolved = resolveHandlerContext({
212
+ cfg,
213
+ accountId,
214
+ context
215
+ });
216
+ if (!resolved) return false;
217
+ return shouldHandleMatrixApprovalRequest({
218
+ cfg,
219
+ accountId: resolved.accountId,
220
+ request
221
+ });
222
+ }
223
+ },
224
+ presentation: {
225
+ buildPendingPayload: ({ view, nowMs }) => buildPendingApprovalContent({
226
+ view,
227
+ nowMs
228
+ }),
229
+ buildResolvedResult: ({ view }) => ({
230
+ kind: "update",
231
+ payload: buildResolvedApprovalText(view)
232
+ }),
233
+ buildExpiredResult: () => ({ kind: "delete" })
234
+ },
235
+ transport: {
236
+ prepareTarget: ({ cfg, accountId, context, plannedTarget }) => {
237
+ return prepareTarget({
238
+ cfg,
239
+ accountId,
240
+ context,
241
+ rawTarget: plannedTarget.target
242
+ }).then((preparedTarget) => preparedTarget ? {
243
+ dedupeKey: buildChannelApprovalNativeTargetKey({
244
+ to: preparedTarget.roomId,
245
+ threadId: preparedTarget.threadId
246
+ }),
247
+ target: preparedTarget
248
+ } : null);
249
+ },
250
+ deliverPending: async ({ cfg, accountId, context, preparedTarget, pendingPayload, view }) => {
251
+ const resolved = resolveHandlerContext({
252
+ cfg,
253
+ accountId,
254
+ context
255
+ });
256
+ if (!resolved) return null;
257
+ const sendSingleTextMessage = resolved.context.deps?.sendSingleTextMessage ?? sendSingleTextMessageMatrix;
258
+ const reactMessage = resolved.context.deps?.reactMessage ?? reactMatrixMessage;
259
+ let result;
260
+ try {
261
+ result = await retryMatrixApprovalDelivery(async () => await sendSingleTextMessage(preparedTarget.to, pendingPayload.text, {
262
+ cfg,
263
+ accountId: resolved.accountId,
264
+ client: resolved.context.client,
265
+ threadId: preparedTarget.threadId,
266
+ extraContent: pendingPayload.extraContent
267
+ }), { shouldRetry: (error) => !isSingleMatrixMessageLimitError(error) });
268
+ } catch (error) {
269
+ if (!isSingleMatrixMessageLimitError(error)) throw error;
270
+ const sendMessage = resolved.context.deps?.sendMessage ?? sendMessageMatrix;
271
+ result = await retryMatrixApprovalDelivery(async () => await sendMessage(preparedTarget.to, pendingPayload.text, {
272
+ cfg,
273
+ accountId: resolved.accountId,
274
+ client: resolved.context.client,
275
+ threadId: preparedTarget.threadId,
276
+ extraContent: pendingPayload.extraContent
277
+ }));
278
+ }
279
+ const receiptMessageIds = listMessageReceiptPlatformIds(result.receipt);
280
+ const platformMessageIds = receiptMessageIds.length ? receiptMessageIds : [result.messageId.trim()].filter(Boolean);
281
+ const reactionEventId = resolveMessageReceiptPrimaryId(result.receipt) || result.primaryMessageId?.trim() || platformMessageIds[0] || result.messageId.trim();
282
+ registerMatrixApprovalReactionTarget({
283
+ roomId: result.roomId,
284
+ eventId: reactionEventId,
285
+ approvalId: pendingPayload.approvalId,
286
+ allowedDecisions: pendingPayload.allowedDecisions,
287
+ ttlMs: view.expiresAtMs - Date.now()
288
+ });
289
+ await Promise.allSettled(listMatrixApprovalReactionBindings(pendingPayload.allowedDecisions).map(async ({ emoji }) => {
290
+ await reactMessage(result.roomId, reactionEventId, emoji, {
291
+ cfg,
292
+ accountId: resolved.accountId,
293
+ client: resolved.context.client
294
+ });
295
+ }));
296
+ return {
297
+ roomId: result.roomId,
298
+ platformMessageIds,
299
+ reactionEventId
300
+ };
301
+ },
302
+ updateEntry: async ({ cfg, accountId, context, entry, payload }) => {
303
+ const resolved = resolveHandlerContext({
304
+ cfg,
305
+ accountId,
306
+ context
307
+ });
308
+ if (!resolved) return;
309
+ const editMessage = resolved.context.deps?.editMessage ?? editMatrixMessage;
310
+ const deleteMessage = resolved.context.deps?.deleteMessage ?? deleteMatrixMessage;
311
+ const [primaryMessageId, ...staleMessageIds] = normalizePendingMessageIds(entry);
312
+ if (!primaryMessageId) return;
313
+ const text = payload;
314
+ await Promise.allSettled([editMessage(entry.roomId, primaryMessageId, text, {
315
+ cfg,
316
+ accountId: resolved.accountId,
317
+ client: resolved.context.client
318
+ }), ...staleMessageIds.map(async (messageId) => {
319
+ await deleteMessage(entry.roomId, messageId, {
320
+ cfg,
321
+ accountId: resolved.accountId,
322
+ client: resolved.context.client,
323
+ reason: "approval resolved"
324
+ });
325
+ })]);
326
+ },
327
+ deleteEntry: async ({ cfg, accountId, context, entry, phase }) => {
328
+ const resolved = resolveHandlerContext({
329
+ cfg,
330
+ accountId,
331
+ context
332
+ });
333
+ if (!resolved) return;
334
+ const deleteMessage = resolved.context.deps?.deleteMessage ?? deleteMatrixMessage;
335
+ await Promise.allSettled(normalizePendingMessageIds(entry).map(async (messageId) => {
336
+ await deleteMessage(entry.roomId, messageId, {
337
+ cfg,
338
+ accountId: resolved.accountId,
339
+ client: resolved.context.client,
340
+ reason: phase === "expired" ? "approval expired" : "approval resolved"
341
+ });
342
+ }));
343
+ }
344
+ },
345
+ interactions: {
346
+ bindPending: (params) => {
347
+ const target = normalizeReactionTargetRef({
348
+ roomId: params.entry.roomId,
349
+ eventId: params.entry.reactionEventId
350
+ });
351
+ if (!target) return null;
352
+ registerMatrixApprovalReactionTarget({
353
+ roomId: target.roomId,
354
+ eventId: target.eventId,
355
+ approvalId: params.pendingPayload.approvalId,
356
+ allowedDecisions: params.pendingPayload.allowedDecisions,
357
+ ttlMs: params.view.expiresAtMs - Date.now()
358
+ });
359
+ return target;
360
+ },
361
+ unbindPending: (params) => {
362
+ const target = normalizeReactionTargetRef(params.binding);
363
+ if (!target) return;
364
+ unregisterMatrixApprovalReactionTarget(target);
365
+ },
366
+ cancelDelivered: (params) => {
367
+ const target = normalizeReactionTargetRef({
368
+ roomId: params.entry.roomId,
369
+ eventId: params.entry.reactionEventId
370
+ });
371
+ if (!target) return;
372
+ unregisterMatrixApprovalReactionTarget(target);
373
+ }
374
+ }
375
+ });
376
+ //#endregion
377
+ export { matrixApprovalNativeRuntime };
@@ -0,0 +1,7 @@
1
+ import { a as normalizeMatrixUserId } from "./config-schema-BMGOlhdI.js";
2
+ //#region extensions/matrix/src/approval-ids.ts
3
+ function normalizeMatrixApproverId(value) {
4
+ return normalizeMatrixUserId(String(value)) || void 0;
5
+ }
6
+ //#endregion
7
+ export { normalizeMatrixApproverId as t };
@@ -0,0 +1,27 @@
1
+ import { g as resolveMatrixAccount } from "./setup-core-BEYoXF3J.js";
2
+ import { t as normalizeMatrixApproverId } from "./approval-ids-BGHK7PnZ.js";
3
+ import { resolveApprovalApprovers } from "klaw/plugin-sdk/approval-auth-runtime";
4
+ //#region extensions/matrix/src/approval-reaction-auth.ts
5
+ function normalizeMatrixExecApproverId(value) {
6
+ const normalized = normalizeMatrixApproverId(value);
7
+ return normalized === "*" ? void 0 : normalized;
8
+ }
9
+ function getMatrixApprovalReactionApprovers(params) {
10
+ const account = resolveMatrixAccount(params).config;
11
+ if (params.approvalKind === "plugin") return resolveApprovalApprovers({
12
+ allowFrom: account.dm?.allowFrom,
13
+ normalizeApprover: normalizeMatrixApproverId
14
+ });
15
+ return resolveApprovalApprovers({
16
+ explicit: account.execApprovals?.approvers,
17
+ allowFrom: account.dm?.allowFrom,
18
+ normalizeApprover: normalizeMatrixExecApproverId
19
+ });
20
+ }
21
+ function isMatrixApprovalReactionAuthorizedSender(params) {
22
+ const normalizedSenderId = params.senderId ? normalizeMatrixApproverId(params.senderId) : void 0;
23
+ if (!normalizedSenderId) return false;
24
+ return getMatrixApprovalReactionApprovers(params).includes(normalizedSenderId);
25
+ }
26
+ //#endregion
27
+ export { isMatrixApprovalReactionAuthorizedSender };