@dsh-ray/lark-channel 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +207 -2
- package/bin/dsh-lark-setup.js +37 -0
- package/bin/dsh-ray-setup.js +34 -0
- package/bin/dsh-supervised-growth-setup.js +34 -0
- package/cordis.patch.yml +23 -0
- package/docs/operations.md +133 -0
- package/docs/progress-security.md +125 -0
- package/docs/rsi-setup.md +216 -0
- package/docs/setup.md +358 -0
- package/docs/supervised-growth.md +95 -0
- package/lib/adapter.d.ts +185 -0
- package/lib/adapter.d.ts.map +1 -0
- package/lib/adapter.js +2072 -0
- package/lib/adapter.js.map +1 -0
- package/lib/answer-card.d.ts +40 -0
- package/lib/answer-card.d.ts.map +1 -0
- package/lib/answer-card.js +262 -0
- package/lib/answer-card.js.map +1 -0
- package/lib/approval.d.ts +26 -0
- package/lib/approval.d.ts.map +1 -0
- package/lib/approval.js +104 -0
- package/lib/approval.js.map +1 -0
- package/lib/business-cli-install.d.ts +9 -0
- package/lib/business-cli-install.d.ts.map +1 -0
- package/lib/business-cli-install.js +367 -0
- package/lib/business-cli-install.js.map +1 -0
- package/lib/business-environment.d.ts +2 -0
- package/lib/business-environment.d.ts.map +1 -0
- package/lib/business-environment.js +16 -0
- package/lib/business-environment.js.map +1 -0
- package/lib/business-skill.d.ts +32 -0
- package/lib/business-skill.d.ts.map +1 -0
- package/lib/business-skill.js +202 -0
- package/lib/business-skill.js.map +1 -0
- package/lib/command-card.d.ts +3 -0
- package/lib/command-card.d.ts.map +1 -0
- package/lib/command-card.js +480 -0
- package/lib/command-card.js.map +1 -0
- package/lib/config.d.ts +32 -0
- package/lib/config.d.ts.map +1 -0
- package/lib/config.js +115 -0
- package/lib/config.js.map +1 -0
- package/lib/group-thread.d.ts +20 -0
- package/lib/group-thread.d.ts.map +1 -0
- package/lib/group-thread.js +36 -0
- package/lib/group-thread.js.map +1 -0
- package/lib/index.d.ts +34 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +53 -0
- package/lib/index.js.map +1 -0
- package/lib/launchd-control.d.ts +24 -0
- package/lib/launchd-control.d.ts.map +1 -0
- package/lib/launchd-control.js +68 -0
- package/lib/launchd-control.js.map +1 -0
- package/lib/launchd-identity.d.ts +34 -0
- package/lib/launchd-identity.d.ts.map +1 -0
- package/lib/launchd-identity.js +184 -0
- package/lib/launchd-identity.js.map +1 -0
- package/lib/launchd-target-lock.d.ts +6 -0
- package/lib/launchd-target-lock.d.ts.map +1 -0
- package/lib/launchd-target-lock.js +48 -0
- package/lib/launchd-target-lock.js.map +1 -0
- package/lib/launchd.d.ts +62 -0
- package/lib/launchd.d.ts.map +1 -0
- package/lib/launchd.js +370 -0
- package/lib/launchd.js.map +1 -0
- package/lib/model-picker.d.ts +24 -0
- package/lib/model-picker.d.ts.map +1 -0
- package/lib/model-picker.js +95 -0
- package/lib/model-picker.js.map +1 -0
- package/lib/normalize.d.ts +12 -0
- package/lib/normalize.d.ts.map +1 -0
- package/lib/normalize.js +85 -0
- package/lib/normalize.js.map +1 -0
- package/lib/permission-picker.d.ts +29 -0
- package/lib/permission-picker.d.ts.map +1 -0
- package/lib/permission-picker.js +145 -0
- package/lib/permission-picker.js.map +1 -0
- package/lib/progress.d.ts +34 -0
- package/lib/progress.d.ts.map +1 -0
- package/lib/progress.js +354 -0
- package/lib/progress.js.map +1 -0
- package/lib/resident.d.ts +13 -0
- package/lib/resident.d.ts.map +1 -0
- package/lib/resident.js +41 -0
- package/lib/resident.js.map +1 -0
- package/lib/rsi-authority-config.d.ts +29 -0
- package/lib/rsi-authority-config.d.ts.map +1 -0
- package/lib/rsi-authority-config.js +233 -0
- package/lib/rsi-authority-config.js.map +1 -0
- package/lib/rsi-authority-resources.d.ts +36 -0
- package/lib/rsi-authority-resources.d.ts.map +1 -0
- package/lib/rsi-authority-resources.js +139 -0
- package/lib/rsi-authority-resources.js.map +1 -0
- package/lib/rsi-authority-runtime.d.ts +51 -0
- package/lib/rsi-authority-runtime.d.ts.map +1 -0
- package/lib/rsi-authority-runtime.js +496 -0
- package/lib/rsi-authority-runtime.js.map +1 -0
- package/lib/rsi-bootstrap-manifest.d.ts +53 -0
- package/lib/rsi-bootstrap-manifest.d.ts.map +1 -0
- package/lib/rsi-bootstrap-manifest.js +507 -0
- package/lib/rsi-bootstrap-manifest.js.map +1 -0
- package/lib/rsi-bootstrap.d.ts +61 -0
- package/lib/rsi-bootstrap.d.ts.map +1 -0
- package/lib/rsi-bootstrap.js +597 -0
- package/lib/rsi-bootstrap.js.map +1 -0
- package/lib/rsi-build.d.ts +76 -0
- package/lib/rsi-build.d.ts.map +1 -0
- package/lib/rsi-build.js +210 -0
- package/lib/rsi-build.js.map +1 -0
- package/lib/rsi-host-authorities.d.ts +18 -0
- package/lib/rsi-host-authorities.d.ts.map +1 -0
- package/lib/rsi-host-authorities.js +129 -0
- package/lib/rsi-host-authorities.js.map +1 -0
- package/lib/rsi-host-update.d.ts +179 -0
- package/lib/rsi-host-update.d.ts.map +1 -0
- package/lib/rsi-host-update.js +568 -0
- package/lib/rsi-host-update.js.map +1 -0
- package/lib/rsi-install-inputs.d.ts +45 -0
- package/lib/rsi-install-inputs.d.ts.map +1 -0
- package/lib/rsi-install-inputs.js +345 -0
- package/lib/rsi-install-inputs.js.map +1 -0
- package/lib/rsi-install.d.ts +117 -0
- package/lib/rsi-install.d.ts.map +1 -0
- package/lib/rsi-install.js +791 -0
- package/lib/rsi-install.js.map +1 -0
- package/lib/rsi-linux-cgroup-roots.d.ts +3 -0
- package/lib/rsi-linux-cgroup-roots.d.ts.map +1 -0
- package/lib/rsi-linux-cgroup-roots.js +3 -0
- package/lib/rsi-linux-cgroup-roots.js.map +1 -0
- package/lib/rsi-linux-creation-build.d.ts +36 -0
- package/lib/rsi-linux-creation-build.d.ts.map +1 -0
- package/lib/rsi-linux-creation-build.js +213 -0
- package/lib/rsi-linux-creation-build.js.map +1 -0
- package/lib/rsi-linux-native-materialize.d.ts +31 -0
- package/lib/rsi-linux-native-materialize.d.ts.map +1 -0
- package/lib/rsi-linux-native-materialize.js +162 -0
- package/lib/rsi-linux-native-materialize.js.map +1 -0
- package/lib/rsi-linux-native-relocation.d.ts +124 -0
- package/lib/rsi-linux-native-relocation.d.ts.map +1 -0
- package/lib/rsi-linux-native-relocation.js +1571 -0
- package/lib/rsi-linux-native-relocation.js.map +1 -0
- package/lib/rsi-linux-native-resources.d.ts +97 -0
- package/lib/rsi-linux-native-resources.d.ts.map +1 -0
- package/lib/rsi-linux-native-resources.js +521 -0
- package/lib/rsi-linux-native-resources.js.map +1 -0
- package/lib/rsi-linux-repository-bootstrap.d.ts +17 -0
- package/lib/rsi-linux-repository-bootstrap.d.ts.map +1 -0
- package/lib/rsi-linux-repository-bootstrap.js +317 -0
- package/lib/rsi-linux-repository-bootstrap.js.map +1 -0
- package/lib/rsi-linux-runner-states.d.ts +20 -0
- package/lib/rsi-linux-runner-states.d.ts.map +1 -0
- package/lib/rsi-linux-runner-states.js +70 -0
- package/lib/rsi-linux-runner-states.js.map +1 -0
- package/lib/rsi-linux-runtime-bootstrap.d.ts +10 -0
- package/lib/rsi-linux-runtime-bootstrap.d.ts.map +1 -0
- package/lib/rsi-linux-runtime-bootstrap.js +38 -0
- package/lib/rsi-linux-runtime-bootstrap.js.map +1 -0
- package/lib/rsi-linux-source-build.d.ts +28 -0
- package/lib/rsi-linux-source-build.d.ts.map +1 -0
- package/lib/rsi-linux-source-build.js +43 -0
- package/lib/rsi-linux-source-build.js.map +1 -0
- package/lib/rsi-local-activation.d.ts +78 -0
- package/lib/rsi-local-activation.d.ts.map +1 -0
- package/lib/rsi-local-activation.js +486 -0
- package/lib/rsi-local-activation.js.map +1 -0
- package/lib/rsi-local-cohort.d.ts +70 -0
- package/lib/rsi-local-cohort.d.ts.map +1 -0
- package/lib/rsi-local-cohort.js +810 -0
- package/lib/rsi-local-cohort.js.map +1 -0
- package/lib/rsi-local-install.d.ts +70 -0
- package/lib/rsi-local-install.d.ts.map +1 -0
- package/lib/rsi-local-install.js +363 -0
- package/lib/rsi-local-install.js.map +1 -0
- package/lib/rsi-local-pair-install.d.ts +53 -0
- package/lib/rsi-local-pair-install.d.ts.map +1 -0
- package/lib/rsi-local-pair-install.js +215 -0
- package/lib/rsi-local-pair-install.js.map +1 -0
- package/lib/rsi-local-profile-update.d.ts +25 -0
- package/lib/rsi-local-profile-update.d.ts.map +1 -0
- package/lib/rsi-local-profile-update.js +226 -0
- package/lib/rsi-local-profile-update.js.map +1 -0
- package/lib/rsi-local-roots-extension.d.ts +11 -0
- package/lib/rsi-local-roots-extension.d.ts.map +1 -0
- package/lib/rsi-local-roots-extension.js +31 -0
- package/lib/rsi-local-roots-extension.js.map +1 -0
- package/lib/rsi-local-update-build.d.ts +37 -0
- package/lib/rsi-local-update-build.d.ts.map +1 -0
- package/lib/rsi-local-update-build.js +75 -0
- package/lib/rsi-local-update-build.js.map +1 -0
- package/lib/rsi-local-update.d.ts +39 -0
- package/lib/rsi-local-update.d.ts.map +1 -0
- package/lib/rsi-local-update.js +205 -0
- package/lib/rsi-local-update.js.map +1 -0
- package/lib/rsi-memory-learning.d.ts +36 -0
- package/lib/rsi-memory-learning.d.ts.map +1 -0
- package/lib/rsi-memory-learning.js +111 -0
- package/lib/rsi-memory-learning.js.map +1 -0
- package/lib/rsi-native-install.d.ts +38 -0
- package/lib/rsi-native-install.d.ts.map +1 -0
- package/lib/rsi-native-install.js +312 -0
- package/lib/rsi-native-install.js.map +1 -0
- package/lib/rsi-native-launchd.d.ts +7 -0
- package/lib/rsi-native-launchd.d.ts.map +1 -0
- package/lib/rsi-native-launchd.js +49 -0
- package/lib/rsi-native-launchd.js.map +1 -0
- package/lib/rsi-native-profile.d.ts +76 -0
- package/lib/rsi-native-profile.d.ts.map +1 -0
- package/lib/rsi-native-profile.js +530 -0
- package/lib/rsi-native-profile.js.map +1 -0
- package/lib/rsi-native-runtime-bootstrap.d.ts +44 -0
- package/lib/rsi-native-runtime-bootstrap.d.ts.map +1 -0
- package/lib/rsi-native-runtime-bootstrap.js +619 -0
- package/lib/rsi-native-runtime-bootstrap.js.map +1 -0
- package/lib/rsi-ordinary-use-learning.d.ts +60 -0
- package/lib/rsi-ordinary-use-learning.d.ts.map +1 -0
- package/lib/rsi-ordinary-use-learning.js +103 -0
- package/lib/rsi-ordinary-use-learning.js.map +1 -0
- package/lib/rsi-owner-profile.d.ts +37 -0
- package/lib/rsi-owner-profile.d.ts.map +1 -0
- package/lib/rsi-owner-profile.js +178 -0
- package/lib/rsi-owner-profile.js.map +1 -0
- package/lib/rsi-plugin-creation.d.ts +46 -0
- package/lib/rsi-plugin-creation.d.ts.map +1 -0
- package/lib/rsi-plugin-creation.js +227 -0
- package/lib/rsi-plugin-creation.js.map +1 -0
- package/lib/rsi-plugin-revision.d.ts +38 -0
- package/lib/rsi-plugin-revision.d.ts.map +1 -0
- package/lib/rsi-plugin-revision.js +221 -0
- package/lib/rsi-plugin-revision.js.map +1 -0
- package/lib/rsi-profile.d.ts +81 -0
- package/lib/rsi-profile.d.ts.map +1 -0
- package/lib/rsi-profile.js +551 -0
- package/lib/rsi-profile.js.map +1 -0
- package/lib/rsi-release-build.d.ts +59 -0
- package/lib/rsi-release-build.d.ts.map +1 -0
- package/lib/rsi-release-build.js +219 -0
- package/lib/rsi-release-build.js.map +1 -0
- package/lib/rsi-scanner-retirement-config.d.ts +34 -0
- package/lib/rsi-scanner-retirement-config.d.ts.map +1 -0
- package/lib/rsi-scanner-retirement-config.js +272 -0
- package/lib/rsi-scanner-retirement-config.js.map +1 -0
- package/lib/rsi-scanner-retirement-runtime.d.ts +23 -0
- package/lib/rsi-scanner-retirement-runtime.d.ts.map +1 -0
- package/lib/rsi-scanner-retirement-runtime.js +98 -0
- package/lib/rsi-scanner-retirement-runtime.js.map +1 -0
- package/lib/rsi-scanner-retirement-stage.d.ts +55 -0
- package/lib/rsi-scanner-retirement-stage.d.ts.map +1 -0
- package/lib/rsi-scanner-retirement-stage.js +181 -0
- package/lib/rsi-scanner-retirement-stage.js.map +1 -0
- package/lib/rsi-scanner-retirement-transition.d.ts +57 -0
- package/lib/rsi-scanner-retirement-transition.d.ts.map +1 -0
- package/lib/rsi-scanner-retirement-transition.js +330 -0
- package/lib/rsi-scanner-retirement-transition.js.map +1 -0
- package/lib/rsi-service-environment.d.ts +6 -0
- package/lib/rsi-service-environment.d.ts.map +1 -0
- package/lib/rsi-service-environment.js +113 -0
- package/lib/rsi-service-environment.js.map +1 -0
- package/lib/rsi-service-setup.d.ts +10 -0
- package/lib/rsi-service-setup.d.ts.map +1 -0
- package/lib/rsi-service-setup.js +34 -0
- package/lib/rsi-service-setup.js.map +1 -0
- package/lib/rsi-setup.d.ts +92 -0
- package/lib/rsi-setup.d.ts.map +1 -0
- package/lib/rsi-setup.js +908 -0
- package/lib/rsi-setup.js.map +1 -0
- package/lib/rsi-source-maintenance.d.ts +33 -0
- package/lib/rsi-source-maintenance.d.ts.map +1 -0
- package/lib/rsi-source-maintenance.js +407 -0
- package/lib/rsi-source-maintenance.js.map +1 -0
- package/lib/rsi-source-update.d.ts +26 -0
- package/lib/rsi-source-update.d.ts.map +1 -0
- package/lib/rsi-source-update.js +276 -0
- package/lib/rsi-source-update.js.map +1 -0
- package/lib/rsi-source.d.ts +34 -0
- package/lib/rsi-source.d.ts.map +1 -0
- package/lib/rsi-source.js +487 -0
- package/lib/rsi-source.js.map +1 -0
- package/lib/rsi-systemd-bootstrap.d.ts +46 -0
- package/lib/rsi-systemd-bootstrap.d.ts.map +1 -0
- package/lib/rsi-systemd-bootstrap.js +271 -0
- package/lib/rsi-systemd-bootstrap.js.map +1 -0
- package/lib/sdk.d.ts +216 -0
- package/lib/sdk.d.ts.map +1 -0
- package/lib/sdk.js +1990 -0
- package/lib/sdk.js.map +1 -0
- package/lib/service.d.ts +63 -0
- package/lib/service.d.ts.map +1 -0
- package/lib/service.js +599 -0
- package/lib/service.js.map +1 -0
- package/lib/setup-business.d.ts +49 -0
- package/lib/setup-business.d.ts.map +1 -0
- package/lib/setup-business.js +335 -0
- package/lib/setup-business.js.map +1 -0
- package/lib/setup-materialization.d.ts +15 -0
- package/lib/setup-materialization.d.ts.map +1 -0
- package/lib/setup-materialization.js +221 -0
- package/lib/setup-materialization.js.map +1 -0
- package/lib/setup-profile.d.ts +23 -0
- package/lib/setup-profile.d.ts.map +1 -0
- package/lib/setup-profile.js +1248 -0
- package/lib/setup-profile.js.map +1 -0
- package/lib/setup.d.ts +298 -0
- package/lib/setup.d.ts.map +1 -0
- package/lib/setup.js +3310 -0
- package/lib/setup.js.map +1 -0
- package/lib/supervised-growth-profile.d.ts +111 -0
- package/lib/supervised-growth-profile.d.ts.map +1 -0
- package/lib/supervised-growth-profile.js +903 -0
- package/lib/supervised-growth-profile.js.map +1 -0
- package/lib/supervised-growth-setup.d.ts +201 -0
- package/lib/supervised-growth-setup.d.ts.map +1 -0
- package/lib/supervised-growth-setup.js +1005 -0
- package/lib/supervised-growth-setup.js.map +1 -0
- package/lib/systemd.d.ts +70 -0
- package/lib/systemd.d.ts.map +1 -0
- package/lib/systemd.js +308 -0
- package/lib/systemd.js.map +1 -0
- package/lib/tool-approval.d.ts +22 -0
- package/lib/tool-approval.d.ts.map +1 -0
- package/lib/tool-approval.js +107 -0
- package/lib/tool-approval.js.map +1 -0
- package/lib/types.d.ts +351 -0
- package/lib/types.d.ts.map +1 -0
- package/lib/types.js +11 -0
- package/lib/types.js.map +1 -0
- package/lib/user-question.d.ts +31 -0
- package/lib/user-question.d.ts.map +1 -0
- package/lib/user-question.js +161 -0
- package/lib/user-question.js.map +1 -0
- package/lib/version.d.ts +2 -0
- package/lib/version.d.ts.map +1 -0
- package/lib/version.js +2 -0
- package/lib/version.js.map +1 -0
- package/lib/windows-task.d.ts +42 -0
- package/lib/windows-task.d.ts.map +1 -0
- package/lib/windows-task.js +143 -0
- package/lib/windows-task.js.map +1 -0
- package/lib/ws-card-callback.d.ts +7 -0
- package/lib/ws-card-callback.d.ts.map +1 -0
- package/lib/ws-card-callback.js +51 -0
- package/lib/ws-card-callback.js.map +1 -0
- package/package.json +169 -3
package/lib/adapter.js
ADDED
|
@@ -0,0 +1,2072 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { LarkApprovalError, signLarkApprovalAction, verifyLarkApprovalAction, verifyLarkApprovalActionForRecovery, } from './approval.js';
|
|
3
|
+
import { tryBuildLarkCommandCard } from './command-card.js';
|
|
4
|
+
import { LarkModelPickerError, parseLarkModelPickerCallback, signLarkModelPickerAction, verifyLarkModelPickerAction, } from './model-picker.js';
|
|
5
|
+
import { isLarkTopicThread, isLarkTopLevelSenderThread } from './group-thread.js';
|
|
6
|
+
import { normalizeLarkMessage } from './normalize.js';
|
|
7
|
+
import { LarkPermissionPickerError, parseLarkPermissionPickerCallback, signLarkPermissionPickerAction, verifyLarkPermissionPickerAction, } from './permission-picker.js';
|
|
8
|
+
import { LarkProgressPresenter } from './progress.js';
|
|
9
|
+
import { LARK_APPROVAL_CARD_MAX_BYTES, LARK_TEXT_FILE_MAX_BYTES, renderLarkMessage } from './sdk.js';
|
|
10
|
+
import { LarkToolApprovalError, signLarkToolApprovalAction, verifyLarkToolApprovalAction, } from './tool-approval.js';
|
|
11
|
+
import { LarkUserQuestionError, parseLarkUserQuestionCallback, signLarkUserQuestionAction, verifyLarkUserQuestionAction, } from './user-question.js';
|
|
12
|
+
import { LarkTransportError, } from './types.js';
|
|
13
|
+
const LARK_TOOL_APPROVAL_REASON_MAX_BYTES = 2 * 1_024;
|
|
14
|
+
const LARK_TOOL_APPROVAL_ARGUMENTS_MAX_BYTES = 16 * 1_024;
|
|
15
|
+
const LARK_TOOL_APPROVAL_MAX_TIMER_MS = 2_147_483_647;
|
|
16
|
+
const LARK_USER_QUESTION_MAX_QUESTIONS = 16;
|
|
17
|
+
const LARK_USER_QUESTION_MAX_OPTIONS = 20;
|
|
18
|
+
const LARK_USER_QUESTION_MAX_TEXT_BYTES = 16 * 1_024;
|
|
19
|
+
const larkCallbackIdentifier = /^[A-Za-z0-9][A-Za-z0-9._@:-]{0,255}$/u;
|
|
20
|
+
const larkProviderMessageIdentifier = /^[A-Za-z0-9][A-Za-z0-9._@/-]{0,255}$/u;
|
|
21
|
+
const larkResourceIdentifier = /^[A-Za-z0-9][A-Za-z0-9._@-]{0,255}$/u;
|
|
22
|
+
const larkTextAttachmentName = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;
|
|
23
|
+
const LARK_PENDING_ATTACHMENT_SEND_LIMIT = 256;
|
|
24
|
+
function hasUsableApprovalSecret(secret) {
|
|
25
|
+
return secret !== undefined && Buffer.byteLength(secret, 'utf8') >= 16;
|
|
26
|
+
}
|
|
27
|
+
function boundedReviewText(value, maxBytes) {
|
|
28
|
+
return value === undefined || (Buffer.byteLength(value, 'utf8') <= maxBytes
|
|
29
|
+
&& !/(?:\p{Cc}|\p{Bidi_Control})/u.test(value.replaceAll('\n', '').replaceAll('\r', '').replaceAll('\t', '')));
|
|
30
|
+
}
|
|
31
|
+
function samePrincipal(left, right) {
|
|
32
|
+
return left.channel === right.channel
|
|
33
|
+
&& left.account === right.account
|
|
34
|
+
&& left.tenant === right.tenant
|
|
35
|
+
&& left.user === right.user;
|
|
36
|
+
}
|
|
37
|
+
function sameConversation(left, right) {
|
|
38
|
+
return left.channel === right.channel
|
|
39
|
+
&& left.account === right.account
|
|
40
|
+
&& left.tenant === right.tenant
|
|
41
|
+
&& left.kind === right.kind
|
|
42
|
+
&& left.chat === right.chat
|
|
43
|
+
&& left.thread === right.thread;
|
|
44
|
+
}
|
|
45
|
+
function validUserQuestionRequest(input) {
|
|
46
|
+
if (!larkCallbackIdentifier.test(input.operationId)
|
|
47
|
+
|| !larkCallbackIdentifier.test(input.bindingId)
|
|
48
|
+
|| !larkCallbackIdentifier.test(input.sessionId)
|
|
49
|
+
|| !Number.isSafeInteger(input.bindingVersion) || input.bindingVersion < 1
|
|
50
|
+
|| !Number.isSafeInteger(input.bindingGeneration) || input.bindingGeneration < 1
|
|
51
|
+
|| input.questions.length < 1 || input.questions.length > LARK_USER_QUESTION_MAX_QUESTIONS) {
|
|
52
|
+
return false;
|
|
53
|
+
}
|
|
54
|
+
const ids = new Set();
|
|
55
|
+
for (const question of input.questions) {
|
|
56
|
+
if (typeof question.id !== 'string' || question.id.length === 0 || ids.has(question.id)
|
|
57
|
+
|| typeof question.question !== 'string' || question.question.trim().length === 0
|
|
58
|
+
|| !boundedReviewText(question.question, LARK_USER_QUESTION_MAX_TEXT_BYTES)
|
|
59
|
+
|| !boundedReviewText(question.detail, LARK_USER_QUESTION_MAX_TEXT_BYTES)
|
|
60
|
+
|| !boundedReviewText(question.header, 1_024)) {
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
ids.add(question.id);
|
|
64
|
+
const options = question.options ?? [];
|
|
65
|
+
if (options.length > LARK_USER_QUESTION_MAX_OPTIONS)
|
|
66
|
+
return false;
|
|
67
|
+
const labels = new Set();
|
|
68
|
+
for (const option of options) {
|
|
69
|
+
if (typeof option.label !== 'string' || option.label.trim().length === 0
|
|
70
|
+
|| labels.has(option.label)
|
|
71
|
+
|| !boundedReviewText(option.label, 1_024)
|
|
72
|
+
|| !boundedReviewText(option.description, 4_096)) {
|
|
73
|
+
return false;
|
|
74
|
+
}
|
|
75
|
+
labels.add(option.label);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return true;
|
|
79
|
+
}
|
|
80
|
+
function displayOptionLabel(label) {
|
|
81
|
+
const recommended = /(?:\s*\(Recommended\)|\s*(推荐))\s*$/u;
|
|
82
|
+
return recommended.test(label)
|
|
83
|
+
? { label: label.replace(recommended, '').trim() || label, recommended: true }
|
|
84
|
+
: { label, recommended: false };
|
|
85
|
+
}
|
|
86
|
+
function sameToolApprovalPayload(left, right) {
|
|
87
|
+
return left.version === right.version
|
|
88
|
+
&& left.channel === right.channel
|
|
89
|
+
&& left.account === right.account
|
|
90
|
+
&& left.tenant === right.tenant
|
|
91
|
+
&& left.operationId === right.operationId
|
|
92
|
+
&& left.bindingId === right.bindingId
|
|
93
|
+
&& left.chatId === right.chatId
|
|
94
|
+
&& left.ownerUser === right.ownerUser
|
|
95
|
+
&& left.actionHash === right.actionHash
|
|
96
|
+
&& left.toolName === right.toolName
|
|
97
|
+
&& left.callId === right.callId
|
|
98
|
+
&& left.expiresAt === right.expiresAt;
|
|
99
|
+
}
|
|
100
|
+
function failureCode(code) {
|
|
101
|
+
return `lark-${code.replaceAll('_', '-')}`;
|
|
102
|
+
}
|
|
103
|
+
function modelPickerFallbackText(intent) {
|
|
104
|
+
const picker = intent.modelPicker;
|
|
105
|
+
if (picker === undefined)
|
|
106
|
+
return intent.text;
|
|
107
|
+
return [
|
|
108
|
+
'飞书未接受模型选择卡片,已回退为文字目录。',
|
|
109
|
+
intent.text,
|
|
110
|
+
'',
|
|
111
|
+
'可用模型:',
|
|
112
|
+
...picker.models.map(model => `- ${model.provider}/${model.id}${model.name === model.id ? '' : ` — ${model.name}`}`),
|
|
113
|
+
'',
|
|
114
|
+
'切换:/model use <provider/model> [effort]',
|
|
115
|
+
'恢复默认:/model reset',
|
|
116
|
+
].join('\n');
|
|
117
|
+
}
|
|
118
|
+
function permissionPickerCard(intent, secret, capability) {
|
|
119
|
+
const current = intent.current === 'ask'
|
|
120
|
+
? '请求批准(ask)'
|
|
121
|
+
: intent.current === 'auto'
|
|
122
|
+
? '帮我批准(auto)'
|
|
123
|
+
: intent.current === 'full'
|
|
124
|
+
? '完全访问权限(full)'
|
|
125
|
+
: '自定义安全组合(custom)';
|
|
126
|
+
const callbackValue = (level) => ({
|
|
127
|
+
permissionPicker: signLarkPermissionPickerAction(secret, {
|
|
128
|
+
version: 2,
|
|
129
|
+
...capability,
|
|
130
|
+
operationId: intent.operationId,
|
|
131
|
+
bindingVersion: intent.bindingVersion,
|
|
132
|
+
sessionId: intent.sessionId,
|
|
133
|
+
issuedAt: intent.issuedAt,
|
|
134
|
+
expiresAt: intent.expiresAt,
|
|
135
|
+
expectedStateHash: intent.expectedStateHash,
|
|
136
|
+
emergencyStopVersion: intent.emergencyStopVersion,
|
|
137
|
+
level,
|
|
138
|
+
}),
|
|
139
|
+
});
|
|
140
|
+
return {
|
|
141
|
+
title: '选择权限模式',
|
|
142
|
+
body: `当前:${current}。请选择新档位。`,
|
|
143
|
+
current: intent.current,
|
|
144
|
+
callbackValues: {
|
|
145
|
+
ask: callbackValue('ask'),
|
|
146
|
+
auto: callbackValue('auto'),
|
|
147
|
+
full: callbackValue('full'),
|
|
148
|
+
},
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
function sendFailure(error) {
|
|
152
|
+
if (!(error instanceof LarkTransportError)) {
|
|
153
|
+
return { outcome: 'unknown', failureCode: 'lark-unknown' };
|
|
154
|
+
}
|
|
155
|
+
if (error.code === 'send_timeout' || error.code === 'unknown') {
|
|
156
|
+
return { outcome: 'unknown', failureCode: failureCode(error.code) };
|
|
157
|
+
}
|
|
158
|
+
const retryable = error.code === 'rate_limited' || error.code === 'not_connected';
|
|
159
|
+
return {
|
|
160
|
+
outcome: 'not-sent',
|
|
161
|
+
failureCode: failureCode(error.code),
|
|
162
|
+
retryable,
|
|
163
|
+
...(error.retryAfterMs === undefined ? {} : { retryAfterMs: error.retryAfterMs }),
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
function validateOutboundTextAttachment(intent, maxBytes) {
|
|
167
|
+
if ((intent.format ?? 'plain') !== 'plain') {
|
|
168
|
+
return {
|
|
169
|
+
ok: false,
|
|
170
|
+
failure: { outcome: 'not-sent', failureCode: 'lark-attachment-unsupported-format', retryable: false },
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
const attachment = intent.attachment;
|
|
174
|
+
if (attachment === undefined || attachment === null || typeof attachment !== 'object'
|
|
175
|
+
|| attachment.kind !== 'text'
|
|
176
|
+
|| typeof attachment.name !== 'string'
|
|
177
|
+
|| !larkTextAttachmentName.test(attachment.name)
|
|
178
|
+
|| attachment.name.includes('..')
|
|
179
|
+
|| (attachment.mediaType !== 'text/plain' && attachment.mediaType !== 'text/markdown')
|
|
180
|
+
|| typeof attachment.text !== 'string'
|
|
181
|
+
|| attachment.text.length === 0) {
|
|
182
|
+
return { ok: false, failure: { outcome: 'not-sent', failureCode: 'lark-attachment-invalid', retryable: false } };
|
|
183
|
+
}
|
|
184
|
+
if (Buffer.byteLength(attachment.text, 'utf8') > maxBytes) {
|
|
185
|
+
return { ok: false, failure: { outcome: 'not-sent', failureCode: 'lark-attachment-too-large', retryable: false } };
|
|
186
|
+
}
|
|
187
|
+
const expectedDigest = createHash('sha256').update(attachment.text, 'utf8').digest('hex');
|
|
188
|
+
if (typeof attachment.sha256 !== 'string' || attachment.sha256 !== expectedDigest) {
|
|
189
|
+
return {
|
|
190
|
+
ok: false,
|
|
191
|
+
failure: { outcome: 'not-sent', failureCode: 'lark-attachment-digest-mismatch', retryable: false },
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
return { ok: true, attachment };
|
|
195
|
+
}
|
|
196
|
+
function uploadFailure(error) {
|
|
197
|
+
if (!(error instanceof LarkTransportError)) {
|
|
198
|
+
return { outcome: 'not-sent', failureCode: 'lark-upload-failed', retryable: true };
|
|
199
|
+
}
|
|
200
|
+
const retryable = error.code !== 'format_error'
|
|
201
|
+
&& error.code !== 'permission_denied'
|
|
202
|
+
&& error.code !== 'target_revoked'
|
|
203
|
+
&& error.code !== 'ssrf_blocked';
|
|
204
|
+
return {
|
|
205
|
+
outcome: 'not-sent',
|
|
206
|
+
failureCode: failureCode(error.code),
|
|
207
|
+
retryable,
|
|
208
|
+
...(error.retryAfterMs === undefined ? {} : { retryAfterMs: error.retryAfterMs }),
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
function routeParts(route) {
|
|
212
|
+
const separator = route.indexOf('/');
|
|
213
|
+
if (separator <= 0 || separator === route.length - 1)
|
|
214
|
+
return undefined;
|
|
215
|
+
return { provider: route.slice(0, separator), model: route.slice(separator + 1) };
|
|
216
|
+
}
|
|
217
|
+
function defaultEffortOption(effortIds) {
|
|
218
|
+
let value = '__default__';
|
|
219
|
+
while (effortIds.includes(value))
|
|
220
|
+
value += '_';
|
|
221
|
+
return value;
|
|
222
|
+
}
|
|
223
|
+
function resolveModelPicker(picker, preferred = {}) {
|
|
224
|
+
const modelsByProvider = new Map();
|
|
225
|
+
for (const model of picker.models) {
|
|
226
|
+
const models = modelsByProvider.get(model.provider) ?? [];
|
|
227
|
+
models.push(model);
|
|
228
|
+
modelsByProvider.set(model.provider, models);
|
|
229
|
+
}
|
|
230
|
+
const provider = [preferred.provider, picker.current.provider, ...picker.providers.map(value => value.id)]
|
|
231
|
+
.find(value => value !== undefined && (modelsByProvider.get(value)?.length ?? 0) > 0);
|
|
232
|
+
if (provider === undefined)
|
|
233
|
+
throw new LarkModelPickerError('invalid', 'model picker has no selectable provider');
|
|
234
|
+
const providerModels = modelsByProvider.get(provider);
|
|
235
|
+
const currentRoute = `${picker.current.provider}/${picker.current.model}`;
|
|
236
|
+
const route = [preferred.route, currentRoute]
|
|
237
|
+
.find(value => value !== undefined && providerModels.some(model => `${model.provider}/${model.id}` === value))
|
|
238
|
+
?? `${providerModels[0].provider}/${providerModels[0].id}`;
|
|
239
|
+
const selectedModel = providerModels.find(model => `${model.provider}/${model.id}` === route);
|
|
240
|
+
const effortNames = new Map(picker.efforts.map(effort => [effort.id, effort.name]));
|
|
241
|
+
const linkedEfforts = (selectedModel.effortIds ?? [])
|
|
242
|
+
.flatMap(id => effortNames.has(id) ? [{ value: id, label: effortNames.get(id) }] : []);
|
|
243
|
+
const defaultEffort = defaultEffortOption(linkedEfforts.map(effort => effort.value));
|
|
244
|
+
const preferredEffort = preferred.effort;
|
|
245
|
+
const initialEffort = preferredEffort === null
|
|
246
|
+
? defaultEffort
|
|
247
|
+
: preferredEffort !== undefined && linkedEfforts.some(effort => effort.value === preferredEffort)
|
|
248
|
+
? preferredEffort
|
|
249
|
+
: route === currentRoute && picker.current.reasoningEffort !== undefined
|
|
250
|
+
&& linkedEfforts.some(effort => effort.value === picker.current.reasoningEffort)
|
|
251
|
+
? picker.current.reasoningEffort
|
|
252
|
+
: defaultEffort;
|
|
253
|
+
return { modelsByProvider, provider, providerModels, route, selectedModel,
|
|
254
|
+
linkedEfforts, defaultEffort, initialEffort };
|
|
255
|
+
}
|
|
256
|
+
function resolvedModelRoute(resolved) {
|
|
257
|
+
return { provider: resolved.provider, model: resolved.selectedModel.id,
|
|
258
|
+
...(resolved.initialEffort === resolved.defaultEffort ? {} : { reasoningEffort: resolved.initialEffort }) };
|
|
259
|
+
}
|
|
260
|
+
function modelPickerCard(picker, secret, capability, preferred = {}) {
|
|
261
|
+
const { modelsByProvider, provider, providerModels, route, selectedModel, linkedEfforts, defaultEffort, initialEffort } = resolveModelPicker(picker, preferred);
|
|
262
|
+
const currentRoute = `${picker.current.provider}/${picker.current.model}`;
|
|
263
|
+
const signedState = {
|
|
264
|
+
version: 3,
|
|
265
|
+
...capability,
|
|
266
|
+
provider,
|
|
267
|
+
model: selectedModel.id,
|
|
268
|
+
effort: initialEffort === defaultEffort ? null : initialEffort,
|
|
269
|
+
};
|
|
270
|
+
const callbackValue = (action) => ({
|
|
271
|
+
modelPicker: signLarkModelPickerAction(secret, { ...signedState, action }),
|
|
272
|
+
});
|
|
273
|
+
const currentEffort = picker.current.reasoningEffort === undefined ? '' : `,effort:${picker.current.reasoningEffort}`;
|
|
274
|
+
return {
|
|
275
|
+
title: '选择会话模型',
|
|
276
|
+
body: `当前模型:${currentRoute}${currentEffort}\n\n选择将在下一条消息生效,并保留当前上下文。`,
|
|
277
|
+
providerOptions: picker.providers
|
|
278
|
+
.filter(value => (modelsByProvider.get(value.id)?.length ?? 0) > 0)
|
|
279
|
+
.map(value => ({ value: value.id, label: value.name })),
|
|
280
|
+
modelOptions: providerModels.map(model => ({ value: `${model.provider}/${model.id}`, label: model.name })),
|
|
281
|
+
effortOptions: [
|
|
282
|
+
{ value: defaultEffort, label: linkedEfforts.length === 0
|
|
283
|
+
? '默认(该模型无 effort 档位)'
|
|
284
|
+
: '默认(由模型决定)' },
|
|
285
|
+
...linkedEfforts,
|
|
286
|
+
],
|
|
287
|
+
initialProvider: provider,
|
|
288
|
+
initialModel: route,
|
|
289
|
+
initialEffort,
|
|
290
|
+
callbackValues: {
|
|
291
|
+
provider: callbackValue('provider'),
|
|
292
|
+
model: callbackValue('model'),
|
|
293
|
+
effort: callbackValue('effort'),
|
|
294
|
+
confirm: callbackValue('confirm'),
|
|
295
|
+
},
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
function modelSelectionRejectionMessage(reason) {
|
|
299
|
+
switch (reason) {
|
|
300
|
+
case 'authorization-revoked': return '当前账号或会话授权已失效,模型未切换。请重新发送 /model。';
|
|
301
|
+
case 'invalid-effort': return '所选 effort 当前不可用,模型未切换。请重新发送 /model。';
|
|
302
|
+
case 'model-unavailable': return '所选模型当前不可用,模型未切换。请重新发送 /model。';
|
|
303
|
+
case 'provider-model-mismatch': return '模型与 provider 不匹配,模型未切换。请重新发送 /model。';
|
|
304
|
+
case 'provider-unavailable': return '所选 provider 当前不可用,模型未切换。请重新发送 /model。';
|
|
305
|
+
case 'selection-superseded': return '该模型选择已被更晚的操作取代,未更改当前模型。';
|
|
306
|
+
}
|
|
307
|
+
return '模型切换未生效,请重新发送 /model。';
|
|
308
|
+
}
|
|
309
|
+
function modelSelectionResultCard(result, payload, picker) {
|
|
310
|
+
const route = result.status === 'selected'
|
|
311
|
+
? { ...result.selection, effort: result.selection.reasoningEffort ?? null }
|
|
312
|
+
: payload;
|
|
313
|
+
const provider = picker?.providers.find(value => value.id === route.provider)?.name ?? route.provider;
|
|
314
|
+
const selectedModel = picker?.models.find(value => value.provider === route.provider && value.id === route.model);
|
|
315
|
+
const model = selectedModel?.name ?? route.model;
|
|
316
|
+
const effort = route.effort === null
|
|
317
|
+
? selectedModel?.effortIds.length === 0
|
|
318
|
+
? '默认(该模型无 effort 档位)'
|
|
319
|
+
: '默认(由模型决定)'
|
|
320
|
+
: picker?.efforts.find(value => value.id === route.effort)?.name ?? route.effort;
|
|
321
|
+
const routeCard = { provider, model, effort };
|
|
322
|
+
return result.status === 'rejected'
|
|
323
|
+
? { status: 'rejected', explanation: modelSelectionRejectionMessage(result.reason), ...routeCard }
|
|
324
|
+
: { status: result.status, ...routeCard };
|
|
325
|
+
}
|
|
326
|
+
function callbackCard(input) {
|
|
327
|
+
return { card: { type: 'raw', data: rawCard(input) } };
|
|
328
|
+
}
|
|
329
|
+
function rawCard(input) {
|
|
330
|
+
const rendered = renderLarkMessage(input);
|
|
331
|
+
if (rendered.msgType !== 'interactive') {
|
|
332
|
+
throw new LarkModelPickerError('invalid', 'model picker callback did not render a card');
|
|
333
|
+
}
|
|
334
|
+
const value = JSON.parse(rendered.content);
|
|
335
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
336
|
+
throw new LarkModelPickerError('invalid', 'model picker callback card is invalid');
|
|
337
|
+
}
|
|
338
|
+
return value;
|
|
339
|
+
}
|
|
340
|
+
const MODEL_SELECTION_FINAL_UPDATE_TIMEOUT_MS = 120_000;
|
|
341
|
+
export class LarkDeliveryAdapter {
|
|
342
|
+
config;
|
|
343
|
+
transport;
|
|
344
|
+
channel = 'lark';
|
|
345
|
+
account;
|
|
346
|
+
capabilities;
|
|
347
|
+
now;
|
|
348
|
+
onConnected;
|
|
349
|
+
onDisconnected;
|
|
350
|
+
approvalSecret;
|
|
351
|
+
settleApproval;
|
|
352
|
+
recoverApprovalSettlement;
|
|
353
|
+
settleModelSelection;
|
|
354
|
+
awaitModelSelection;
|
|
355
|
+
settlePermissionSelection;
|
|
356
|
+
loadModelPicker;
|
|
357
|
+
advanceModelPicker;
|
|
358
|
+
statusReactions;
|
|
359
|
+
userQuestionTtlMs;
|
|
360
|
+
progressPresenter;
|
|
361
|
+
progressCredentialFingerprint;
|
|
362
|
+
pendingToolApprovals = new Map();
|
|
363
|
+
pendingUserQuestions = new Map();
|
|
364
|
+
userQuestionAnswerEvents = new Map();
|
|
365
|
+
toolApprovalTombstones = new Map();
|
|
366
|
+
toolApprovalUpdates = new Set();
|
|
367
|
+
closing = false;
|
|
368
|
+
deliveryContext;
|
|
369
|
+
presentationGeneration = 0;
|
|
370
|
+
modelSelectionUpdates = new Map();
|
|
371
|
+
pendingAttachmentSends = new Map();
|
|
372
|
+
state = 'disconnected';
|
|
373
|
+
gapGeneration = 0;
|
|
374
|
+
lastErrorCode;
|
|
375
|
+
constructor(config, transport, options = {}) {
|
|
376
|
+
this.config = config;
|
|
377
|
+
this.transport = transport;
|
|
378
|
+
this.account = config.account;
|
|
379
|
+
const permissionPickerAvailable = hasUsableApprovalSecret(options.approvalSecret)
|
|
380
|
+
&& options.settlePermissionSelection !== undefined;
|
|
381
|
+
this.capabilities = Object.freeze({
|
|
382
|
+
reconcileUnknownSend: false,
|
|
383
|
+
receipts: ['read'],
|
|
384
|
+
// Feishu only reports DM reads; reconnect gaps are not replayable, so
|
|
385
|
+
// absence of a read event must never be treated as authoritative.
|
|
386
|
+
readReceipts: 'best-effort',
|
|
387
|
+
formats: permissionPickerAvailable
|
|
388
|
+
? ['plain', 'markdown', 'approval', 'model-picker', 'permission-picker']
|
|
389
|
+
: ['plain', 'markdown', 'approval', 'model-picker'],
|
|
390
|
+
inboundImages: typeof transport.downloadMessageImage === 'function',
|
|
391
|
+
toolApprovals: hasUsableApprovalSecret(options.approvalSecret),
|
|
392
|
+
userQuestions: hasUsableApprovalSecret(options.approvalSecret),
|
|
393
|
+
textAttachments: true,
|
|
394
|
+
});
|
|
395
|
+
this.now = options.now ?? Date.now;
|
|
396
|
+
this.onConnected = options.onConnected;
|
|
397
|
+
this.onDisconnected = options.onDisconnected;
|
|
398
|
+
this.approvalSecret = options.approvalSecret;
|
|
399
|
+
this.settleApproval = options.settleApproval;
|
|
400
|
+
this.recoverApprovalSettlement = options.recoverApprovalSettlement;
|
|
401
|
+
this.settleModelSelection = options.settleModelSelection;
|
|
402
|
+
this.awaitModelSelection = options.awaitModelSelection;
|
|
403
|
+
this.settlePermissionSelection = options.settlePermissionSelection;
|
|
404
|
+
this.loadModelPicker = options.loadModelPicker;
|
|
405
|
+
this.advanceModelPicker = options.advanceModelPicker;
|
|
406
|
+
this.statusReactions = options.statusReactions ?? true;
|
|
407
|
+
this.userQuestionTtlMs = options.userQuestionTtlMs ?? 24 * 60 * 60 * 1_000;
|
|
408
|
+
this.progressCredentialFingerprint = options.progressCredentialFingerprint;
|
|
409
|
+
this.progressPresenter = new LarkProgressPresenter(transport, options.showProgress ?? true, options.progressDetails ?? 'direct', error => this.recordPresentationFailure(error), options.showBackgroundProgress ?? false);
|
|
410
|
+
}
|
|
411
|
+
async start(context) {
|
|
412
|
+
this.deliveryContext = context;
|
|
413
|
+
this.closing = false;
|
|
414
|
+
this.presentationGeneration += 1;
|
|
415
|
+
this.state = 'connecting';
|
|
416
|
+
this.progressPresenter.bindJournal(context.progressJournal, this.progressCredentialFingerprint);
|
|
417
|
+
let recovery;
|
|
418
|
+
let recoveryTimer;
|
|
419
|
+
const recover = () => {
|
|
420
|
+
if (recovery !== undefined || this.closing
|
|
421
|
+
|| (this.state !== 'connected' && this.state !== 'connected-with-gap'))
|
|
422
|
+
return;
|
|
423
|
+
recovery = this.progressPresenter.recover(this.channel, this.account)
|
|
424
|
+
.catch(error => this.recordPresentationFailure(error))
|
|
425
|
+
.finally(() => { recovery = undefined; });
|
|
426
|
+
};
|
|
427
|
+
const unsubscribe = this.transport.subscribe({
|
|
428
|
+
message: async (message) => {
|
|
429
|
+
// A reply to a live question card is already an explicit interaction
|
|
430
|
+
// with the bot. Lark does not necessarily mark that reply as an @mention,
|
|
431
|
+
// so let only this narrowly identified candidate pass normalization's
|
|
432
|
+
// group mention gate. If the full owner/route/message fences below do
|
|
433
|
+
// not accept it as an answer, ignore it instead of enqueueing a turn.
|
|
434
|
+
const unmentionedQuestionReply = message.chatType === 'group'
|
|
435
|
+
&& this.config.requireMentionInGroups
|
|
436
|
+
&& !message.mentionedBot
|
|
437
|
+
&& message.replyToMessageId !== undefined
|
|
438
|
+
&& [...this.pendingUserQuestions.values()].some(pending => pending.providerMessageId === message.replyToMessageId);
|
|
439
|
+
const normalized = normalizeLarkMessage(unmentionedQuestionReply
|
|
440
|
+
? { ...this.config, requireMentionInGroups: false }
|
|
441
|
+
: this.config, message, this.now());
|
|
442
|
+
if (normalized.outcome !== 'accept') {
|
|
443
|
+
// An unaddressed group message is still a metadata-only intake
|
|
444
|
+
// observation; stale and empty events are not.
|
|
445
|
+
if (normalized.reason === 'bot-mention-required')
|
|
446
|
+
this.observeIntake(context, message, false);
|
|
447
|
+
return;
|
|
448
|
+
}
|
|
449
|
+
if (await this.tryAnswerUserQuestion(normalized.envelope, message.messageId))
|
|
450
|
+
return;
|
|
451
|
+
if (this.tryAnswerToolApproval(normalized.envelope, message.messageId))
|
|
452
|
+
return;
|
|
453
|
+
if (unmentionedQuestionReply)
|
|
454
|
+
return;
|
|
455
|
+
this.observeIntake(context, message, message.chatType === 'p2p' || message.mentionedBot
|
|
456
|
+
|| normalized.envelope.kind === 'command', normalized.envelope.text);
|
|
457
|
+
const accepted = await context.accept(normalized.envelope);
|
|
458
|
+
if (this.statusReactions && !accepted.duplicate && accepted.status === 'queued') {
|
|
459
|
+
// The durable Inbox acknowledgement is the critical path. A slow or
|
|
460
|
+
// unavailable reaction endpoint must not hold the WebSocket handler open.
|
|
461
|
+
void this.addReaction(message.messageId, 'Get');
|
|
462
|
+
}
|
|
463
|
+
},
|
|
464
|
+
cardAction: async (action) => this.handleCardAction(action),
|
|
465
|
+
readReceipt: receipt => this.forwardReadReceipt(receipt),
|
|
466
|
+
reconnecting: () => {
|
|
467
|
+
this.cancelPendingToolApprovals('unavailable');
|
|
468
|
+
this.gapGeneration += 1;
|
|
469
|
+
this.leaveConnected('reconnecting');
|
|
470
|
+
},
|
|
471
|
+
reconnected: () => {
|
|
472
|
+
this.state = 'connected-with-gap';
|
|
473
|
+
this.onConnected?.();
|
|
474
|
+
recover();
|
|
475
|
+
},
|
|
476
|
+
error: error => {
|
|
477
|
+
this.lastErrorCode = error.code;
|
|
478
|
+
if (error.code === 'not_connected') {
|
|
479
|
+
this.leaveConnected('disconnected');
|
|
480
|
+
this.cancelPendingToolApprovals('unavailable');
|
|
481
|
+
}
|
|
482
|
+
},
|
|
483
|
+
});
|
|
484
|
+
try {
|
|
485
|
+
await this.transport.connect();
|
|
486
|
+
this.state = 'connected';
|
|
487
|
+
this.onConnected?.();
|
|
488
|
+
recover();
|
|
489
|
+
recoveryTimer = setInterval(recover, 10_000);
|
|
490
|
+
recoveryTimer.unref?.();
|
|
491
|
+
}
|
|
492
|
+
catch (error) {
|
|
493
|
+
if (this.deliveryContext === context)
|
|
494
|
+
this.deliveryContext = undefined;
|
|
495
|
+
this.progressPresenter.stop();
|
|
496
|
+
unsubscribe();
|
|
497
|
+
this.state = 'disconnected';
|
|
498
|
+
this.cancelPendingToolApprovals('unavailable', true);
|
|
499
|
+
this.cancelPendingUserQuestions();
|
|
500
|
+
await this.transport.disconnect().catch(() => { });
|
|
501
|
+
throw error;
|
|
502
|
+
}
|
|
503
|
+
let active = true;
|
|
504
|
+
return async () => {
|
|
505
|
+
if (!active)
|
|
506
|
+
return;
|
|
507
|
+
active = false;
|
|
508
|
+
if (recoveryTimer !== undefined)
|
|
509
|
+
clearInterval(recoveryTimer);
|
|
510
|
+
this.progressPresenter.stop();
|
|
511
|
+
unsubscribe();
|
|
512
|
+
this.leaveConnected('disconnected');
|
|
513
|
+
this.cancelPendingToolApprovals('unavailable', true);
|
|
514
|
+
this.cancelPendingUserQuestions();
|
|
515
|
+
this.clearUserQuestionAnswerEvents();
|
|
516
|
+
this.cancelModelSelectionUpdates();
|
|
517
|
+
this.pendingAttachmentSends.clear();
|
|
518
|
+
if (this.deliveryContext === context)
|
|
519
|
+
this.deliveryContext = undefined;
|
|
520
|
+
this.closing = true;
|
|
521
|
+
await this.drainToolApprovalUpdates();
|
|
522
|
+
await this.transport.disconnect();
|
|
523
|
+
if (recovery !== undefined) {
|
|
524
|
+
let timer;
|
|
525
|
+
try {
|
|
526
|
+
await Promise.race([recovery, new Promise(resolve => {
|
|
527
|
+
timer = setTimeout(resolve, 5_000);
|
|
528
|
+
timer.unref?.();
|
|
529
|
+
})]);
|
|
530
|
+
}
|
|
531
|
+
finally {
|
|
532
|
+
if (timer !== undefined)
|
|
533
|
+
clearTimeout(timer);
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
};
|
|
537
|
+
}
|
|
538
|
+
/**
|
|
539
|
+
* WP20 intake: hand Delivery an observation (ids, booleans, a sha256 digest
|
|
540
|
+
* and the transient normalized text the digest covers). Optional on older
|
|
541
|
+
* Delivery cores and never allowed to affect acceptance.
|
|
542
|
+
*/
|
|
543
|
+
/**
|
|
544
|
+
* Best-effort read acknowledgement for bot-authored DM messages.
|
|
545
|
+
*
|
|
546
|
+
* Delivery owns the monotonic receipt state; an unknown provider id (for
|
|
547
|
+
* example a message the bot sent before this process) is expected and must
|
|
548
|
+
* not escape the WebSocket handler. Duplicate ids in one event are collapsed.
|
|
549
|
+
*/
|
|
550
|
+
forwardReadReceipt(receipt) {
|
|
551
|
+
const context = this.deliveryContext;
|
|
552
|
+
if (context === undefined)
|
|
553
|
+
return;
|
|
554
|
+
for (const messageId of new Set(receipt.messageIds)) {
|
|
555
|
+
void context.receipt({ channel: 'lark', account: this.account, providerMessageId: messageId,
|
|
556
|
+
status: 'read', occurredAt: receipt.readAt }).catch(() => {
|
|
557
|
+
// Receipt mismatch/conflict is a Delivery-side no-op for this adapter.
|
|
558
|
+
});
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
observeIntake(context, message, addressed, text) {
|
|
562
|
+
if (typeof context.observe !== 'function')
|
|
563
|
+
return;
|
|
564
|
+
try {
|
|
565
|
+
const normalized = text ?? message.content.replaceAll('\r\n', '\n').trim();
|
|
566
|
+
context.observe({
|
|
567
|
+
eventId: message.messageId,
|
|
568
|
+
occurredAt: message.createTime,
|
|
569
|
+
principal: { channel: 'lark', account: this.config.account, tenant: this.config.tenant, user: message.senderId },
|
|
570
|
+
conversation: { kind: message.chatType === 'p2p' ? 'dm' : 'group', chat: message.chatId },
|
|
571
|
+
addressed,
|
|
572
|
+
// The transport reports Feishu's provider-declared sender type; older
|
|
573
|
+
// transports omit it and are treated as user senders.
|
|
574
|
+
senderIsBot: message.senderIsBot === true,
|
|
575
|
+
...(message.replyToMessageId === undefined ? {} : { replyToProviderMessageId: message.replyToMessageId }),
|
|
576
|
+
// `text` is transient: Delivery forwards it only to an opted-in observer and never stores it.
|
|
577
|
+
...(normalized.length === 0 ? {} : { contentDigest: createHash('sha256').update(normalized, 'utf8').digest('hex'), text: normalized }),
|
|
578
|
+
});
|
|
579
|
+
}
|
|
580
|
+
catch { /* observation is best-effort */ }
|
|
581
|
+
}
|
|
582
|
+
health() {
|
|
583
|
+
return {
|
|
584
|
+
state: this.state,
|
|
585
|
+
gapGeneration: this.gapGeneration,
|
|
586
|
+
...(this.lastErrorCode === undefined ? {} : { lastErrorCode: this.lastErrorCode }),
|
|
587
|
+
};
|
|
588
|
+
}
|
|
589
|
+
leaveConnected(next) {
|
|
590
|
+
const wasConnected = this.state === 'connected' || this.state === 'connected-with-gap';
|
|
591
|
+
this.state = next;
|
|
592
|
+
if (wasConnected)
|
|
593
|
+
this.onDisconnected?.();
|
|
594
|
+
}
|
|
595
|
+
async progress(intent) {
|
|
596
|
+
if (!this.matchesTarget(intent.target))
|
|
597
|
+
return;
|
|
598
|
+
await this.progressPresenter.publish(intent);
|
|
599
|
+
}
|
|
600
|
+
async requestToolApproval(input, signal) {
|
|
601
|
+
if (signal.aborted)
|
|
602
|
+
return 'cancelled';
|
|
603
|
+
if (!hasUsableApprovalSecret(this.approvalSecret)
|
|
604
|
+
|| (this.state !== 'connected' && this.state !== 'connected-with-gap')
|
|
605
|
+
|| !this.matchesTarget(input.target)
|
|
606
|
+
|| !larkCallbackIdentifier.test(input.target.conversation.chat)
|
|
607
|
+
|| !larkCallbackIdentifier.test(input.target.principal.user)
|
|
608
|
+
|| input.target.conversation.kind !== 'dm'
|
|
609
|
+
|| input.target.conversation.thread !== undefined
|
|
610
|
+
|| typeof input.callId !== 'string'
|
|
611
|
+
|| typeof input.arguments !== 'string'
|
|
612
|
+
|| !boundedReviewText(input.reason, LARK_TOOL_APPROVAL_REASON_MAX_BYTES)
|
|
613
|
+
|| !boundedReviewText(input.arguments, LARK_TOOL_APPROVAL_ARGUMENTS_MAX_BYTES)) {
|
|
614
|
+
return 'unavailable';
|
|
615
|
+
}
|
|
616
|
+
let now;
|
|
617
|
+
try {
|
|
618
|
+
now = this.now();
|
|
619
|
+
}
|
|
620
|
+
catch {
|
|
621
|
+
return 'unavailable';
|
|
622
|
+
}
|
|
623
|
+
if (!Number.isSafeInteger(now) || now < 0 || !Number.isSafeInteger(input.expiresAt)
|
|
624
|
+
|| !Number.isSafeInteger(input.expiresAt - now) || now >= input.expiresAt) {
|
|
625
|
+
return 'unavailable';
|
|
626
|
+
}
|
|
627
|
+
const previousTombstone = this.toolApprovalTombstones.get(input.operationId);
|
|
628
|
+
if (previousTombstone !== undefined) {
|
|
629
|
+
if (now < previousTombstone.expiresAt)
|
|
630
|
+
return 'unavailable';
|
|
631
|
+
const expiredPending = this.pendingToolApprovals.get(input.operationId);
|
|
632
|
+
if (expiredPending !== undefined)
|
|
633
|
+
this.settleToolApproval(expiredPending, 'unavailable', 'expired');
|
|
634
|
+
this.deleteToolApprovalTombstone(input.operationId, previousTombstone);
|
|
635
|
+
}
|
|
636
|
+
const payload = {
|
|
637
|
+
version: 1,
|
|
638
|
+
channel: this.channel,
|
|
639
|
+
account: this.account,
|
|
640
|
+
tenant: this.config.tenant,
|
|
641
|
+
operationId: input.operationId,
|
|
642
|
+
bindingId: input.bindingId,
|
|
643
|
+
chatId: input.target.conversation.chat,
|
|
644
|
+
ownerUser: input.target.principal.user,
|
|
645
|
+
actionHash: input.actionHash,
|
|
646
|
+
toolName: input.toolName,
|
|
647
|
+
callId: input.callId,
|
|
648
|
+
expiresAt: input.expiresAt,
|
|
649
|
+
};
|
|
650
|
+
let card;
|
|
651
|
+
try {
|
|
652
|
+
card = { toolApproval: {
|
|
653
|
+
title: '工具调用需要确认',
|
|
654
|
+
toolName: input.toolName,
|
|
655
|
+
...(input.reason === undefined ? {} : { reason: input.reason }),
|
|
656
|
+
arguments: input.arguments,
|
|
657
|
+
allowValue: { toolApproval: signLarkToolApprovalAction(this.approvalSecret, { ...payload, decision: 'allowed-once' }) },
|
|
658
|
+
rejectValue: { toolApproval: signLarkToolApprovalAction(this.approvalSecret, { ...payload, decision: 'rejected' }) },
|
|
659
|
+
} };
|
|
660
|
+
if (Buffer.byteLength(renderLarkMessage(card).content, 'utf8') > LARK_APPROVAL_CARD_MAX_BYTES) {
|
|
661
|
+
return 'unavailable';
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
catch {
|
|
665
|
+
return 'unavailable';
|
|
666
|
+
}
|
|
667
|
+
let resolve;
|
|
668
|
+
const outcome = new Promise(settle => { resolve = settle; });
|
|
669
|
+
let pending;
|
|
670
|
+
const abort = () => {
|
|
671
|
+
let status = 'cancelled';
|
|
672
|
+
try {
|
|
673
|
+
const abortedAt = this.now();
|
|
674
|
+
if (Number.isSafeInteger(abortedAt) && abortedAt >= payload.expiresAt)
|
|
675
|
+
status = 'expired';
|
|
676
|
+
}
|
|
677
|
+
catch { /* A failed clock cannot establish expiry. */ }
|
|
678
|
+
this.settleToolApproval(pending, 'cancelled', status);
|
|
679
|
+
};
|
|
680
|
+
pending = { payload, signal, abort, resolve, presentationGeneration: this.presentationGeneration };
|
|
681
|
+
const tombstone = { expiresAt: input.expiresAt };
|
|
682
|
+
this.pendingToolApprovals.set(input.operationId, pending);
|
|
683
|
+
this.toolApprovalTombstones.set(input.operationId, tombstone);
|
|
684
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
685
|
+
if (signal.aborted) {
|
|
686
|
+
this.settleToolApproval(pending, 'cancelled');
|
|
687
|
+
return outcome;
|
|
688
|
+
}
|
|
689
|
+
this.armToolApprovalTombstone(input.operationId, tombstone);
|
|
690
|
+
if (this.pendingToolApprovals.get(input.operationId) !== pending)
|
|
691
|
+
return outcome;
|
|
692
|
+
const sendOptions = {
|
|
693
|
+
requestKey: `tool-approval:${input.operationId}:${input.actionHash}`,
|
|
694
|
+
};
|
|
695
|
+
try {
|
|
696
|
+
const result = await this.transport.send(input.target.conversation.chat, card, sendOptions);
|
|
697
|
+
if (this.pendingToolApprovals.get(input.operationId) !== pending) {
|
|
698
|
+
if (larkProviderMessageIdentifier.test(result.messageId) && pending.resultStatus !== undefined) {
|
|
699
|
+
pending.providerMessageId = result.messageId;
|
|
700
|
+
this.updateToolApprovalResult(pending, pending.resultStatus);
|
|
701
|
+
}
|
|
702
|
+
return await outcome;
|
|
703
|
+
}
|
|
704
|
+
if (!larkProviderMessageIdentifier.test(result.messageId)) {
|
|
705
|
+
this.settleToolApproval(pending, 'unavailable');
|
|
706
|
+
return await outcome;
|
|
707
|
+
}
|
|
708
|
+
pending.providerMessageId = result.messageId;
|
|
709
|
+
const earlyAction = pending.earlyAction;
|
|
710
|
+
delete pending.earlyAction;
|
|
711
|
+
if (earlyAction?.messageId === result.messageId) {
|
|
712
|
+
this.settleToolApproval(pending, earlyAction.decision);
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
catch (error) {
|
|
716
|
+
this.recordPresentationFailure(error);
|
|
717
|
+
if (error instanceof LarkTransportError && error.code === 'format_error'
|
|
718
|
+
&& this.pendingToolApprovals.get(input.operationId) === pending) {
|
|
719
|
+
try {
|
|
720
|
+
const fallback = await this.transport.send(input.target.conversation.chat, { text: `工具调用需要确认\n工具:${input.toolName}\n理由:${input.reason ?? '(未提供)'}\n参数:${input.arguments}\n\n` + '请直接回复“允许一次”或“拒绝”。仅当本私聊中恰好有一个待审批操作时,文字回复才会生效。' }, {
|
|
721
|
+
requestKey: `${sendOptions.requestKey}:text-fallback`,
|
|
722
|
+
});
|
|
723
|
+
if (larkProviderMessageIdentifier.test(fallback.messageId)) {
|
|
724
|
+
pending.textFallback = true;
|
|
725
|
+
pending.providerMessageId = fallback.messageId;
|
|
726
|
+
return await outcome;
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
catch (fallbackError) {
|
|
730
|
+
this.recordPresentationFailure(fallbackError);
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
this.settleToolApproval(pending, 'unavailable');
|
|
734
|
+
}
|
|
735
|
+
return await outcome;
|
|
736
|
+
}
|
|
737
|
+
async requestUserQuestion(input, signal) {
|
|
738
|
+
if (signal.aborted
|
|
739
|
+
|| !hasUsableApprovalSecret(this.approvalSecret)
|
|
740
|
+
|| (this.state !== 'connected' && this.state !== 'connected-with-gap')
|
|
741
|
+
|| !this.matchesTarget(input.target)
|
|
742
|
+
|| !larkCallbackIdentifier.test(input.target.conversation.chat)
|
|
743
|
+
|| !larkCallbackIdentifier.test(input.target.principal.user)
|
|
744
|
+
|| !validUserQuestionRequest(input)) {
|
|
745
|
+
return { outcome: 'unavailable' };
|
|
746
|
+
}
|
|
747
|
+
let now;
|
|
748
|
+
try {
|
|
749
|
+
now = this.now();
|
|
750
|
+
}
|
|
751
|
+
catch {
|
|
752
|
+
return { outcome: 'unavailable' };
|
|
753
|
+
}
|
|
754
|
+
const expiresAt = now + this.userQuestionTtlMs;
|
|
755
|
+
if (!Number.isSafeInteger(now) || now < 0
|
|
756
|
+
|| !Number.isSafeInteger(this.userQuestionTtlMs) || this.userQuestionTtlMs < 1
|
|
757
|
+
|| !Number.isSafeInteger(expiresAt)) {
|
|
758
|
+
return { outcome: 'unavailable' };
|
|
759
|
+
}
|
|
760
|
+
const requestHash = createHash('sha256')
|
|
761
|
+
.update(JSON.stringify(input.questions), 'utf8')
|
|
762
|
+
.digest('hex');
|
|
763
|
+
const existing = this.pendingUserQuestions.get(input.operationId);
|
|
764
|
+
if (existing !== undefined) {
|
|
765
|
+
return existing.requestHash === requestHash
|
|
766
|
+
&& existing.input.sessionId === input.sessionId
|
|
767
|
+
&& existing.input.bindingId === input.bindingId
|
|
768
|
+
&& existing.input.bindingVersion === input.bindingVersion
|
|
769
|
+
&& existing.input.bindingGeneration === input.bindingGeneration
|
|
770
|
+
&& samePrincipal(existing.input.target.principal, input.target.principal)
|
|
771
|
+
&& sameConversation(existing.input.target.conversation, input.target.conversation)
|
|
772
|
+
? existing.outcome
|
|
773
|
+
: { outcome: 'unavailable' };
|
|
774
|
+
}
|
|
775
|
+
let resolve;
|
|
776
|
+
const outcome = new Promise(settle => { resolve = settle; });
|
|
777
|
+
let pending;
|
|
778
|
+
const abort = () => {
|
|
779
|
+
this.settleUserQuestion(pending, { outcome: 'unavailable' }, 'resolved', true);
|
|
780
|
+
};
|
|
781
|
+
pending = {
|
|
782
|
+
input,
|
|
783
|
+
payload: {
|
|
784
|
+
version: 1,
|
|
785
|
+
channel: this.channel,
|
|
786
|
+
account: this.account,
|
|
787
|
+
tenant: this.config.tenant,
|
|
788
|
+
rpcId: input.operationId,
|
|
789
|
+
sessionId: input.sessionId,
|
|
790
|
+
bindingId: input.bindingId,
|
|
791
|
+
bindingVersion: input.bindingVersion,
|
|
792
|
+
bindingGeneration: input.bindingGeneration,
|
|
793
|
+
chatId: input.target.conversation.chat,
|
|
794
|
+
ownerUser: input.target.principal.user,
|
|
795
|
+
requestHash,
|
|
796
|
+
expiresAt,
|
|
797
|
+
},
|
|
798
|
+
requestHash,
|
|
799
|
+
signal,
|
|
800
|
+
abort,
|
|
801
|
+
resolve,
|
|
802
|
+
outcome,
|
|
803
|
+
answers: [],
|
|
804
|
+
selectedOptionIndexes: new Set(),
|
|
805
|
+
questionIndex: 0,
|
|
806
|
+
revision: 0,
|
|
807
|
+
};
|
|
808
|
+
let card;
|
|
809
|
+
try {
|
|
810
|
+
card = { userQuestion: this.userQuestionCard(pending) };
|
|
811
|
+
if (Buffer.byteLength(renderLarkMessage(card).content, 'utf8') > LARK_APPROVAL_CARD_MAX_BYTES) {
|
|
812
|
+
return { outcome: 'unavailable' };
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
catch {
|
|
816
|
+
return { outcome: 'unavailable' };
|
|
817
|
+
}
|
|
818
|
+
this.pendingUserQuestions.set(input.operationId, pending);
|
|
819
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
820
|
+
if (signal.aborted) {
|
|
821
|
+
this.settleUserQuestion(pending, { outcome: 'unavailable' }, 'resolved', false);
|
|
822
|
+
return outcome;
|
|
823
|
+
}
|
|
824
|
+
this.armUserQuestionExpiry(pending);
|
|
825
|
+
let sending;
|
|
826
|
+
try {
|
|
827
|
+
sending = Promise.resolve(this.transport.send(input.target.conversation.chat, card, this.userQuestionSendOptions(pending)));
|
|
828
|
+
}
|
|
829
|
+
catch (error) {
|
|
830
|
+
this.recordPresentationFailure(error);
|
|
831
|
+
this.settleUserQuestion(pending, { outcome: 'unavailable' }, 'resolved', false);
|
|
832
|
+
return outcome;
|
|
833
|
+
}
|
|
834
|
+
void sending.then(result => {
|
|
835
|
+
if (this.pendingUserQuestions.get(input.operationId) !== pending)
|
|
836
|
+
return;
|
|
837
|
+
if (!larkProviderMessageIdentifier.test(result.messageId)) {
|
|
838
|
+
this.settleUserQuestion(pending, { outcome: 'unavailable' }, 'resolved', false);
|
|
839
|
+
return;
|
|
840
|
+
}
|
|
841
|
+
pending.providerMessageId = result.messageId;
|
|
842
|
+
}, error => {
|
|
843
|
+
this.recordPresentationFailure(error);
|
|
844
|
+
this.settleUserQuestion(pending, { outcome: 'unavailable' }, 'resolved', false);
|
|
845
|
+
});
|
|
846
|
+
return outcome;
|
|
847
|
+
}
|
|
848
|
+
async readInboundImage(input, signal) {
|
|
849
|
+
if (input.attachment.resourceType !== 'image') {
|
|
850
|
+
return { outcome: 'not-downloaded', failureCode: 'lark-image-type-unsupported', retryable: false };
|
|
851
|
+
}
|
|
852
|
+
const identifier = /^[A-Za-z0-9][A-Za-z0-9._@-]{0,255}$/u;
|
|
853
|
+
if (!identifier.test(input.eventId) || !identifier.test(input.attachment.providerRef)
|
|
854
|
+
|| !Number.isSafeInteger(input.maxBytes) || input.maxBytes < 1) {
|
|
855
|
+
return { outcome: 'not-downloaded', failureCode: 'lark-image-reference-invalid', retryable: false };
|
|
856
|
+
}
|
|
857
|
+
if (signal.aborted) {
|
|
858
|
+
return { outcome: 'not-downloaded', failureCode: 'lark-image-aborted', retryable: true };
|
|
859
|
+
}
|
|
860
|
+
const download = this.transport.downloadMessageImage;
|
|
861
|
+
if (typeof download !== 'function') {
|
|
862
|
+
return { outcome: 'not-downloaded', failureCode: 'lark-image-download-unavailable', retryable: false };
|
|
863
|
+
}
|
|
864
|
+
try {
|
|
865
|
+
const image = await download.call(this.transport, input.eventId, input.attachment.providerRef, { maxBytes: input.maxBytes, signal });
|
|
866
|
+
if (signal.aborted) {
|
|
867
|
+
return { outcome: 'not-downloaded', failureCode: 'lark-image-aborted', retryable: true };
|
|
868
|
+
}
|
|
869
|
+
return {
|
|
870
|
+
outcome: 'downloaded',
|
|
871
|
+
data: image.data,
|
|
872
|
+
mediaType: image.mediaType,
|
|
873
|
+
};
|
|
874
|
+
}
|
|
875
|
+
catch (error) {
|
|
876
|
+
if (signal.aborted) {
|
|
877
|
+
return { outcome: 'not-downloaded', failureCode: 'lark-image-aborted', retryable: true };
|
|
878
|
+
}
|
|
879
|
+
const code = error instanceof LarkTransportError ? error.code : 'unknown';
|
|
880
|
+
const retryable = code !== 'format_error' && code !== 'permission_denied' && code !== 'target_revoked';
|
|
881
|
+
return {
|
|
882
|
+
outcome: 'not-downloaded',
|
|
883
|
+
failureCode: `lark-image-${code.replaceAll('_', '-')}`,
|
|
884
|
+
retryable,
|
|
885
|
+
...(error instanceof LarkTransportError && error.retryAfterMs !== undefined
|
|
886
|
+
? { retryAfterMs: error.retryAfterMs }
|
|
887
|
+
: {}),
|
|
888
|
+
};
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
async send(intent, signal) {
|
|
892
|
+
const conversation = intent.target.conversation;
|
|
893
|
+
if (!this.matchesTarget(intent.target)) {
|
|
894
|
+
return { outcome: 'not-sent', failureCode: 'lark-route-mismatch', retryable: false };
|
|
895
|
+
}
|
|
896
|
+
if (signal.aborted)
|
|
897
|
+
return { outcome: 'not-sent', failureCode: 'lark-aborted', retryable: true };
|
|
898
|
+
const syntheticTopLevelGroup = conversation.kind === 'group'
|
|
899
|
+
&& isLarkTopLevelSenderThread(conversation.thread);
|
|
900
|
+
const topicGroup = conversation.kind === 'group' && isLarkTopicThread(conversation.thread);
|
|
901
|
+
const providerReplyTarget = topicGroup
|
|
902
|
+
? intent.replyToEventId
|
|
903
|
+
: syntheticTopLevelGroup
|
|
904
|
+
? undefined
|
|
905
|
+
: (intent.replyToEventId
|
|
906
|
+
?? (conversation.kind === 'group' ? conversation.thread : undefined));
|
|
907
|
+
const baseOptions = {
|
|
908
|
+
...(providerReplyTarget === undefined ? {} : { replyTo: providerReplyTarget }),
|
|
909
|
+
...(conversation.kind === 'group' && providerReplyTarget !== undefined ? { replyInThread: true } : {}),
|
|
910
|
+
};
|
|
911
|
+
if (intent.attachment !== undefined) {
|
|
912
|
+
return await this.sendWithAttachment(intent, baseOptions, signal);
|
|
913
|
+
}
|
|
914
|
+
const useMarkdownCard = intent.format === 'markdown';
|
|
915
|
+
let input;
|
|
916
|
+
if (intent.format === 'approval') {
|
|
917
|
+
if (intent.approval === undefined || this.approvalSecret === undefined || this.settleApproval === undefined) {
|
|
918
|
+
return { outcome: 'not-sent', failureCode: 'lark-approval-unavailable', retryable: false };
|
|
919
|
+
}
|
|
920
|
+
if (Buffer.byteLength(intent.text, 'utf8') > this.config.maxTextBytes) {
|
|
921
|
+
return { outcome: 'not-sent', failureCode: 'lark-approval-too-large', retryable: false };
|
|
922
|
+
}
|
|
923
|
+
if (createHash('sha256').update(intent.text).digest('hex') !== intent.approval.diffHash) {
|
|
924
|
+
return { outcome: 'not-sent', failureCode: 'lark-approval-diff-mismatch', retryable: false };
|
|
925
|
+
}
|
|
926
|
+
if (this.now() >= intent.approval.expiresAt) {
|
|
927
|
+
return { outcome: 'not-sent', failureCode: 'lark-approval-expired', retryable: false };
|
|
928
|
+
}
|
|
929
|
+
const common = {
|
|
930
|
+
version: 2,
|
|
931
|
+
channel: conversation.channel,
|
|
932
|
+
account: conversation.account,
|
|
933
|
+
tenant: conversation.tenant,
|
|
934
|
+
operationId: intent.approval.operationId,
|
|
935
|
+
bindingId: intent.bindingId,
|
|
936
|
+
proposalId: intent.approval.proposalId,
|
|
937
|
+
expectedVersion: intent.approval.expectedVersion,
|
|
938
|
+
expiresAt: intent.approval.expiresAt,
|
|
939
|
+
chatId: conversation.chat,
|
|
940
|
+
diffHash: intent.approval.diffHash,
|
|
941
|
+
};
|
|
942
|
+
input = { approval: {
|
|
943
|
+
title: intent.approval.title,
|
|
944
|
+
body: intent.text,
|
|
945
|
+
approveValue: { approval: signLarkApprovalAction(this.approvalSecret, { ...common, decision: 'approved' }) },
|
|
946
|
+
rejectValue: { approval: signLarkApprovalAction(this.approvalSecret, { ...common, decision: 'rejected' }) },
|
|
947
|
+
} };
|
|
948
|
+
if (Buffer.byteLength(renderLarkMessage(input).content, 'utf8') > LARK_APPROVAL_CARD_MAX_BYTES) {
|
|
949
|
+
return { outcome: 'not-sent', failureCode: 'lark-approval-too-large', retryable: false };
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
else if (intent.format === 'permission-picker') {
|
|
953
|
+
if (intent.permissionPicker === undefined || this.approvalSecret === undefined
|
|
954
|
+
|| this.settlePermissionSelection === undefined) {
|
|
955
|
+
return { outcome: 'not-sent', failureCode: 'lark-permission-picker-unavailable', retryable: false };
|
|
956
|
+
}
|
|
957
|
+
if (this.now() >= intent.permissionPicker.expiresAt) {
|
|
958
|
+
return { outcome: 'not-sent', failureCode: 'lark-permission-picker-expired', retryable: false };
|
|
959
|
+
}
|
|
960
|
+
input = { permissionPicker: permissionPickerCard(intent.permissionPicker, this.approvalSecret, {
|
|
961
|
+
channel: conversation.channel,
|
|
962
|
+
account: conversation.account,
|
|
963
|
+
tenant: conversation.tenant,
|
|
964
|
+
bindingId: intent.bindingId,
|
|
965
|
+
chatId: conversation.chat,
|
|
966
|
+
ownerUser: intent.target.principal.user,
|
|
967
|
+
}) };
|
|
968
|
+
}
|
|
969
|
+
else if (intent.format === 'model-picker') {
|
|
970
|
+
if (intent.modelPicker === undefined || this.approvalSecret === undefined
|
|
971
|
+
|| this.settleModelSelection === undefined || this.loadModelPicker === undefined
|
|
972
|
+
|| this.advanceModelPicker === undefined) {
|
|
973
|
+
return { outcome: 'not-sent', failureCode: 'lark-model-picker-unavailable', retryable: false };
|
|
974
|
+
}
|
|
975
|
+
if (this.now() >= intent.modelPicker.expiresAt) {
|
|
976
|
+
return { outcome: 'not-sent', failureCode: 'lark-model-picker-expired', retryable: false };
|
|
977
|
+
}
|
|
978
|
+
const picker = intent.modelPicker;
|
|
979
|
+
input = { modelPicker: modelPickerCard(picker, this.approvalSecret, {
|
|
980
|
+
operationId: picker.operationId,
|
|
981
|
+
bindingId: intent.bindingId,
|
|
982
|
+
expiresAt: picker.expiresAt,
|
|
983
|
+
chatId: conversation.chat,
|
|
984
|
+
revision: 0,
|
|
985
|
+
}) };
|
|
986
|
+
}
|
|
987
|
+
else if (useMarkdownCard) {
|
|
988
|
+
input = { markdown: intent.text };
|
|
989
|
+
}
|
|
990
|
+
else {
|
|
991
|
+
const commandCard = tryBuildLarkCommandCard(intent.text);
|
|
992
|
+
if (commandCard !== undefined) {
|
|
993
|
+
const candidate = { commandCard };
|
|
994
|
+
input = Buffer.byteLength(renderLarkMessage(candidate).content, 'utf8') <= LARK_APPROVAL_CARD_MAX_BYTES
|
|
995
|
+
? candidate
|
|
996
|
+
: { text: intent.text };
|
|
997
|
+
}
|
|
998
|
+
else {
|
|
999
|
+
input = { text: intent.text };
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
const options = {
|
|
1003
|
+
requestKey: intent.idempotencyKey,
|
|
1004
|
+
...baseOptions,
|
|
1005
|
+
};
|
|
1006
|
+
let result;
|
|
1007
|
+
try {
|
|
1008
|
+
result = await this.transport.send(conversation.chat, input, options);
|
|
1009
|
+
}
|
|
1010
|
+
catch (error) {
|
|
1011
|
+
if (!(error instanceof LarkTransportError) || error.code !== 'format_error') {
|
|
1012
|
+
return sendFailure(error);
|
|
1013
|
+
}
|
|
1014
|
+
// Agent-authored Markdown can be valid for DSH yet contain a construct the current Lark
|
|
1015
|
+
// card parser rejects. The answer is already durable at this boundary, so preserve it with
|
|
1016
|
+
// a text message instead of dead-lettering the only user-visible result.
|
|
1017
|
+
const fallback = useMarkdownCard
|
|
1018
|
+
? { text: intent.text, suffix: 'markdown-fallback' }
|
|
1019
|
+
: 'commandCard' in input
|
|
1020
|
+
? { text: intent.text, suffix: 'command-card-fallback' }
|
|
1021
|
+
: intent.format === 'permission-picker' && intent.permissionPicker !== undefined
|
|
1022
|
+
? { text: intent.text, suffix: 'permission-picker-fallback' }
|
|
1023
|
+
: intent.format === 'model-picker' && intent.modelPicker !== undefined
|
|
1024
|
+
? { text: modelPickerFallbackText(intent), suffix: 'model-picker-fallback' }
|
|
1025
|
+
: undefined;
|
|
1026
|
+
if (fallback === undefined)
|
|
1027
|
+
return sendFailure(error);
|
|
1028
|
+
try {
|
|
1029
|
+
result = await this.transport.send(conversation.chat, { text: fallback.text }, {
|
|
1030
|
+
...options,
|
|
1031
|
+
requestKey: `${intent.idempotencyKey}:${fallback.suffix}`,
|
|
1032
|
+
});
|
|
1033
|
+
}
|
|
1034
|
+
catch (fallbackError) {
|
|
1035
|
+
return sendFailure(fallbackError);
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
if (!larkProviderMessageIdentifier.test(result.messageId)) {
|
|
1039
|
+
return { outcome: 'unknown', failureCode: 'invalid-provider-result' };
|
|
1040
|
+
}
|
|
1041
|
+
this.markSentReaction(intent);
|
|
1042
|
+
return { outcome: 'accepted', providerMessageId: result.messageId };
|
|
1043
|
+
}
|
|
1044
|
+
rememberAttachmentFileMessage(key, messageId) {
|
|
1045
|
+
if (!this.pendingAttachmentSends.has(key)
|
|
1046
|
+
&& this.pendingAttachmentSends.size >= LARK_PENDING_ATTACHMENT_SEND_LIMIT) {
|
|
1047
|
+
const oldest = this.pendingAttachmentSends.keys().next().value;
|
|
1048
|
+
if (oldest !== undefined)
|
|
1049
|
+
this.pendingAttachmentSends.delete(oldest);
|
|
1050
|
+
}
|
|
1051
|
+
this.pendingAttachmentSends.set(key, messageId);
|
|
1052
|
+
}
|
|
1053
|
+
markSentReaction(intent) {
|
|
1054
|
+
// Delivery's durable interruption receipt acknowledges an unknown task outcome,
|
|
1055
|
+
// not a completed task. Keep the original request free of a misleading DONE.
|
|
1056
|
+
const interrupted = intent.idempotencyKey.startsWith('inbound:')
|
|
1057
|
+
&& (intent.idempotencyKey.endsWith(':interrupted') || intent.idempotencyKey.endsWith(':maintenance')
|
|
1058
|
+
|| intent.idempotencyKey.endsWith(':maintenance-failed'));
|
|
1059
|
+
if (this.statusReactions && intent.replyToEventId !== undefined && !interrupted) {
|
|
1060
|
+
void this.addReaction(intent.replyToEventId, 'DONE');
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
async sendWithAttachment(intent, baseOptions, signal) {
|
|
1064
|
+
const maxBytes = Math.min(this.config.maxTextBytes, LARK_TEXT_FILE_MAX_BYTES);
|
|
1065
|
+
const validated = validateOutboundTextAttachment(intent, maxBytes);
|
|
1066
|
+
if (!validated.ok)
|
|
1067
|
+
return validated.failure;
|
|
1068
|
+
const { attachment } = validated;
|
|
1069
|
+
const uploadTextFile = this.transport.uploadTextFile;
|
|
1070
|
+
if (typeof uploadTextFile !== 'function') {
|
|
1071
|
+
return { outcome: 'not-sent', failureCode: 'lark-attachment-upload-unavailable', retryable: false };
|
|
1072
|
+
}
|
|
1073
|
+
const conversation = intent.target.conversation;
|
|
1074
|
+
const summaryDigest = createHash('sha256').update(intent.text, 'utf8').digest('hex');
|
|
1075
|
+
const attachmentSendKey = JSON.stringify([
|
|
1076
|
+
intent.idempotencyKey,
|
|
1077
|
+
conversation.channel,
|
|
1078
|
+
conversation.account,
|
|
1079
|
+
conversation.tenant,
|
|
1080
|
+
conversation.kind,
|
|
1081
|
+
conversation.chat,
|
|
1082
|
+
conversation.thread ?? '',
|
|
1083
|
+
intent.replyToEventId ?? '',
|
|
1084
|
+
summaryDigest,
|
|
1085
|
+
attachment.sha256,
|
|
1086
|
+
]);
|
|
1087
|
+
let fileMessageId = this.pendingAttachmentSends.get(attachmentSendKey);
|
|
1088
|
+
if (fileMessageId === undefined) {
|
|
1089
|
+
let fileKey;
|
|
1090
|
+
try {
|
|
1091
|
+
fileKey = await uploadTextFile.call(this.transport, {
|
|
1092
|
+
name: attachment.name,
|
|
1093
|
+
mediaType: attachment.mediaType,
|
|
1094
|
+
text: attachment.text,
|
|
1095
|
+
maxBytes,
|
|
1096
|
+
signal,
|
|
1097
|
+
});
|
|
1098
|
+
}
|
|
1099
|
+
catch (error) {
|
|
1100
|
+
if (signal.aborted)
|
|
1101
|
+
return { outcome: 'not-sent', failureCode: 'lark-aborted', retryable: true };
|
|
1102
|
+
return uploadFailure(error);
|
|
1103
|
+
}
|
|
1104
|
+
if (signal.aborted)
|
|
1105
|
+
return { outcome: 'not-sent', failureCode: 'lark-aborted', retryable: true };
|
|
1106
|
+
if (typeof fileKey !== 'string' || !larkResourceIdentifier.test(fileKey)) {
|
|
1107
|
+
return { outcome: 'not-sent', failureCode: 'lark-upload-failed', retryable: true };
|
|
1108
|
+
}
|
|
1109
|
+
let fileResult;
|
|
1110
|
+
try {
|
|
1111
|
+
// Send the attachment file before the inline summary so a truncated notice body can never be left without its file.
|
|
1112
|
+
fileResult = await this.transport.send(conversation.chat, { fileKey }, {
|
|
1113
|
+
...baseOptions,
|
|
1114
|
+
requestKey: `${intent.idempotencyKey}:attachment`,
|
|
1115
|
+
signal,
|
|
1116
|
+
});
|
|
1117
|
+
}
|
|
1118
|
+
catch (error) {
|
|
1119
|
+
return sendFailure(error);
|
|
1120
|
+
}
|
|
1121
|
+
if (!larkProviderMessageIdentifier.test(fileResult.messageId)) {
|
|
1122
|
+
return { outcome: 'unknown', failureCode: 'invalid-provider-result' };
|
|
1123
|
+
}
|
|
1124
|
+
fileMessageId = fileResult.messageId;
|
|
1125
|
+
this.rememberAttachmentFileMessage(attachmentSendKey, fileMessageId);
|
|
1126
|
+
}
|
|
1127
|
+
if (signal.aborted) {
|
|
1128
|
+
return { outcome: 'unknown', failureCode: 'lark-aborted', providerMessageId: fileMessageId };
|
|
1129
|
+
}
|
|
1130
|
+
let summaryResult;
|
|
1131
|
+
try {
|
|
1132
|
+
summaryResult = await this.transport.send(conversation.chat, { text: intent.text }, {
|
|
1133
|
+
...baseOptions,
|
|
1134
|
+
requestKey: intent.idempotencyKey,
|
|
1135
|
+
signal,
|
|
1136
|
+
});
|
|
1137
|
+
}
|
|
1138
|
+
catch (error) {
|
|
1139
|
+
if (signal.aborted) {
|
|
1140
|
+
return { outcome: 'unknown', failureCode: 'lark-aborted', providerMessageId: fileMessageId };
|
|
1141
|
+
}
|
|
1142
|
+
const failure = sendFailure(error);
|
|
1143
|
+
if (failure.outcome === 'not-sent' && failure.retryable)
|
|
1144
|
+
return failure;
|
|
1145
|
+
return {
|
|
1146
|
+
outcome: 'unknown',
|
|
1147
|
+
failureCode: failure.failureCode,
|
|
1148
|
+
providerMessageId: fileMessageId,
|
|
1149
|
+
};
|
|
1150
|
+
}
|
|
1151
|
+
if (!larkProviderMessageIdentifier.test(summaryResult.messageId)) {
|
|
1152
|
+
return { outcome: 'unknown', failureCode: 'invalid-provider-result', providerMessageId: fileMessageId };
|
|
1153
|
+
}
|
|
1154
|
+
this.pendingAttachmentSends.delete(attachmentSendKey);
|
|
1155
|
+
this.markSentReaction(intent);
|
|
1156
|
+
return { outcome: 'accepted', providerMessageId: summaryResult.messageId };
|
|
1157
|
+
}
|
|
1158
|
+
async updatePresentation(providerMessageId, presentation, signal) {
|
|
1159
|
+
if (signal.aborted)
|
|
1160
|
+
throw signal.reason;
|
|
1161
|
+
const update = this.transport.updateRawCard;
|
|
1162
|
+
if (update === undefined)
|
|
1163
|
+
throw new Error('Lark transport does not support card replacement');
|
|
1164
|
+
if (presentation.kind === 'automation-incident') {
|
|
1165
|
+
await update.call(this.transport, providerMessageId, rawCard({
|
|
1166
|
+
automationIncident: presentation,
|
|
1167
|
+
}), signal);
|
|
1168
|
+
return;
|
|
1169
|
+
}
|
|
1170
|
+
if (presentation.kind !== 'approval-application') {
|
|
1171
|
+
throw new Error('Lark presentation kind is unsupported');
|
|
1172
|
+
}
|
|
1173
|
+
await update.call(this.transport, providerMessageId, rawCard({
|
|
1174
|
+
approvalApplication: {
|
|
1175
|
+
status: presentation.applicationStatus,
|
|
1176
|
+
operation: presentation.operation,
|
|
1177
|
+
policyProposalId: presentation.policyProposalId,
|
|
1178
|
+
localProposalId: presentation.localProposalId,
|
|
1179
|
+
terminalAt: presentation.terminalAt,
|
|
1180
|
+
...(presentation.ruleId === undefined ? {} : { ruleId: presentation.ruleId }),
|
|
1181
|
+
...(presentation.resultingRuleVersion === undefined
|
|
1182
|
+
? {} : { resultingRuleVersion: presentation.resultingRuleVersion }),
|
|
1183
|
+
...(presentation.ruleStatus === undefined ? {} : { ruleStatus: presentation.ruleStatus }),
|
|
1184
|
+
},
|
|
1185
|
+
}), signal);
|
|
1186
|
+
}
|
|
1187
|
+
matchesTarget(target) {
|
|
1188
|
+
const { conversation, principal } = target;
|
|
1189
|
+
return conversation.channel === this.channel
|
|
1190
|
+
&& principal.channel === this.channel
|
|
1191
|
+
&& conversation.account === this.account
|
|
1192
|
+
&& principal.account === this.account
|
|
1193
|
+
&& conversation.tenant === this.config.tenant
|
|
1194
|
+
&& principal.tenant === this.config.tenant;
|
|
1195
|
+
}
|
|
1196
|
+
userQuestionCard(pending) {
|
|
1197
|
+
if (!hasUsableApprovalSecret(this.approvalSecret)) {
|
|
1198
|
+
throw new LarkUserQuestionError('invalid', 'Lark user question signing is unavailable');
|
|
1199
|
+
}
|
|
1200
|
+
const question = pending.input.questions[pending.questionIndex];
|
|
1201
|
+
if (question === undefined) {
|
|
1202
|
+
throw new LarkUserQuestionError('invalid', 'Lark user question index is invalid');
|
|
1203
|
+
}
|
|
1204
|
+
const callbackValue = (action, optionIndex) => ({
|
|
1205
|
+
userQuestion: signLarkUserQuestionAction(this.approvalSecret, {
|
|
1206
|
+
...pending.payload,
|
|
1207
|
+
questionIndex: pending.questionIndex,
|
|
1208
|
+
optionIndex,
|
|
1209
|
+
action,
|
|
1210
|
+
revision: pending.revision,
|
|
1211
|
+
}),
|
|
1212
|
+
});
|
|
1213
|
+
const options = (question.options ?? []).map((option, optionIndex) => {
|
|
1214
|
+
const display = displayOptionLabel(option.label);
|
|
1215
|
+
return {
|
|
1216
|
+
label: display.label,
|
|
1217
|
+
...(option.description === undefined ? {} : { description: option.description }),
|
|
1218
|
+
recommended: display.recommended,
|
|
1219
|
+
selected: pending.selectedOptionIndexes.has(optionIndex),
|
|
1220
|
+
value: callbackValue(question.multiSelect === true ? 'toggle' : 'select', optionIndex),
|
|
1221
|
+
};
|
|
1222
|
+
});
|
|
1223
|
+
return {
|
|
1224
|
+
title: question.header?.trim() || '需要你的回答',
|
|
1225
|
+
question: question.question.trim(),
|
|
1226
|
+
...(question.detail === undefined ? {} : { detail: question.detail }),
|
|
1227
|
+
position: pending.questionIndex + 1,
|
|
1228
|
+
total: pending.input.questions.length,
|
|
1229
|
+
multiSelect: question.multiSelect === true,
|
|
1230
|
+
expectsText: options.length === 0,
|
|
1231
|
+
options,
|
|
1232
|
+
...(question.multiSelect === true && pending.selectedOptionIndexes.size > 0
|
|
1233
|
+
? { submitValue: callbackValue('submit', null) }
|
|
1234
|
+
: {}),
|
|
1235
|
+
cancelValue: callbackValue('cancel', null),
|
|
1236
|
+
answered: pending.answers.map((answer, index) => ({
|
|
1237
|
+
title: pending.input.questions[index]?.header?.trim() || `问题 ${index + 1}`,
|
|
1238
|
+
answer: this.userQuestionAnswerSummary(answer),
|
|
1239
|
+
})),
|
|
1240
|
+
};
|
|
1241
|
+
}
|
|
1242
|
+
userQuestionAnswerSummary(answer) {
|
|
1243
|
+
const parts = [...answer.selected, ...(answer.custom === undefined ? [] : [answer.custom])];
|
|
1244
|
+
const value = parts.join(';');
|
|
1245
|
+
return value.length <= 240 ? value : `${value.slice(0, 237)}...`;
|
|
1246
|
+
}
|
|
1247
|
+
userQuestionSendOptions(pending) {
|
|
1248
|
+
const conversation = pending.input.target.conversation;
|
|
1249
|
+
const providerReplyTarget = conversation.kind === 'group'
|
|
1250
|
+
&& !isLarkTopLevelSenderThread(conversation.thread)
|
|
1251
|
+
&& !isLarkTopicThread(conversation.thread)
|
|
1252
|
+
? conversation.thread
|
|
1253
|
+
: undefined;
|
|
1254
|
+
return {
|
|
1255
|
+
requestKey: `user-question:${pending.input.operationId}:${pending.requestHash}:${pending.revision}`,
|
|
1256
|
+
...(providerReplyTarget === undefined ? {} : { replyTo: providerReplyTarget, replyInThread: true }),
|
|
1257
|
+
};
|
|
1258
|
+
}
|
|
1259
|
+
async refreshUserQuestionCard(pending) {
|
|
1260
|
+
if (this.pendingUserQuestions.get(pending.input.operationId) !== pending)
|
|
1261
|
+
return;
|
|
1262
|
+
const card = { userQuestion: this.userQuestionCard(pending) };
|
|
1263
|
+
if (Buffer.byteLength(renderLarkMessage(card).content, 'utf8') > LARK_APPROVAL_CARD_MAX_BYTES) {
|
|
1264
|
+
this.settleUserQuestion(pending, { outcome: 'unavailable' }, 'resolved', true);
|
|
1265
|
+
return;
|
|
1266
|
+
}
|
|
1267
|
+
const update = this.transport.updateRawCard;
|
|
1268
|
+
if (pending.providerMessageId !== undefined && update !== undefined) {
|
|
1269
|
+
try {
|
|
1270
|
+
await update.call(this.transport, pending.providerMessageId, rawCard(card), new AbortController().signal);
|
|
1271
|
+
return;
|
|
1272
|
+
}
|
|
1273
|
+
catch (error) {
|
|
1274
|
+
this.recordPresentationFailure(error);
|
|
1275
|
+
}
|
|
1276
|
+
}
|
|
1277
|
+
try {
|
|
1278
|
+
const result = await this.transport.send(pending.input.target.conversation.chat, card, this.userQuestionSendOptions(pending));
|
|
1279
|
+
if (this.pendingUserQuestions.get(pending.input.operationId) !== pending)
|
|
1280
|
+
return;
|
|
1281
|
+
if (!larkProviderMessageIdentifier.test(result.messageId)) {
|
|
1282
|
+
this.settleUserQuestion(pending, { outcome: 'unavailable' }, 'resolved', true);
|
|
1283
|
+
return;
|
|
1284
|
+
}
|
|
1285
|
+
pending.providerMessageId = result.messageId;
|
|
1286
|
+
}
|
|
1287
|
+
catch (error) {
|
|
1288
|
+
this.recordPresentationFailure(error);
|
|
1289
|
+
this.settleUserQuestion(pending, { outcome: 'unavailable' }, 'resolved', true);
|
|
1290
|
+
}
|
|
1291
|
+
}
|
|
1292
|
+
userQuestionResult(status, answerCount) {
|
|
1293
|
+
if (status === 'answered') {
|
|
1294
|
+
return { status, summary: `已提交 ${answerCount} 个回答,智能体正在继续处理。` };
|
|
1295
|
+
}
|
|
1296
|
+
if (status === 'cancelled') {
|
|
1297
|
+
return { status, summary: '问题已取消,智能体将停止等待本次回答。' };
|
|
1298
|
+
}
|
|
1299
|
+
return { status, summary: '问题已在其他界面处理,或当前会话已经结束。' };
|
|
1300
|
+
}
|
|
1301
|
+
updateUserQuestionResult(pending, status) {
|
|
1302
|
+
const update = this.transport.updateRawCard;
|
|
1303
|
+
if (pending.providerMessageId === undefined || update === undefined)
|
|
1304
|
+
return;
|
|
1305
|
+
const card = rawCard({ userQuestionResult: this.userQuestionResult(status, pending.answers.length) });
|
|
1306
|
+
void update.call(this.transport, pending.providerMessageId, card, new AbortController().signal).catch(error => this.recordPresentationFailure(error));
|
|
1307
|
+
}
|
|
1308
|
+
settleUserQuestion(pending, outcome, status, updatePresentation) {
|
|
1309
|
+
if (this.pendingUserQuestions.get(pending.input.operationId) !== pending)
|
|
1310
|
+
return false;
|
|
1311
|
+
this.pendingUserQuestions.delete(pending.input.operationId);
|
|
1312
|
+
pending.signal.removeEventListener('abort', pending.abort);
|
|
1313
|
+
if (pending.timer !== undefined)
|
|
1314
|
+
clearTimeout(pending.timer);
|
|
1315
|
+
pending.resolve(outcome);
|
|
1316
|
+
if (updatePresentation)
|
|
1317
|
+
this.updateUserQuestionResult(pending, status);
|
|
1318
|
+
return true;
|
|
1319
|
+
}
|
|
1320
|
+
armUserQuestionExpiry(pending) {
|
|
1321
|
+
const expire = () => {
|
|
1322
|
+
if (this.pendingUserQuestions.get(pending.input.operationId) !== pending)
|
|
1323
|
+
return;
|
|
1324
|
+
let remaining;
|
|
1325
|
+
try {
|
|
1326
|
+
remaining = pending.payload.expiresAt - this.now();
|
|
1327
|
+
}
|
|
1328
|
+
catch {
|
|
1329
|
+
this.settleUserQuestion(pending, { outcome: 'unavailable' }, 'resolved', true);
|
|
1330
|
+
return;
|
|
1331
|
+
}
|
|
1332
|
+
if (!Number.isSafeInteger(remaining)) {
|
|
1333
|
+
this.settleUserQuestion(pending, { outcome: 'unavailable' }, 'resolved', true);
|
|
1334
|
+
return;
|
|
1335
|
+
}
|
|
1336
|
+
if (remaining <= 0) {
|
|
1337
|
+
this.settleUserQuestion(pending, { outcome: 'cancelled' }, 'cancelled', true);
|
|
1338
|
+
return;
|
|
1339
|
+
}
|
|
1340
|
+
pending.timer = setTimeout(expire, Math.min(remaining, LARK_TOOL_APPROVAL_MAX_TIMER_MS));
|
|
1341
|
+
pending.timer.unref();
|
|
1342
|
+
};
|
|
1343
|
+
expire();
|
|
1344
|
+
}
|
|
1345
|
+
cancelPendingUserQuestions() {
|
|
1346
|
+
for (const pending of this.pendingUserQuestions.values()) {
|
|
1347
|
+
this.settleUserQuestion(pending, { outcome: 'unavailable' }, 'resolved', true);
|
|
1348
|
+
}
|
|
1349
|
+
}
|
|
1350
|
+
recordUserQuestionAnswer(pending, answer) {
|
|
1351
|
+
pending.answers.push(answer);
|
|
1352
|
+
pending.selectedOptionIndexes.clear();
|
|
1353
|
+
if (pending.questionIndex + 1 < pending.input.questions.length) {
|
|
1354
|
+
pending.questionIndex += 1;
|
|
1355
|
+
pending.revision += 1;
|
|
1356
|
+
return undefined;
|
|
1357
|
+
}
|
|
1358
|
+
return { outcome: 'answered', answer: { answers: [...pending.answers] } };
|
|
1359
|
+
}
|
|
1360
|
+
rememberUserQuestionAnswerEvent(eventId) {
|
|
1361
|
+
if (this.userQuestionAnswerEvents.has(eventId))
|
|
1362
|
+
return;
|
|
1363
|
+
const timer = setTimeout(() => {
|
|
1364
|
+
this.userQuestionAnswerEvents.delete(eventId);
|
|
1365
|
+
}, Math.max(this.config.staleAfterMs, 60_000));
|
|
1366
|
+
timer.unref();
|
|
1367
|
+
this.userQuestionAnswerEvents.set(eventId, timer);
|
|
1368
|
+
}
|
|
1369
|
+
clearUserQuestionAnswerEvents() {
|
|
1370
|
+
for (const timer of this.userQuestionAnswerEvents.values())
|
|
1371
|
+
clearTimeout(timer);
|
|
1372
|
+
this.userQuestionAnswerEvents.clear();
|
|
1373
|
+
}
|
|
1374
|
+
async tryAnswerUserQuestion(envelope, providerMessageId) {
|
|
1375
|
+
if (this.userQuestionAnswerEvents.has(providerMessageId))
|
|
1376
|
+
return true;
|
|
1377
|
+
if (envelope.kind !== 'text' || envelope.attachments !== undefined)
|
|
1378
|
+
return false;
|
|
1379
|
+
const replyTo = envelope.metadata?.replyToProviderMessageId;
|
|
1380
|
+
if (replyTo === undefined)
|
|
1381
|
+
return false;
|
|
1382
|
+
const pending = [...this.pendingUserQuestions.values()].find(candidate => candidate.providerMessageId === replyTo
|
|
1383
|
+
&& samePrincipal(candidate.input.target.principal, envelope.principal)
|
|
1384
|
+
&& candidate.input.target.conversation.channel === envelope.conversation.channel
|
|
1385
|
+
&& candidate.input.target.conversation.account === envelope.conversation.account
|
|
1386
|
+
&& candidate.input.target.conversation.tenant === envelope.conversation.tenant
|
|
1387
|
+
&& candidate.input.target.conversation.kind === envelope.conversation.kind
|
|
1388
|
+
&& candidate.input.target.conversation.chat === envelope.conversation.chat);
|
|
1389
|
+
if (pending === undefined || pending.providerMessageId === undefined)
|
|
1390
|
+
return false;
|
|
1391
|
+
const question = pending.input.questions[pending.questionIndex];
|
|
1392
|
+
if (question === undefined)
|
|
1393
|
+
return false;
|
|
1394
|
+
const typed = envelope.text.trim();
|
|
1395
|
+
if (typed.length === 0)
|
|
1396
|
+
return false;
|
|
1397
|
+
const exactOption = (question.options ?? []).find(option => option.label === typed);
|
|
1398
|
+
const staged = [...pending.selectedOptionIndexes].sort((left, right) => left - right)
|
|
1399
|
+
.flatMap(index => question.options?.[index]?.label ?? []);
|
|
1400
|
+
const selected = exactOption === undefined
|
|
1401
|
+
? staged
|
|
1402
|
+
: question.multiSelect === true
|
|
1403
|
+
? [...new Set([...staged, exactOption.label])]
|
|
1404
|
+
: [exactOption.label];
|
|
1405
|
+
const custom = exactOption === undefined ? typed : undefined;
|
|
1406
|
+
const result = this.recordUserQuestionAnswer(pending, {
|
|
1407
|
+
id: question.id,
|
|
1408
|
+
selected,
|
|
1409
|
+
...(custom === undefined ? {} : { custom }),
|
|
1410
|
+
});
|
|
1411
|
+
this.rememberUserQuestionAnswerEvent(providerMessageId);
|
|
1412
|
+
if (result === undefined) {
|
|
1413
|
+
await this.refreshUserQuestionCard(pending);
|
|
1414
|
+
}
|
|
1415
|
+
else {
|
|
1416
|
+
this.settleUserQuestion(pending, result, 'answered', true);
|
|
1417
|
+
}
|
|
1418
|
+
if (this.statusReactions)
|
|
1419
|
+
void this.addReaction(providerMessageId, 'DONE');
|
|
1420
|
+
return true;
|
|
1421
|
+
}
|
|
1422
|
+
tryAnswerToolApproval(envelope, providerMessageId) {
|
|
1423
|
+
if (envelope.kind !== 'text' || envelope.attachments !== undefined || envelope.conversation.kind !== 'dm')
|
|
1424
|
+
return false;
|
|
1425
|
+
const decision = new Map([
|
|
1426
|
+
['允许', 'allowed-once'],
|
|
1427
|
+
['允许一次', 'allowed-once'],
|
|
1428
|
+
['拒绝', 'rejected'],
|
|
1429
|
+
]).get(envelope.text.trim());
|
|
1430
|
+
if (decision === undefined)
|
|
1431
|
+
return false;
|
|
1432
|
+
const candidates = [...this.pendingToolApprovals.values()].filter(candidate => candidate.providerMessageId !== undefined
|
|
1433
|
+
&& candidate.payload.channel === envelope.conversation.channel
|
|
1434
|
+
&& candidate.payload.account === envelope.conversation.account
|
|
1435
|
+
&& candidate.payload.tenant === envelope.conversation.tenant
|
|
1436
|
+
&& candidate.payload.chatId === envelope.conversation.chat
|
|
1437
|
+
&& candidate.payload.ownerUser === envelope.principal.user
|
|
1438
|
+
&& samePrincipal(envelope.principal, {
|
|
1439
|
+
channel: candidate.payload.channel,
|
|
1440
|
+
account: candidate.payload.account,
|
|
1441
|
+
tenant: candidate.payload.tenant,
|
|
1442
|
+
user: candidate.payload.ownerUser,
|
|
1443
|
+
}));
|
|
1444
|
+
if (candidates.length === 1) {
|
|
1445
|
+
this.settleToolApproval(candidates[0], decision);
|
|
1446
|
+
if (this.statusReactions)
|
|
1447
|
+
void this.addReaction(providerMessageId, 'DONE');
|
|
1448
|
+
}
|
|
1449
|
+
// Consume an approval-shaped owner message whenever at least one matching request is open.
|
|
1450
|
+
// With multiple requests the text is ambiguous, so only the exact card buttons may settle them.
|
|
1451
|
+
return candidates.length > 0;
|
|
1452
|
+
}
|
|
1453
|
+
armToolApprovalTombstone(operationId, tombstone) {
|
|
1454
|
+
const expire = () => {
|
|
1455
|
+
if (this.toolApprovalTombstones.get(operationId) !== tombstone)
|
|
1456
|
+
return;
|
|
1457
|
+
let remaining;
|
|
1458
|
+
try {
|
|
1459
|
+
remaining = tombstone.expiresAt - this.now();
|
|
1460
|
+
}
|
|
1461
|
+
catch {
|
|
1462
|
+
const pending = this.pendingToolApprovals.get(operationId);
|
|
1463
|
+
if (pending !== undefined)
|
|
1464
|
+
this.settleToolApproval(pending, 'unavailable');
|
|
1465
|
+
tombstone.timer = setTimeout(expire, 1_000);
|
|
1466
|
+
tombstone.timer.unref();
|
|
1467
|
+
return;
|
|
1468
|
+
}
|
|
1469
|
+
if (!Number.isSafeInteger(remaining)) {
|
|
1470
|
+
const pending = this.pendingToolApprovals.get(operationId);
|
|
1471
|
+
if (pending !== undefined)
|
|
1472
|
+
this.settleToolApproval(pending, 'unavailable');
|
|
1473
|
+
tombstone.timer = setTimeout(expire, 1_000);
|
|
1474
|
+
tombstone.timer.unref();
|
|
1475
|
+
return;
|
|
1476
|
+
}
|
|
1477
|
+
if (remaining <= 0) {
|
|
1478
|
+
const pending = this.pendingToolApprovals.get(operationId);
|
|
1479
|
+
if (pending !== undefined)
|
|
1480
|
+
this.settleToolApproval(pending, 'unavailable', 'expired');
|
|
1481
|
+
this.deleteToolApprovalTombstone(operationId, tombstone);
|
|
1482
|
+
return;
|
|
1483
|
+
}
|
|
1484
|
+
tombstone.timer = setTimeout(expire, Math.min(remaining, LARK_TOOL_APPROVAL_MAX_TIMER_MS));
|
|
1485
|
+
tombstone.timer.unref();
|
|
1486
|
+
};
|
|
1487
|
+
expire();
|
|
1488
|
+
}
|
|
1489
|
+
deleteToolApprovalTombstone(operationId, tombstone) {
|
|
1490
|
+
if (this.toolApprovalTombstones.get(operationId) !== tombstone)
|
|
1491
|
+
return false;
|
|
1492
|
+
this.toolApprovalTombstones.delete(operationId);
|
|
1493
|
+
if (tombstone.timer !== undefined)
|
|
1494
|
+
clearTimeout(tombstone.timer);
|
|
1495
|
+
return true;
|
|
1496
|
+
}
|
|
1497
|
+
toolApprovalResult(pending, status) {
|
|
1498
|
+
return { toolApprovalResult: { status, toolName: pending.payload.toolName } };
|
|
1499
|
+
}
|
|
1500
|
+
updateToolApprovalResult(pending, status) {
|
|
1501
|
+
const update = this.transport.updateRawCard;
|
|
1502
|
+
const messageId = pending.providerMessageId;
|
|
1503
|
+
if (this.closing || pending.presentationGeneration !== this.presentationGeneration
|
|
1504
|
+
|| pending.textFallback || messageId === undefined || update === undefined)
|
|
1505
|
+
return;
|
|
1506
|
+
const controller = new AbortController();
|
|
1507
|
+
const card = rawCard(this.toolApprovalResult(pending, status));
|
|
1508
|
+
let abort;
|
|
1509
|
+
const cancelled = new Promise(resolve => { abort = resolve; });
|
|
1510
|
+
controller.signal.addEventListener('abort', abort, { once: true });
|
|
1511
|
+
const deadline = setTimeout(() => {
|
|
1512
|
+
this.recordPresentationFailure(new LarkTransportError('send_timeout', 'Lark tool approval update timed out'));
|
|
1513
|
+
controller.abort();
|
|
1514
|
+
}, 30_000);
|
|
1515
|
+
deadline.unref?.();
|
|
1516
|
+
const entry = { controller, done: Promise.resolve() };
|
|
1517
|
+
entry.done = Promise.race([
|
|
1518
|
+
Promise.resolve().then(() => update.call(this.transport, messageId, card, controller.signal))
|
|
1519
|
+
.catch(error => { if (!controller.signal.aborted)
|
|
1520
|
+
this.recordPresentationFailure(error); }),
|
|
1521
|
+
cancelled,
|
|
1522
|
+
]).finally(() => {
|
|
1523
|
+
clearTimeout(deadline);
|
|
1524
|
+
controller.signal.removeEventListener('abort', abort);
|
|
1525
|
+
this.toolApprovalUpdates.delete(entry);
|
|
1526
|
+
});
|
|
1527
|
+
this.toolApprovalUpdates.add(entry);
|
|
1528
|
+
}
|
|
1529
|
+
async drainToolApprovalUpdates() {
|
|
1530
|
+
if (this.toolApprovalUpdates.size === 0)
|
|
1531
|
+
return;
|
|
1532
|
+
let deadline;
|
|
1533
|
+
await Promise.race([
|
|
1534
|
+
Promise.all([...this.toolApprovalUpdates].map(entry => entry.done)),
|
|
1535
|
+
new Promise(resolve => { deadline = setTimeout(resolve, 1_000); }),
|
|
1536
|
+
]);
|
|
1537
|
+
clearTimeout(deadline);
|
|
1538
|
+
for (const entry of this.toolApprovalUpdates)
|
|
1539
|
+
entry.controller.abort();
|
|
1540
|
+
await Promise.all([...this.toolApprovalUpdates].map(entry => entry.done));
|
|
1541
|
+
}
|
|
1542
|
+
settleToolApproval(pending, outcome, status = outcome, updatePresentation = true) {
|
|
1543
|
+
if (this.pendingToolApprovals.get(pending.payload.operationId) !== pending)
|
|
1544
|
+
return false;
|
|
1545
|
+
this.pendingToolApprovals.delete(pending.payload.operationId);
|
|
1546
|
+
pending.signal.removeEventListener('abort', pending.abort);
|
|
1547
|
+
pending.resultStatus = status;
|
|
1548
|
+
pending.resolve(outcome);
|
|
1549
|
+
if (updatePresentation)
|
|
1550
|
+
this.updateToolApprovalResult(pending, status);
|
|
1551
|
+
return true;
|
|
1552
|
+
}
|
|
1553
|
+
cancelPendingToolApprovals(outcome, clearTombstones = false) {
|
|
1554
|
+
for (const pending of this.pendingToolApprovals.values()) {
|
|
1555
|
+
this.settleToolApproval(pending, outcome);
|
|
1556
|
+
}
|
|
1557
|
+
if (!clearTombstones)
|
|
1558
|
+
return;
|
|
1559
|
+
for (const [operationId, tombstone] of this.toolApprovalTombstones) {
|
|
1560
|
+
this.deleteToolApprovalTombstone(operationId, tombstone);
|
|
1561
|
+
}
|
|
1562
|
+
}
|
|
1563
|
+
async addReaction(messageId, emojiType) {
|
|
1564
|
+
try {
|
|
1565
|
+
await this.transport.addReaction(messageId, emojiType);
|
|
1566
|
+
}
|
|
1567
|
+
catch (error) {
|
|
1568
|
+
this.recordPresentationFailure(error);
|
|
1569
|
+
}
|
|
1570
|
+
}
|
|
1571
|
+
recordPresentationFailure(error) {
|
|
1572
|
+
this.lastErrorCode = error instanceof LarkTransportError ? error.code : 'unknown';
|
|
1573
|
+
}
|
|
1574
|
+
cancelModelSelectionUpdates() {
|
|
1575
|
+
for (const pending of this.modelSelectionUpdates.values()) {
|
|
1576
|
+
if (pending.start !== undefined)
|
|
1577
|
+
clearImmediate(pending.start);
|
|
1578
|
+
if (pending.deadline !== undefined)
|
|
1579
|
+
clearTimeout(pending.deadline);
|
|
1580
|
+
pending.controller.abort(new Error('lark-channel: model selection presentation stopped'));
|
|
1581
|
+
}
|
|
1582
|
+
this.modelSelectionUpdates.clear();
|
|
1583
|
+
}
|
|
1584
|
+
startModelSelectionFinalUpdate(input, payload, picker) {
|
|
1585
|
+
const awaitModelSelection = this.awaitModelSelection;
|
|
1586
|
+
const updateRawCard = this.transport.updateRawCard?.bind(this.transport);
|
|
1587
|
+
if (awaitModelSelection === undefined || updateRawCard === undefined
|
|
1588
|
+
|| this.modelSelectionUpdates.has(input.callbackEventId))
|
|
1589
|
+
return;
|
|
1590
|
+
const controller = new AbortController();
|
|
1591
|
+
const pending = { controller };
|
|
1592
|
+
this.modelSelectionUpdates.set(input.callbackEventId, pending);
|
|
1593
|
+
// Card callback ACKs are sent after this handler resolves. Start the
|
|
1594
|
+
// independent PATCH lifecycle in the next macrotask, then serialize the
|
|
1595
|
+
// pending and terminal replacements on one chain so provider-side request
|
|
1596
|
+
// reordering cannot restore the pending card over the terminal result.
|
|
1597
|
+
pending.start = setImmediate(() => {
|
|
1598
|
+
delete pending.start;
|
|
1599
|
+
if (controller.signal.aborted || this.modelSelectionUpdates.get(input.callbackEventId) !== pending)
|
|
1600
|
+
return;
|
|
1601
|
+
pending.deadline = setTimeout(() => {
|
|
1602
|
+
controller.abort(new Error('lark-channel: model selection final update timed out'));
|
|
1603
|
+
}, MODEL_SELECTION_FINAL_UPDATE_TIMEOUT_MS);
|
|
1604
|
+
pending.deadline.unref?.();
|
|
1605
|
+
void updateRawCard(input.cardMessageId, rawCard({
|
|
1606
|
+
modelSelectionResult: modelSelectionResultCard({ status: 'pending' }, payload, picker),
|
|
1607
|
+
}), controller.signal)
|
|
1608
|
+
.catch(error => {
|
|
1609
|
+
if (!controller.signal.aborted)
|
|
1610
|
+
this.recordPresentationFailure(error);
|
|
1611
|
+
})
|
|
1612
|
+
.then(async () => {
|
|
1613
|
+
if (controller.signal.aborted)
|
|
1614
|
+
return undefined;
|
|
1615
|
+
return await awaitModelSelection(input, controller.signal);
|
|
1616
|
+
})
|
|
1617
|
+
.then(async (result) => {
|
|
1618
|
+
if (result === undefined || controller.signal.aborted)
|
|
1619
|
+
return;
|
|
1620
|
+
await updateRawCard(input.cardMessageId, rawCard({
|
|
1621
|
+
modelSelectionResult: modelSelectionResultCard(result, payload, picker),
|
|
1622
|
+
}), controller.signal);
|
|
1623
|
+
})
|
|
1624
|
+
.catch(error => {
|
|
1625
|
+
if (!controller.signal.aborted)
|
|
1626
|
+
this.recordPresentationFailure(error);
|
|
1627
|
+
})
|
|
1628
|
+
.finally(() => {
|
|
1629
|
+
if (pending.deadline !== undefined)
|
|
1630
|
+
clearTimeout(pending.deadline);
|
|
1631
|
+
if (this.modelSelectionUpdates.get(input.callbackEventId) === pending) {
|
|
1632
|
+
this.modelSelectionUpdates.delete(input.callbackEventId);
|
|
1633
|
+
}
|
|
1634
|
+
});
|
|
1635
|
+
});
|
|
1636
|
+
pending.start.unref?.();
|
|
1637
|
+
}
|
|
1638
|
+
async handleCardAction(action) {
|
|
1639
|
+
try {
|
|
1640
|
+
const value = action.value;
|
|
1641
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
1642
|
+
throw new LarkApprovalError('invalid', 'Lark card action value is invalid');
|
|
1643
|
+
}
|
|
1644
|
+
if (typeof value.toolApproval === 'string') {
|
|
1645
|
+
if (Object.keys(value).length !== 1) {
|
|
1646
|
+
throw new LarkToolApprovalError('invalid', 'Lark tool approval action value is invalid');
|
|
1647
|
+
}
|
|
1648
|
+
return this.handleToolApprovalAction(action, value.toolApproval);
|
|
1649
|
+
}
|
|
1650
|
+
if (Object.prototype.hasOwnProperty.call(value, 'userQuestion')) {
|
|
1651
|
+
return await this.handleUserQuestionAction(action, parseLarkUserQuestionCallback(value));
|
|
1652
|
+
}
|
|
1653
|
+
if (Object.prototype.hasOwnProperty.call(value, 'permissionPicker')) {
|
|
1654
|
+
return await this.handlePermissionPickerAction(action, parseLarkPermissionPickerCallback(value));
|
|
1655
|
+
}
|
|
1656
|
+
if (typeof value.modelPicker === 'string') {
|
|
1657
|
+
return await this.handleModelPickerAction(action, parseLarkModelPickerCallback(value));
|
|
1658
|
+
}
|
|
1659
|
+
if (Object.keys(value).length !== 1 || typeof value.approval !== 'string'
|
|
1660
|
+
|| this.approvalSecret === undefined) {
|
|
1661
|
+
throw new LarkApprovalError('invalid', 'Lark approval action value is invalid');
|
|
1662
|
+
}
|
|
1663
|
+
const token = value.approval;
|
|
1664
|
+
let expired = false;
|
|
1665
|
+
let payload;
|
|
1666
|
+
try {
|
|
1667
|
+
payload = verifyLarkApprovalAction(this.approvalSecret, token, this.now());
|
|
1668
|
+
}
|
|
1669
|
+
catch (error) {
|
|
1670
|
+
if (!(error instanceof LarkApprovalError) || error.code !== 'expired')
|
|
1671
|
+
throw error;
|
|
1672
|
+
payload = verifyLarkApprovalActionForRecovery(this.approvalSecret, token);
|
|
1673
|
+
expired = true;
|
|
1674
|
+
}
|
|
1675
|
+
if (payload.channel !== this.channel || payload.account !== this.account
|
|
1676
|
+
|| payload.tenant !== this.config.tenant || payload.chatId !== action.chatId) {
|
|
1677
|
+
throw new LarkApprovalError('invalid', 'Lark approval route does not match');
|
|
1678
|
+
}
|
|
1679
|
+
const callbackEventId = createHash('sha256')
|
|
1680
|
+
.update(`${action.messageId}\0${action.operatorId}\0${token}`)
|
|
1681
|
+
.digest('hex');
|
|
1682
|
+
const settlement = {
|
|
1683
|
+
operationId: payload.operationId,
|
|
1684
|
+
callbackEventId,
|
|
1685
|
+
callbackChatId: action.chatId,
|
|
1686
|
+
bindingId: payload.bindingId,
|
|
1687
|
+
principal: { channel: 'lark', account: this.account, tenant: this.config.tenant, user: action.operatorId },
|
|
1688
|
+
proposalId: payload.proposalId,
|
|
1689
|
+
expectedVersion: payload.expectedVersion,
|
|
1690
|
+
diffHash: payload.diffHash,
|
|
1691
|
+
decision: payload.decision,
|
|
1692
|
+
reason: `Lark owner ${payload.decision}`,
|
|
1693
|
+
};
|
|
1694
|
+
if (expired) {
|
|
1695
|
+
if (this.recoverApprovalSettlement === undefined
|
|
1696
|
+
|| await this.recoverApprovalSettlement(settlement) === undefined) {
|
|
1697
|
+
throw new LarkApprovalError('invalid', 'expired Lark approval settlement is not recoverable');
|
|
1698
|
+
}
|
|
1699
|
+
}
|
|
1700
|
+
else {
|
|
1701
|
+
if (this.settleApproval === undefined) {
|
|
1702
|
+
throw new LarkApprovalError('invalid', 'Lark approval settlement is unavailable');
|
|
1703
|
+
}
|
|
1704
|
+
await this.settleApproval(settlement);
|
|
1705
|
+
}
|
|
1706
|
+
return {
|
|
1707
|
+
toast: { type: 'success', content: payload.decision === 'approved'
|
|
1708
|
+
? '批准已记录,等待账本结算'
|
|
1709
|
+
: '提案已拒绝' },
|
|
1710
|
+
...callbackCard({ approvalResult: {
|
|
1711
|
+
decision: payload.decision,
|
|
1712
|
+
proposalId: payload.proposalId,
|
|
1713
|
+
} }),
|
|
1714
|
+
};
|
|
1715
|
+
}
|
|
1716
|
+
catch (error) {
|
|
1717
|
+
if (error instanceof LarkPermissionPickerError) {
|
|
1718
|
+
this.lastErrorCode = 'format_error';
|
|
1719
|
+
return { toast: { type: 'warning', content: error.code === 'expired'
|
|
1720
|
+
? '权限卡片已过期,请重新发送 /permission'
|
|
1721
|
+
: '权限卡片无效或已失效,请重新发送 /permission' } };
|
|
1722
|
+
}
|
|
1723
|
+
if (error instanceof LarkUserQuestionError) {
|
|
1724
|
+
return { toast: { type: 'warning', content: error.code === 'expired'
|
|
1725
|
+
? '问题卡片已过期,请重新向智能体发起请求'
|
|
1726
|
+
: '问题卡片已更新或失效,请使用最新卡片' } };
|
|
1727
|
+
}
|
|
1728
|
+
if (error instanceof LarkApprovalError || error instanceof LarkModelPickerError
|
|
1729
|
+
|| error instanceof LarkToolApprovalError) {
|
|
1730
|
+
this.lastErrorCode = 'format_error';
|
|
1731
|
+
return;
|
|
1732
|
+
}
|
|
1733
|
+
throw error;
|
|
1734
|
+
}
|
|
1735
|
+
}
|
|
1736
|
+
async handlePermissionPickerAction(action, callback) {
|
|
1737
|
+
if (!hasUsableApprovalSecret(this.approvalSecret) || this.settlePermissionSelection === undefined
|
|
1738
|
+
|| action.tag !== 'button' || !larkProviderMessageIdentifier.test(action.messageId)) {
|
|
1739
|
+
throw new LarkPermissionPickerError('invalid', 'Lark permission picker callback is unavailable');
|
|
1740
|
+
}
|
|
1741
|
+
const token = callback.permissionPicker;
|
|
1742
|
+
const payload = verifyLarkPermissionPickerAction(this.approvalSecret, token, this.now());
|
|
1743
|
+
if (payload.channel !== this.channel || payload.account !== this.account
|
|
1744
|
+
|| payload.tenant !== this.config.tenant || payload.chatId !== action.chatId
|
|
1745
|
+
|| payload.ownerUser !== action.operatorId) {
|
|
1746
|
+
throw new LarkPermissionPickerError('invalid', 'Lark permission picker route does not match');
|
|
1747
|
+
}
|
|
1748
|
+
const callbackEventId = createHash('sha256')
|
|
1749
|
+
.update(`${action.messageId}\0${action.operatorId}\0${token}`)
|
|
1750
|
+
.digest('hex');
|
|
1751
|
+
try {
|
|
1752
|
+
await this.settlePermissionSelection({
|
|
1753
|
+
operationId: payload.operationId,
|
|
1754
|
+
callbackEventId,
|
|
1755
|
+
callbackChatId: action.chatId,
|
|
1756
|
+
cardMessageId: action.messageId,
|
|
1757
|
+
bindingId: payload.bindingId,
|
|
1758
|
+
bindingVersion: payload.bindingVersion,
|
|
1759
|
+
sessionId: payload.sessionId,
|
|
1760
|
+
principal: {
|
|
1761
|
+
channel: payload.channel,
|
|
1762
|
+
account: payload.account,
|
|
1763
|
+
tenant: payload.tenant,
|
|
1764
|
+
user: payload.ownerUser,
|
|
1765
|
+
},
|
|
1766
|
+
issuedAt: payload.issuedAt,
|
|
1767
|
+
expiresAt: payload.expiresAt,
|
|
1768
|
+
expectedStateHash: payload.expectedStateHash,
|
|
1769
|
+
emergencyStopVersion: payload.emergencyStopVersion,
|
|
1770
|
+
targetLevel: payload.level,
|
|
1771
|
+
});
|
|
1772
|
+
return { toast: { type: 'success', content: '权限切换已受理' } };
|
|
1773
|
+
}
|
|
1774
|
+
catch (error) {
|
|
1775
|
+
this.recordPresentationFailure(error);
|
|
1776
|
+
return { toast: { type: 'warning', content: '权限卡片状态已更新,请重新发送 /permission' } };
|
|
1777
|
+
}
|
|
1778
|
+
}
|
|
1779
|
+
handleToolApprovalAction(action, token) {
|
|
1780
|
+
if (!hasUsableApprovalSecret(this.approvalSecret) || action.tag !== 'button'
|
|
1781
|
+
|| !larkProviderMessageIdentifier.test(action.messageId)) {
|
|
1782
|
+
throw new LarkToolApprovalError('invalid', 'Lark tool approval callback is unavailable');
|
|
1783
|
+
}
|
|
1784
|
+
const payload = verifyLarkToolApprovalAction(this.approvalSecret, token, this.now());
|
|
1785
|
+
if (payload.channel !== this.channel || payload.account !== this.account
|
|
1786
|
+
|| payload.tenant !== this.config.tenant || payload.chatId !== action.chatId
|
|
1787
|
+
|| payload.ownerUser !== action.operatorId) {
|
|
1788
|
+
throw new LarkToolApprovalError('invalid', 'Lark tool approval route does not match');
|
|
1789
|
+
}
|
|
1790
|
+
const pending = this.pendingToolApprovals.get(payload.operationId);
|
|
1791
|
+
if (pending === undefined || !sameToolApprovalPayload(pending.payload, payload)) {
|
|
1792
|
+
throw new LarkToolApprovalError('invalid', 'Lark tool approval request does not match');
|
|
1793
|
+
}
|
|
1794
|
+
if (pending.providerMessageId === undefined) {
|
|
1795
|
+
const earlyAction = pending.earlyAction;
|
|
1796
|
+
if (earlyAction !== undefined && (earlyAction.messageId !== action.messageId
|
|
1797
|
+
|| earlyAction.decision !== payload.decision)) {
|
|
1798
|
+
throw new LarkToolApprovalError('invalid', 'Lark tool approval request does not match');
|
|
1799
|
+
}
|
|
1800
|
+
pending.earlyAction = { messageId: action.messageId, decision: payload.decision };
|
|
1801
|
+
return { toast: { type: 'info', content: '正在确认工具审批卡片' } };
|
|
1802
|
+
}
|
|
1803
|
+
if (pending.providerMessageId !== action.messageId) {
|
|
1804
|
+
throw new LarkToolApprovalError('invalid', 'Lark tool approval request does not match');
|
|
1805
|
+
}
|
|
1806
|
+
if (!this.settleToolApproval(pending, payload.decision, payload.decision, false)) {
|
|
1807
|
+
throw new LarkToolApprovalError('invalid', 'Lark tool approval request is no longer pending');
|
|
1808
|
+
}
|
|
1809
|
+
return { toast: { type: payload.decision === 'allowed-once' ? 'success' : 'info',
|
|
1810
|
+
content: payload.decision === 'allowed-once' ? '已仅允许本次工具调用' : '已拒绝工具调用' },
|
|
1811
|
+
...callbackCard(this.toolApprovalResult(pending, payload.decision)) };
|
|
1812
|
+
}
|
|
1813
|
+
async handleUserQuestionAction(action, callback) {
|
|
1814
|
+
if (!hasUsableApprovalSecret(this.approvalSecret) || action.tag !== 'button'
|
|
1815
|
+
|| !larkProviderMessageIdentifier.test(action.messageId)) {
|
|
1816
|
+
throw new LarkUserQuestionError('invalid', 'Lark user question callback is unavailable');
|
|
1817
|
+
}
|
|
1818
|
+
const payload = verifyLarkUserQuestionAction(this.approvalSecret, callback.userQuestion, this.now());
|
|
1819
|
+
if (payload.channel !== this.channel || payload.account !== this.account
|
|
1820
|
+
|| payload.tenant !== this.config.tenant || payload.chatId !== action.chatId
|
|
1821
|
+
|| payload.ownerUser !== action.operatorId) {
|
|
1822
|
+
throw new LarkUserQuestionError('invalid', 'Lark user question route does not match');
|
|
1823
|
+
}
|
|
1824
|
+
const pending = this.pendingUserQuestions.get(payload.rpcId);
|
|
1825
|
+
if (pending === undefined
|
|
1826
|
+
|| pending.providerMessageId !== action.messageId
|
|
1827
|
+
|| pending.payload.version !== payload.version
|
|
1828
|
+
|| pending.payload.channel !== payload.channel
|
|
1829
|
+
|| pending.payload.account !== payload.account
|
|
1830
|
+
|| pending.payload.tenant !== payload.tenant
|
|
1831
|
+
|| pending.payload.rpcId !== payload.rpcId
|
|
1832
|
+
|| pending.payload.sessionId !== payload.sessionId
|
|
1833
|
+
|| pending.payload.bindingId !== payload.bindingId
|
|
1834
|
+
|| pending.payload.bindingVersion !== payload.bindingVersion
|
|
1835
|
+
|| pending.payload.bindingGeneration !== payload.bindingGeneration
|
|
1836
|
+
|| pending.payload.chatId !== payload.chatId
|
|
1837
|
+
|| pending.payload.ownerUser !== payload.ownerUser
|
|
1838
|
+
|| pending.payload.requestHash !== payload.requestHash
|
|
1839
|
+
|| pending.payload.expiresAt !== payload.expiresAt
|
|
1840
|
+
|| pending.questionIndex !== payload.questionIndex
|
|
1841
|
+
|| pending.revision !== payload.revision) {
|
|
1842
|
+
throw new LarkUserQuestionError('invalid', 'Lark user question request does not match');
|
|
1843
|
+
}
|
|
1844
|
+
const question = pending.input.questions[pending.questionIndex];
|
|
1845
|
+
if (question === undefined) {
|
|
1846
|
+
throw new LarkUserQuestionError('invalid', 'Lark user question index is invalid');
|
|
1847
|
+
}
|
|
1848
|
+
if (payload.action === 'cancel') {
|
|
1849
|
+
this.settleUserQuestion(pending, { outcome: 'cancelled' }, 'cancelled', false);
|
|
1850
|
+
return {
|
|
1851
|
+
toast: { type: 'info', content: '已取消本次问题' },
|
|
1852
|
+
...callbackCard({ userQuestionResult: this.userQuestionResult('cancelled', pending.answers.length) }),
|
|
1853
|
+
};
|
|
1854
|
+
}
|
|
1855
|
+
const options = question.options ?? [];
|
|
1856
|
+
if (payload.action === 'toggle') {
|
|
1857
|
+
if (question.multiSelect !== true || payload.optionIndex === null
|
|
1858
|
+
|| options[payload.optionIndex] === undefined) {
|
|
1859
|
+
throw new LarkUserQuestionError('invalid', 'Lark user question option is invalid');
|
|
1860
|
+
}
|
|
1861
|
+
if (pending.selectedOptionIndexes.has(payload.optionIndex)) {
|
|
1862
|
+
pending.selectedOptionIndexes.delete(payload.optionIndex);
|
|
1863
|
+
}
|
|
1864
|
+
else {
|
|
1865
|
+
pending.selectedOptionIndexes.add(payload.optionIndex);
|
|
1866
|
+
}
|
|
1867
|
+
pending.revision += 1;
|
|
1868
|
+
return {
|
|
1869
|
+
toast: { type: 'info', content: pending.selectedOptionIndexes.size === 0
|
|
1870
|
+
? '已清空选择'
|
|
1871
|
+
: `已选择 ${pending.selectedOptionIndexes.size} 项` },
|
|
1872
|
+
...callbackCard({ userQuestion: this.userQuestionCard(pending) }),
|
|
1873
|
+
};
|
|
1874
|
+
}
|
|
1875
|
+
let answer;
|
|
1876
|
+
if (payload.action === 'select') {
|
|
1877
|
+
if (question.multiSelect === true || payload.optionIndex === null
|
|
1878
|
+
|| options[payload.optionIndex] === undefined) {
|
|
1879
|
+
throw new LarkUserQuestionError('invalid', 'Lark user question option is invalid');
|
|
1880
|
+
}
|
|
1881
|
+
answer = { id: question.id, selected: [options[payload.optionIndex].label] };
|
|
1882
|
+
}
|
|
1883
|
+
else {
|
|
1884
|
+
if (question.multiSelect !== true || payload.optionIndex !== null
|
|
1885
|
+
|| pending.selectedOptionIndexes.size === 0) {
|
|
1886
|
+
throw new LarkUserQuestionError('invalid', 'Lark user question selection is empty');
|
|
1887
|
+
}
|
|
1888
|
+
answer = {
|
|
1889
|
+
id: question.id,
|
|
1890
|
+
selected: [...pending.selectedOptionIndexes]
|
|
1891
|
+
.sort((left, right) => left - right)
|
|
1892
|
+
.map(index => options[index].label),
|
|
1893
|
+
};
|
|
1894
|
+
}
|
|
1895
|
+
const result = this.recordUserQuestionAnswer(pending, answer);
|
|
1896
|
+
if (result === undefined) {
|
|
1897
|
+
return {
|
|
1898
|
+
toast: { type: 'success', content: '回答已记录,请继续下一题' },
|
|
1899
|
+
...callbackCard({ userQuestion: this.userQuestionCard(pending) }),
|
|
1900
|
+
};
|
|
1901
|
+
}
|
|
1902
|
+
this.settleUserQuestion(pending, result, 'answered', false);
|
|
1903
|
+
return {
|
|
1904
|
+
toast: { type: 'success', content: '回答已提交,智能体将继续处理' },
|
|
1905
|
+
...callbackCard({ userQuestionResult: this.userQuestionResult('answered', pending.answers.length) }),
|
|
1906
|
+
};
|
|
1907
|
+
}
|
|
1908
|
+
async handleModelPickerAction(action, callback) {
|
|
1909
|
+
if (this.approvalSecret === undefined || this.settleModelSelection === undefined
|
|
1910
|
+
|| !larkProviderMessageIdentifier.test(action.messageId)) {
|
|
1911
|
+
throw new LarkModelPickerError('invalid', 'Lark model picker callback is unavailable');
|
|
1912
|
+
}
|
|
1913
|
+
const token = callback.modelPicker;
|
|
1914
|
+
const payload = verifyLarkModelPickerAction(this.approvalSecret, token, this.now());
|
|
1915
|
+
if (payload.chatId !== action.chatId)
|
|
1916
|
+
throw new LarkModelPickerError('invalid', 'Lark model picker chat does not match');
|
|
1917
|
+
if (payload.action !== 'confirm') {
|
|
1918
|
+
const selectedOption = action.option;
|
|
1919
|
+
if (this.loadModelPicker === undefined || this.advanceModelPicker === undefined
|
|
1920
|
+
|| typeof selectedOption !== 'string') {
|
|
1921
|
+
throw new LarkModelPickerError('invalid', 'Lark model picker navigation is unavailable');
|
|
1922
|
+
}
|
|
1923
|
+
if (action.tag !== 'select_static') {
|
|
1924
|
+
throw new LarkModelPickerError('invalid', 'Lark model picker navigation action is invalid');
|
|
1925
|
+
}
|
|
1926
|
+
let picker;
|
|
1927
|
+
try {
|
|
1928
|
+
picker = await this.loadModelPicker({
|
|
1929
|
+
operationId: payload.operationId,
|
|
1930
|
+
callbackChatId: action.chatId,
|
|
1931
|
+
cardMessageId: action.messageId,
|
|
1932
|
+
bindingId: payload.bindingId,
|
|
1933
|
+
principal: { channel: 'lark', account: this.account, tenant: this.config.tenant, user: action.operatorId },
|
|
1934
|
+
});
|
|
1935
|
+
}
|
|
1936
|
+
catch (error) {
|
|
1937
|
+
this.recordPresentationFailure(error);
|
|
1938
|
+
return { toast: { type: 'warning', content: '模型选择已结束,请重新发送 /model' } };
|
|
1939
|
+
}
|
|
1940
|
+
if (picker === undefined || picker.operationId !== payload.operationId || picker.expiresAt !== payload.expiresAt) {
|
|
1941
|
+
return { toast: { type: 'warning', content: '模型选择已结束,请重新发送 /model' } };
|
|
1942
|
+
}
|
|
1943
|
+
const capability = {
|
|
1944
|
+
operationId: payload.operationId,
|
|
1945
|
+
bindingId: payload.bindingId,
|
|
1946
|
+
expiresAt: payload.expiresAt,
|
|
1947
|
+
chatId: payload.chatId,
|
|
1948
|
+
};
|
|
1949
|
+
let preferred;
|
|
1950
|
+
if (payload.action === 'provider') {
|
|
1951
|
+
if (!picker.providers.some(provider => provider.id === selectedOption)
|
|
1952
|
+
|| !picker.models.some(model => model.provider === selectedOption)) {
|
|
1953
|
+
throw new LarkModelPickerError('invalid', 'Lark model picker provider is unavailable');
|
|
1954
|
+
}
|
|
1955
|
+
preferred = {
|
|
1956
|
+
provider: selectedOption,
|
|
1957
|
+
effort: null,
|
|
1958
|
+
};
|
|
1959
|
+
}
|
|
1960
|
+
else if (payload.action === 'model') {
|
|
1961
|
+
const selected = routeParts(selectedOption);
|
|
1962
|
+
if (selected === undefined || selected.provider !== payload.provider
|
|
1963
|
+
|| !picker.models.some(model => model.provider === selected.provider && model.id === selected.model)) {
|
|
1964
|
+
throw new LarkModelPickerError('invalid', 'Lark model picker model is unavailable');
|
|
1965
|
+
}
|
|
1966
|
+
preferred = {
|
|
1967
|
+
provider: selected.provider,
|
|
1968
|
+
route: selectedOption,
|
|
1969
|
+
effort: null,
|
|
1970
|
+
};
|
|
1971
|
+
}
|
|
1972
|
+
else {
|
|
1973
|
+
const selectedModel = picker.models.find(model => model.provider === payload.provider && model.id === payload.model);
|
|
1974
|
+
const defaultEffort = selectedModel === undefined ? undefined : defaultEffortOption(selectedModel.effortIds);
|
|
1975
|
+
if (selectedModel === undefined || (selectedOption !== defaultEffort && !selectedModel.effortIds.includes(selectedOption))) {
|
|
1976
|
+
throw new LarkModelPickerError('invalid', 'Lark model picker effort is unavailable');
|
|
1977
|
+
}
|
|
1978
|
+
preferred = {
|
|
1979
|
+
provider: payload.provider,
|
|
1980
|
+
route: `${payload.provider}/${payload.model}`,
|
|
1981
|
+
effort: selectedOption === defaultEffort ? null : selectedOption,
|
|
1982
|
+
};
|
|
1983
|
+
}
|
|
1984
|
+
const next = resolvedModelRoute(resolveModelPicker(picker, preferred));
|
|
1985
|
+
let advanced;
|
|
1986
|
+
try {
|
|
1987
|
+
advanced = await this.advanceModelPicker({
|
|
1988
|
+
operationId: payload.operationId,
|
|
1989
|
+
callbackChatId: action.chatId,
|
|
1990
|
+
cardMessageId: action.messageId,
|
|
1991
|
+
bindingId: payload.bindingId,
|
|
1992
|
+
principal: { channel: 'lark', account: this.account, tenant: this.config.tenant, user: action.operatorId },
|
|
1993
|
+
expected: { revision: payload.revision, provider: payload.provider, model: payload.model,
|
|
1994
|
+
...(payload.effort === null ? {} : { reasoningEffort: payload.effort }) },
|
|
1995
|
+
next,
|
|
1996
|
+
});
|
|
1997
|
+
}
|
|
1998
|
+
catch (error) {
|
|
1999
|
+
this.recordPresentationFailure(error);
|
|
2000
|
+
return { toast: { type: 'warning', content: '模型选择已结束,请重新发送 /model' } };
|
|
2001
|
+
}
|
|
2002
|
+
const state = advanced.state;
|
|
2003
|
+
return callbackCard({ modelPicker: modelPickerCard(picker, this.approvalSecret, {
|
|
2004
|
+
...capability, revision: state.revision,
|
|
2005
|
+
}, {
|
|
2006
|
+
provider: state.provider,
|
|
2007
|
+
route: `${state.provider}/${state.model}`,
|
|
2008
|
+
effort: state.reasoningEffort ?? null,
|
|
2009
|
+
}) });
|
|
2010
|
+
}
|
|
2011
|
+
if (action.tag !== 'button') {
|
|
2012
|
+
throw new LarkModelPickerError('invalid', 'Lark model picker confirmation action is invalid');
|
|
2013
|
+
}
|
|
2014
|
+
const callbackEventId = createHash('sha256')
|
|
2015
|
+
.update(`${action.messageId}\0${action.operatorId}\0${token}`)
|
|
2016
|
+
.digest('hex');
|
|
2017
|
+
try {
|
|
2018
|
+
const settlementInput = {
|
|
2019
|
+
operationId: payload.operationId,
|
|
2020
|
+
callbackEventId,
|
|
2021
|
+
callbackChatId: action.chatId,
|
|
2022
|
+
cardMessageId: action.messageId,
|
|
2023
|
+
bindingId: payload.bindingId,
|
|
2024
|
+
principal: { channel: 'lark', account: this.account, tenant: this.config.tenant, user: action.operatorId },
|
|
2025
|
+
provider: payload.provider,
|
|
2026
|
+
modelProvider: payload.provider,
|
|
2027
|
+
model: payload.model,
|
|
2028
|
+
expectedRevision: payload.revision,
|
|
2029
|
+
...(payload.effort === null ? {} : { reasoningEffort: payload.effort }),
|
|
2030
|
+
};
|
|
2031
|
+
const settlement = await this.settleModelSelection(settlementInput);
|
|
2032
|
+
let picker;
|
|
2033
|
+
if (this.loadModelPicker !== undefined) {
|
|
2034
|
+
try {
|
|
2035
|
+
picker = await this.loadModelPicker({
|
|
2036
|
+
operationId: payload.operationId,
|
|
2037
|
+
callbackChatId: action.chatId,
|
|
2038
|
+
cardMessageId: action.messageId,
|
|
2039
|
+
bindingId: payload.bindingId,
|
|
2040
|
+
principal: {
|
|
2041
|
+
channel: 'lark',
|
|
2042
|
+
account: this.account,
|
|
2043
|
+
tenant: this.config.tenant,
|
|
2044
|
+
user: action.operatorId,
|
|
2045
|
+
},
|
|
2046
|
+
});
|
|
2047
|
+
}
|
|
2048
|
+
catch {
|
|
2049
|
+
// Settlement already succeeded. Catalog labels are optional presentation data,
|
|
2050
|
+
// so keep the ACK successful and render the signed IDs instead.
|
|
2051
|
+
}
|
|
2052
|
+
}
|
|
2053
|
+
if (settlement.status === 'pending') {
|
|
2054
|
+
this.startModelSelectionFinalUpdate(settlementInput, payload, picker);
|
|
2055
|
+
}
|
|
2056
|
+
if (settlement.status === 'pending') {
|
|
2057
|
+
return { toast: { type: 'info', content: '模型选择已提交,正在验证' } };
|
|
2058
|
+
}
|
|
2059
|
+
return {
|
|
2060
|
+
toast: settlement.status === 'selected'
|
|
2061
|
+
? { type: 'success', content: '模型已切换' }
|
|
2062
|
+
: { type: 'warning', content: '模型切换未生效' },
|
|
2063
|
+
...callbackCard({ modelSelectionResult: modelSelectionResultCard(settlement, payload, picker) }),
|
|
2064
|
+
};
|
|
2065
|
+
}
|
|
2066
|
+
catch (error) {
|
|
2067
|
+
this.recordPresentationFailure(error);
|
|
2068
|
+
return { toast: { type: 'warning', content: '卡片状态已更新,请重新发送 /model' } };
|
|
2069
|
+
}
|
|
2070
|
+
}
|
|
2071
|
+
}
|
|
2072
|
+
//# sourceMappingURL=adapter.js.map
|