@xmanrui/dsh-im 5.10.0 → 5.11.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/README.en.md +39 -5
- package/README.md +42 -5
- package/bin/dsh-im.mjs +65 -0
- package/docs/client-integration.md +4 -0
- package/lib/client.js +1202 -95
- package/lib/index.js +365 -339
- package/package.json +7 -6
- package/plugin-src/client/access-policy-settings.js +210 -12
- package/plugin-src/client/bot-general-settings.js +44 -3
- package/plugin-src/client/i18n-ru.js +85 -0
- package/plugin-src/client/i18n.js +83 -0
- package/plugin-src/client/im-channels.js +419 -0
- package/plugin-src/client/index.js +33 -1
- package/plugin-src/client/styles.js +7 -7
- package/plugin-src/client/update-panel.js +2 -1
- package/plugin-src/host/channel-list-rpc.mjs +280 -0
- package/plugin-src/host/channels/dingtalk/production.mjs +28 -10
- package/plugin-src/host/channels/dingtalk/rpc.mjs +10 -1
- package/plugin-src/host/channels/feishu/production.mjs +39 -10
- package/plugin-src/host/channels/feishu/rpc.mjs +10 -1
- package/plugin-src/host/channels/matrix/production.mjs +28 -10
- package/plugin-src/host/channels/matrix/rpc.mjs +10 -0
- package/plugin-src/host/channels/qq/production.mjs +30 -11
- package/plugin-src/host/channels/qq/rpc.mjs +10 -1
- package/plugin-src/host/channels/shared/access-policy-production.mjs +9 -0
- package/plugin-src/host/channels/shared/binding-events.mjs +109 -0
- package/plugin-src/host/channels/shared/production.mjs +14 -1
- package/plugin-src/host/channels/shared/reply-content-rpc.mjs +17 -0
- package/plugin-src/host/channels/shared/rpc.mjs +9 -0
- package/plugin-src/host/channels/slack/production.mjs +28 -10
- package/plugin-src/host/channels/slack/rpc.mjs +10 -0
- package/plugin-src/host/channels/telegram/production.mjs +5 -0
- package/plugin-src/host/channels/wecom/production.mjs +28 -10
- package/plugin-src/host/channels/wecom/rpc.mjs +10 -1
- package/plugin-src/host/channels/wecom-app/production.mjs +28 -10
- package/plugin-src/host/channels/wecom-app/rpc.mjs +9 -0
- package/plugin-src/host/channels/weixin/production.mjs +28 -10
- package/plugin-src/host/channels/weixin/rpc.mjs +10 -1
- package/plugin-src/host/channels/whatsapp/production.mjs +28 -10
- package/plugin-src/host/channels/whatsapp/rpc.mjs +10 -1
- package/plugin-src/host/delivery-service.mjs +3 -4
- package/plugin-src/host/delivery-suggestions.mjs +3 -1
- package/plugin-src/host/harness-connection.mjs +2 -1
- package/plugin-src/host/harness-peer.mjs +3 -1
- package/plugin-src/host/index.mjs +8 -1
- package/plugin-src/host/modern-harness-api.mjs +5 -1
- package/plugin-src/host/root-scope.mjs +32 -0
- package/plugin-src/host/session-sync-coordinator.mjs +2 -1
- package/plugin-src/management-rpc.mjs +18 -2
- package/scripts/verify-package.mjs +36 -7
- package/src/channels/dingtalk/dingtalk-bridge.mjs +50 -6
- package/src/channels/dingtalk/state-store.mjs +56 -0
- package/src/channels/discord/discord-api.mjs +2 -1
- package/src/channels/feishu/bridge.mjs +154 -58
- package/src/channels/feishu/feishu-cards.mjs +10 -4
- package/src/channels/feishu/feishu-runtime.mjs +11 -3
- package/src/channels/feishu/message-utils.mjs +106 -30
- package/src/channels/feishu/slash-command-panel.mjs +26 -0
- package/src/channels/feishu/state-store.mjs +14 -0
- package/src/channels/matrix/matrix-api.mjs +2 -1
- package/src/channels/qq/qq-bridge.mjs +105 -14
- package/src/channels/qq/state-store.mjs +13 -1
- package/src/channels/shared/access-policy.mjs +60 -7
- package/src/channels/shared/bot-workspace-store.mjs +155 -3
- package/src/channels/shared/busy-message-dispatcher.mjs +2 -2
- package/src/channels/shared/channel-capabilities.mjs +44 -0
- package/src/channels/shared/command-catalog.mjs +68 -3
- package/src/channels/shared/command-permission.mjs +6 -2
- package/src/channels/shared/conversation-state-store.mjs +16 -0
- package/src/channels/shared/deferred-delivery-coordinator.mjs +6 -1
- package/src/channels/shared/deferred-delivery.mjs +4 -0
- package/src/channels/shared/diagnostic-details.mjs +6 -1
- package/src/channels/shared/failure-log-file.mjs +79 -0
- package/src/channels/shared/harness-client.mjs +111 -6
- package/src/channels/shared/i18n-en/feishu.mjs +2 -2
- package/src/channels/shared/i18n-en/shared-a.mjs +13 -2
- package/src/channels/shared/i18n-en/shared-b.mjs +67 -4
- package/src/channels/shared/i18n-en/shared-d.mjs +144 -0
- package/src/channels/shared/i18n-en/weixin.mjs +4 -0
- package/src/channels/shared/i18n-en.mjs +2 -0
- package/src/channels/shared/i18n-ru/feishu.mjs +2 -2
- package/src/channels/shared/i18n-ru/shared-a.mjs +13 -2
- package/src/channels/shared/i18n-ru/shared-b.mjs +67 -4
- package/src/channels/shared/i18n-ru/shared-d.mjs +144 -0
- package/src/channels/shared/i18n-ru/weixin.mjs +4 -0
- package/src/channels/shared/i18n-ru.mjs +2 -0
- package/src/channels/shared/inbound-access.mjs +10 -0
- package/src/channels/shared/markdown-chunks.mjs +5 -0
- package/src/channels/shared/message-failure.mjs +22 -1
- package/src/channels/shared/new-command.mjs +158 -4
- package/src/channels/shared/plan-goal-command.mjs +132 -0
- package/src/channels/shared/qrcode.mjs +5 -0
- package/src/channels/shared/reply-content.mjs +102 -0
- package/src/channels/shared/reset-command.mjs +46 -0
- package/src/channels/shared/semantic/artifact.mjs +133 -29
- package/src/channels/shared/semantic/reply-reference.mjs +18 -3
- package/src/channels/shared/session-nav-command.mjs +999 -0
- package/src/channels/shared/session-ring-support.mjs +184 -0
- package/src/channels/shared/session-ring.mjs +202 -0
- package/src/channels/shared/session-title.mjs +11 -0
- package/src/channels/shared/status-command.mjs +2 -1
- package/src/channels/shared/text-harness-bridge.mjs +166 -7
- package/src/channels/shared/workspace-command.mjs +567 -31
- package/src/channels/shared/workspace-session.mjs +39 -3
- package/src/channels/slack/slack-api.mjs +2 -1
- package/src/channels/telegram/config-store.mjs +10 -2
- package/src/channels/telegram/telegram-rich-message.mjs +17 -5
- package/src/channels/telegram/telegram-runtime.mjs +14 -1
- package/src/channels/wecom/state-store.mjs +13 -1
- package/src/channels/wecom/wecom-bridge.mjs +183 -26
- package/src/channels/wecom-app/state-store.mjs +13 -1
- package/src/channels/wecom-app/wecom-app-bridge.mjs +44 -4
- package/src/channels/weixin/state-store.mjs +13 -1
- package/src/channels/weixin/weixin-bridge.mjs +71 -4
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { isSessionNotFound } from './session-error.mjs';
|
|
2
|
+
import { t } from './i18n.mjs';
|
|
3
|
+
import { WORKSPACE_SESSION_STALE } from './workspace-session.mjs';
|
|
4
|
+
|
|
5
|
+
// Session-scoped Host commands that are not part of the shared bot command
|
|
6
|
+
// table. The plugin does not implement them; it delegates the full command
|
|
7
|
+
// line to the DSH Host command gateway, exactly like /compact and /clear:
|
|
8
|
+
// /plan enter plan mode (optionally with a steering message)
|
|
9
|
+
// /plan off leave plan mode
|
|
10
|
+
// /goal view the current goal / available subcommands
|
|
11
|
+
// /goal <...> set, edit, clear, pause or resume the goal
|
|
12
|
+
// When the Host has not registered a command the gateway result is undefined
|
|
13
|
+
// and the user gets a "not registered" notice instead of a silent fallback.
|
|
14
|
+
const PLAN_COMMAND = /^\/plan(?=$|\s)([\s\S]*)$/i;
|
|
15
|
+
const GOAL_COMMAND = /^\/goal(?=$|\s)([\s\S]*)$/i;
|
|
16
|
+
|
|
17
|
+
function commandResult(message) {
|
|
18
|
+
return { handled: true, message, messages: [message] };
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function delegatedResultText(commandName, execution) {
|
|
22
|
+
const result = execution?.result;
|
|
23
|
+
if (!result || typeof result !== 'object'
|
|
24
|
+
|| !['success', 'error'].includes(result.kind)
|
|
25
|
+
|| (result.text !== undefined && typeof result.text !== 'string')) {
|
|
26
|
+
throw new TypeError(`Harness returned an invalid ${commandName} result`);
|
|
27
|
+
}
|
|
28
|
+
const text = result.text?.trim() ?? '';
|
|
29
|
+
if (text) return text;
|
|
30
|
+
return result.kind === 'success'
|
|
31
|
+
? t('{name} 已执行。', { name: commandName })
|
|
32
|
+
: t('{name} 执行失败。', { name: commandName });
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function delegatedErrorText(commandName, error) {
|
|
36
|
+
const code = error?.code ?? error?.failure?.code;
|
|
37
|
+
if (isSessionNotFound(code)) {
|
|
38
|
+
return t('当前聊天绑定的会话已不存在,请发送新消息开启会话。');
|
|
39
|
+
}
|
|
40
|
+
if (code === 'agent-busy') return t('当前会话正在生成回复,请稍后重试。');
|
|
41
|
+
if (code === 'cancelled' || error?.name === 'AbortError') return t('操作已取消。');
|
|
42
|
+
if (code === WORKSPACE_SESSION_STALE || code === 'workspace-bot-not-found') {
|
|
43
|
+
return t('工作区或机器人状态已发生变化,请重试。');
|
|
44
|
+
}
|
|
45
|
+
if (code === 'commands-unavailable') {
|
|
46
|
+
return t('当前 Host 不支持命令委派,请确认 DSH 命令网关可用。');
|
|
47
|
+
}
|
|
48
|
+
return t('{name} 执行失败,请稍后重试。', { name: commandName });
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function runDelegatedCommand({
|
|
52
|
+
commandName,
|
|
53
|
+
commandLine,
|
|
54
|
+
harness,
|
|
55
|
+
state,
|
|
56
|
+
conversationKey,
|
|
57
|
+
options,
|
|
58
|
+
}) {
|
|
59
|
+
if (typeof state?.sessionFor !== 'function') {
|
|
60
|
+
return commandResult(t('当前机器人没有可用的会话状态。'));
|
|
61
|
+
}
|
|
62
|
+
const sessionId = state.sessionFor(conversationKey);
|
|
63
|
+
if (typeof sessionId !== 'string' || !sessionId) {
|
|
64
|
+
return commandResult(t('当前聊天还没有可用的会话,请先发送一条消息。'));
|
|
65
|
+
}
|
|
66
|
+
try {
|
|
67
|
+
let execution;
|
|
68
|
+
if (typeof harness?.workspaceSession === 'function') {
|
|
69
|
+
const session = harness.workspaceSession(sessionId, conversationKey);
|
|
70
|
+
if (typeof session?.executeCommand !== 'function') {
|
|
71
|
+
return commandResult(t('当前机器人暂不支持 {name} 命令。', { name: commandName }));
|
|
72
|
+
}
|
|
73
|
+
execution = await session.executeCommand(commandLine, options);
|
|
74
|
+
} else {
|
|
75
|
+
// Legacy Harnesses have no scoped Session handle to carry the route fence.
|
|
76
|
+
if (typeof harness?.executeCommand !== 'function') {
|
|
77
|
+
return commandResult(t('当前机器人暂不支持 {name} 命令。', { name: commandName }));
|
|
78
|
+
}
|
|
79
|
+
execution = await harness.executeCommand(sessionId, commandLine, options);
|
|
80
|
+
}
|
|
81
|
+
if (execution === undefined) {
|
|
82
|
+
return commandResult(t('当前 Host 未注册 {name} 命令。', { name: commandName }));
|
|
83
|
+
}
|
|
84
|
+
return commandResult(delegatedResultText(commandName, execution));
|
|
85
|
+
} catch (error) {
|
|
86
|
+
return commandResult(delegatedErrorText(commandName, error));
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Execute the Host /plan command against the IM conversation's bound Session.
|
|
92
|
+
* Unknown input returns null so the caller may continue ordinary message
|
|
93
|
+
* routing.
|
|
94
|
+
*/
|
|
95
|
+
export async function runPlanCommand(text, harness, state, conversationKey, options = {}) {
|
|
96
|
+
if (!isPlanCommand(text)) return null;
|
|
97
|
+
const rest = PLAN_COMMAND.exec(text.trim())[1].trim();
|
|
98
|
+
return runDelegatedCommand({
|
|
99
|
+
commandName: '/plan',
|
|
100
|
+
commandLine: rest ? `/plan ${rest}` : '/plan',
|
|
101
|
+
harness,
|
|
102
|
+
state,
|
|
103
|
+
conversationKey,
|
|
104
|
+
options,
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function isPlanCommand(text) {
|
|
109
|
+
return typeof text === 'string' && PLAN_COMMAND.test(text.trim());
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Execute the Host /goal command against the IM conversation's bound Session.
|
|
114
|
+
* Unknown input returns null so the caller may continue ordinary message
|
|
115
|
+
* routing.
|
|
116
|
+
*/
|
|
117
|
+
export async function runGoalCommand(text, harness, state, conversationKey, options = {}) {
|
|
118
|
+
if (!isGoalCommand(text)) return null;
|
|
119
|
+
const rest = GOAL_COMMAND.exec(text.trim())[1].trim();
|
|
120
|
+
return runDelegatedCommand({
|
|
121
|
+
commandName: '/goal',
|
|
122
|
+
commandLine: rest ? `/goal ${rest}` : '/goal',
|
|
123
|
+
harness,
|
|
124
|
+
state,
|
|
125
|
+
conversationKey,
|
|
126
|
+
options,
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export function isGoalCommand(text) {
|
|
131
|
+
return typeof text === 'string' && GOAL_COMMAND.test(text.trim());
|
|
132
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-bot reply content filters.
|
|
3
|
+
*
|
|
4
|
+
* A Harness turn produces more than its final answer: the assistant narrates
|
|
5
|
+
* between tool calls ("let me check that first"), tools run, and the model may
|
|
6
|
+
* reason. Some conversations only want the answer. Each bot therefore keeps
|
|
7
|
+
* three independent switches for the parts of a turn it is willing to receive:
|
|
8
|
+
*
|
|
9
|
+
* narration -- the assistant's own prose between tool calls
|
|
10
|
+
* tools -- tool calls, their results and tool failures
|
|
11
|
+
* thinking -- the model's reasoning trace, where the channel shows one
|
|
12
|
+
*
|
|
13
|
+
* The final answer is never switchable: it is the reason the bot replies at
|
|
14
|
+
* all. When narration is hidden the delivered answer is also extracted after
|
|
15
|
+
* the last tool call, because the prose around it belongs to the process the
|
|
16
|
+
* user asked not to see.
|
|
17
|
+
*
|
|
18
|
+
* Kept free of Node imports so the Web client can share the same rules.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
export const SET_REPLY_CONTENT_ENDPOINT = 'bot.reply-content.set';
|
|
22
|
+
|
|
23
|
+
/** Every key a bot may switch off; the final answer is deliberately absent. */
|
|
24
|
+
export const REPLY_CONTENT_KEYS = Object.freeze(['narration', 'tools', 'thinking']);
|
|
25
|
+
|
|
26
|
+
/** Defaults keep the pre-existing behaviour: a turn is delivered in full. */
|
|
27
|
+
export const DEFAULT_REPLY_CONTENT = Object.freeze({
|
|
28
|
+
narration: true,
|
|
29
|
+
tools: true,
|
|
30
|
+
thinking: true,
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
function booleanOr(value, fallback) {
|
|
34
|
+
return typeof value === 'boolean' ? value : fallback;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* A complete, frozen switch set. A missing or damaged key falls back to its
|
|
39
|
+
* default, so one bad field can never silence a bot.
|
|
40
|
+
*/
|
|
41
|
+
export function normalizeReplyContent(value) {
|
|
42
|
+
const source = value && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
|
43
|
+
return Object.freeze({
|
|
44
|
+
narration: booleanOr(source.narration, DEFAULT_REPLY_CONTENT.narration),
|
|
45
|
+
tools: booleanOr(source.tools, DEFAULT_REPLY_CONTENT.tools),
|
|
46
|
+
thinking: booleanOr(source.thinking, DEFAULT_REPLY_CONTENT.thinking),
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Whether this switch set is the all-on default (and so need not be stored). */
|
|
51
|
+
export function isDefaultReplyContent(value) {
|
|
52
|
+
const content = normalizeReplyContent(value);
|
|
53
|
+
return REPLY_CONTENT_KEYS.every((key) => content[key] === DEFAULT_REPLY_CONTENT[key]);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** True when at least one part of the turn is filtered out. */
|
|
57
|
+
export function filtersProcessContent(value) {
|
|
58
|
+
const content = normalizeReplyContent(value);
|
|
59
|
+
return REPLY_CONTENT_KEYS.some((key) => content[key] === false);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The answer a bot should deliver for this switch set.
|
|
64
|
+
*
|
|
65
|
+
* narration=false asks for the answer alone, so the text of every completed
|
|
66
|
+
* step before the last tool call is process prose rather than the answer.
|
|
67
|
+
*/
|
|
68
|
+
export function replyContentFinalAnswerOnly(value) {
|
|
69
|
+
return normalizeReplyContent(value).narration === false;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Whether a progress update of this kind may be delivered. */
|
|
73
|
+
export function allowsReplyContent(value, kind) {
|
|
74
|
+
const content = normalizeReplyContent(value);
|
|
75
|
+
if (kind === 'narration' || kind === 'tools' || kind === 'thinking') return content[kind];
|
|
76
|
+
return true;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Strict shape for the settings endpoint: every switch must be present and
|
|
81
|
+
* boolean. Validation is separate from normalization so a malformed request is
|
|
82
|
+
* rejected instead of silently rewritten.
|
|
83
|
+
*/
|
|
84
|
+
export function isReplyContent(value) {
|
|
85
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
86
|
+
&& Object.keys(value).length === REPLY_CONTENT_KEYS.length
|
|
87
|
+
&& REPLY_CONTENT_KEYS.every((key) => typeof value[key] === 'boolean');
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** A strict set, or a thrown error naming the field that is wrong. */
|
|
91
|
+
export function validateReplyContent(value) {
|
|
92
|
+
if (!isReplyContent(value)) {
|
|
93
|
+
const error = new Error('replyContent must carry boolean narration, tools and thinking switches.');
|
|
94
|
+
error.code = 'reply-content-invalid';
|
|
95
|
+
throw error;
|
|
96
|
+
}
|
|
97
|
+
return Object.freeze({
|
|
98
|
+
narration: value.narration,
|
|
99
|
+
tools: value.tools,
|
|
100
|
+
thinking: value.thinking,
|
|
101
|
+
});
|
|
102
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { t } from './i18n.mjs';
|
|
2
|
+
import { replaceConversationSession } from './new-command.mjs';
|
|
3
|
+
|
|
4
|
+
const RESET_COMMAND = /^\/reset(?=$|\s)([\s\S]*)$/iu;
|
|
5
|
+
const RESET_USAGE = '用法:/reset(不带参数且不可附带图片或文件)';
|
|
6
|
+
|
|
7
|
+
function commandResult(message) {
|
|
8
|
+
return { handled: true, message, messages: [message] };
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* /reset is answered locally: it creates a fresh Session through the same eager
|
|
13
|
+
* path /new uses and swaps it into the current ring entry in place, so the
|
|
14
|
+
* number stays, /ls does not grow, the title and user-titled flag survive, and
|
|
15
|
+
* the previous Session simply leaves this chat's ring (it is never deleted or
|
|
16
|
+
* archived). It never reaches the Host command registry.
|
|
17
|
+
*/
|
|
18
|
+
export async function runResetCommand(text, harness, state, conversationKey, options = {}) {
|
|
19
|
+
if (!isResetCommand(text)) return null;
|
|
20
|
+
const match = RESET_COMMAND.exec(text.trim());
|
|
21
|
+
if (match[1].trim() || options.hasImages || options.hasFiles) {
|
|
22
|
+
return commandResult(t(RESET_USAGE));
|
|
23
|
+
}
|
|
24
|
+
if (options.pendingInteraction || options.busy) {
|
|
25
|
+
return commandResult(t('当前会话正在生成回复或等待交互,请先完成交互或发送 /stop,再执行 /reset。'));
|
|
26
|
+
}
|
|
27
|
+
if (typeof state?.sessionFor !== 'function') {
|
|
28
|
+
return commandResult(t('当前机器人没有可用的会话状态,未重置当前会话。'));
|
|
29
|
+
}
|
|
30
|
+
if (typeof harness?.createSession !== 'function') {
|
|
31
|
+
return commandResult(t('当前 Host 不支持 /reset,当前会话未修改。'));
|
|
32
|
+
}
|
|
33
|
+
const previous = state.sessionFor(conversationKey);
|
|
34
|
+
const result = await replaceConversationSession({ state, harness, key: conversationKey });
|
|
35
|
+
if (result.failed || typeof result.sessionId !== 'string' || !result.sessionId) {
|
|
36
|
+
return commandResult(t('重置当前会话上下文失败,当前会话未修改,请稍后重试。'));
|
|
37
|
+
}
|
|
38
|
+
if (typeof previous === 'string' && previous) {
|
|
39
|
+
return commandResult(t('当前会话上下文已重置(编号保持不变)。旧会话 ID:{id},可用 /session {id} 重新绑定。', { id: previous }));
|
|
40
|
+
}
|
|
41
|
+
return commandResult(t('当前聊天还没有会话,已开启全新会话。'));
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function isResetCommand(text) {
|
|
45
|
+
return typeof text === 'string' && RESET_COMMAND.test(text.trim());
|
|
46
|
+
}
|
|
@@ -5,6 +5,7 @@ import { tmpdir } from 'node:os';
|
|
|
5
5
|
import { basename, extname, isAbsolute, join, resolve } from 'node:path';
|
|
6
6
|
|
|
7
7
|
export const OUTBOUND_ARTIFACT_TOOL = 'dsh_im_return_file';
|
|
8
|
+
const HOST_PRESENT_TOOL = 'present';
|
|
8
9
|
|
|
9
10
|
const ARTIFACT_KIND = 'dsh-im-outbound-artifact';
|
|
10
11
|
const ARTIFACT_READ_CHUNK_BYTES = 64 * 1024;
|
|
@@ -281,6 +282,7 @@ export class OutboundArtifactRegistry {
|
|
|
281
282
|
#consumersByPrompt = new Map();
|
|
282
283
|
#consumersByTurn = new Map();
|
|
283
284
|
#openTurns = new Map();
|
|
285
|
+
#adoptions = new Map();
|
|
284
286
|
#uuid;
|
|
285
287
|
|
|
286
288
|
constructor({ uuid = randomUUID } = {}) {
|
|
@@ -375,6 +377,118 @@ export class OutboundArtifactRegistry {
|
|
|
375
377
|
}
|
|
376
378
|
}
|
|
377
379
|
|
|
380
|
+
/**
|
|
381
|
+
* Adopt the files the host `present` tool recorded for this Turn.
|
|
382
|
+
*
|
|
383
|
+
* `present` appends `deliverables/presented` to the durable Session and
|
|
384
|
+
* reports success, but the IM delivery path only claims artifacts registered
|
|
385
|
+
* through `dsh_im_return_file`. A file presented in an IM conversation was
|
|
386
|
+
* therefore dropped without an error: the answer stayed intact and the user
|
|
387
|
+
* received nothing. Snapshot the recorded paths into the same pipeline so the
|
|
388
|
+
* channel delivers them when the Turn ends.
|
|
389
|
+
*/
|
|
390
|
+
adoptPresented(session, event, { logger } = {}) {
|
|
391
|
+
const sessionId = sessionIdOf(session);
|
|
392
|
+
const turn = event?.data?.turn;
|
|
393
|
+
const files = event?.data?.files;
|
|
394
|
+
if (!sessionId || !Number.isInteger(turn) || turn < 0) return null;
|
|
395
|
+
if (!Array.isArray(files) || files.length === 0) return null;
|
|
396
|
+
if (!this.#consumerForTurn(sessionId, turn)) {
|
|
397
|
+
logger?.warn?.('[dsh-im] files presented by the host tool were not delivered: no IM delivery consumer owns this turn', {
|
|
398
|
+
sessionId, turn, fileCount: files.length,
|
|
399
|
+
});
|
|
400
|
+
return null;
|
|
401
|
+
}
|
|
402
|
+
const workspace = session?.header?.cwd;
|
|
403
|
+
const keyForTurn = turnKey(sessionId, turn);
|
|
404
|
+
// Snapshot in parallel, commit in the order the answer presented them so
|
|
405
|
+
// the channel sends the files in a predictable sequence.
|
|
406
|
+
const adoption = Promise.all(files.map((file) => this.#snapshotPresentedFile({
|
|
407
|
+
sessionId, turn, workspace, file, logger,
|
|
408
|
+
}))).then((artifacts) => {
|
|
409
|
+
for (const artifact of artifacts) {
|
|
410
|
+
if (artifact) this.#commitArtifact(artifact);
|
|
411
|
+
}
|
|
412
|
+
});
|
|
413
|
+
const pending = this.#adoptions.get(keyForTurn) ?? [];
|
|
414
|
+
pending.push(adoption);
|
|
415
|
+
this.#adoptions.set(keyForTurn, pending);
|
|
416
|
+
return adoption;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/** Let a Turn end wait for in-flight present() adoption instead of outrunning it. */
|
|
420
|
+
async adoptionsSettled(sessionId, turn) {
|
|
421
|
+
if (typeof sessionId !== 'string' || !Number.isInteger(turn)) return;
|
|
422
|
+
const keyForTurn = turnKey(sessionId, turn);
|
|
423
|
+
const pending = this.#adoptions.get(keyForTurn);
|
|
424
|
+
if (!pending) return;
|
|
425
|
+
await Promise.allSettled(pending);
|
|
426
|
+
if (this.#adoptions.get(keyForTurn) === pending) this.#adoptions.delete(keyForTurn);
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
async #snapshotPresentedFile({ sessionId, turn, workspace, file, logger }) {
|
|
430
|
+
const requestedPath = typeof file?.path === 'string' ? file.path.trim() : '';
|
|
431
|
+
if (!requestedPath) return null;
|
|
432
|
+
try {
|
|
433
|
+
const snapshot = await snapshotFile(workspace, requestedPath);
|
|
434
|
+
return this.#buildArtifact(sessionId, turn, snapshot, {
|
|
435
|
+
callId: typeof file?.callId === 'string' ? file.callId : null,
|
|
436
|
+
kind: 'session-event',
|
|
437
|
+
toolName: HOST_PRESENT_TOOL,
|
|
438
|
+
});
|
|
439
|
+
} catch (error) {
|
|
440
|
+
logger?.warn?.('[dsh-im] could not adopt a file presented by the host tool:', {
|
|
441
|
+
sessionId, turn, path: requestedPath, reason: error?.code ?? error?.message,
|
|
442
|
+
});
|
|
443
|
+
return null;
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
#buildArtifact(sessionId, turn, snapshot, { callId, kind, toolName }) {
|
|
448
|
+
const artifact = Object.freeze({
|
|
449
|
+
kind: ARTIFACT_KIND,
|
|
450
|
+
schemaVersion: 1,
|
|
451
|
+
artifactId: this.#uuid(),
|
|
452
|
+
deliveryKey: this.#uuid(),
|
|
453
|
+
fileName: snapshot.fileName,
|
|
454
|
+
mediaType: snapshot.mediaType,
|
|
455
|
+
size: snapshot.size,
|
|
456
|
+
digest: snapshot.digest,
|
|
457
|
+
source: 'managed-temp',
|
|
458
|
+
registeredBy: Object.freeze({
|
|
459
|
+
kind,
|
|
460
|
+
eventId: typeof callId === 'string' ? callId : 'unknown',
|
|
461
|
+
toolName,
|
|
462
|
+
}),
|
|
463
|
+
origin: Object.freeze({
|
|
464
|
+
sessionId,
|
|
465
|
+
turn,
|
|
466
|
+
callId: typeof callId === 'string' ? callId : null,
|
|
467
|
+
}),
|
|
468
|
+
createdAt: Date.now(),
|
|
469
|
+
});
|
|
470
|
+
artifactStorage.set(artifact, {
|
|
471
|
+
path: snapshot.storagePath,
|
|
472
|
+
materializing: 0,
|
|
473
|
+
materialized: false,
|
|
474
|
+
releaseRequested: false,
|
|
475
|
+
cleanupRequested: false,
|
|
476
|
+
cleanupDeferred: false,
|
|
477
|
+
onCleanup: () => this.#forgetArtifact(artifact),
|
|
478
|
+
});
|
|
479
|
+
return artifact;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
#commitArtifact(artifact) {
|
|
483
|
+
const keyForTurn = turnKey(artifact.origin.sessionId, artifact.origin.turn);
|
|
484
|
+
let committed = this.#turns.get(keyForTurn);
|
|
485
|
+
if (!committed) {
|
|
486
|
+
committed = new Map();
|
|
487
|
+
this.#turns.set(keyForTurn, committed);
|
|
488
|
+
}
|
|
489
|
+
committed.set(artifactKey(artifact), artifact);
|
|
490
|
+
}
|
|
491
|
+
|
|
378
492
|
#currentTurn(session) {
|
|
379
493
|
const sessionId = sessionIdOf(session);
|
|
380
494
|
return this.#openTurns.has(sessionId)
|
|
@@ -418,6 +532,9 @@ export class OutboundArtifactRegistry {
|
|
|
418
532
|
if (key.startsWith(prefix)) this.#consumersByTurn.delete(key);
|
|
419
533
|
}
|
|
420
534
|
this.#openTurns.delete(sessionId);
|
|
535
|
+
for (const key of [...this.#adoptions.keys()]) {
|
|
536
|
+
if (key.startsWith(prefix)) this.#adoptions.delete(key);
|
|
537
|
+
}
|
|
421
538
|
for (const artifact of artifacts) cleanupArtifactStorage(artifact);
|
|
422
539
|
}
|
|
423
540
|
|
|
@@ -446,7 +563,7 @@ export class OutboundArtifactRegistry {
|
|
|
446
563
|
if (!consumer) throw unavailable();
|
|
447
564
|
|
|
448
565
|
const snapshot = await snapshotFile(workspace, requestedPath, exec?.signal);
|
|
449
|
-
const { storagePath
|
|
566
|
+
const { storagePath } = snapshot;
|
|
450
567
|
// Copying and hashing yield to cancellation, disposal and Turn completion.
|
|
451
568
|
// Never leave a late snapshot behind after its delivery owner has gone.
|
|
452
569
|
try {
|
|
@@ -457,33 +574,10 @@ export class OutboundArtifactRegistry {
|
|
|
457
574
|
await unlink(storagePath).catch(() => undefined);
|
|
458
575
|
throw error;
|
|
459
576
|
}
|
|
460
|
-
const artifact =
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
deliveryKey: this.#uuid(),
|
|
465
|
-
...snapshotMetadata,
|
|
466
|
-
source: 'managed-temp',
|
|
467
|
-
registeredBy: Object.freeze({
|
|
468
|
-
kind: 'tool-result',
|
|
469
|
-
eventId: typeof exec?.callId === 'string' ? exec.callId : 'unknown',
|
|
470
|
-
toolName: OUTBOUND_ARTIFACT_TOOL,
|
|
471
|
-
}),
|
|
472
|
-
origin: Object.freeze({
|
|
473
|
-
sessionId,
|
|
474
|
-
turn,
|
|
475
|
-
callId: typeof exec?.callId === 'string' ? exec.callId : null,
|
|
476
|
-
}),
|
|
477
|
-
createdAt: Date.now(),
|
|
478
|
-
});
|
|
479
|
-
artifactStorage.set(artifact, {
|
|
480
|
-
path: storagePath,
|
|
481
|
-
materializing: 0,
|
|
482
|
-
materialized: false,
|
|
483
|
-
releaseRequested: false,
|
|
484
|
-
cleanupRequested: false,
|
|
485
|
-
cleanupDeferred: false,
|
|
486
|
-
onCleanup: () => this.#forgetArtifact(artifact),
|
|
577
|
+
const artifact = this.#buildArtifact(sessionId, turn, snapshot, {
|
|
578
|
+
callId: exec?.callId,
|
|
579
|
+
kind: 'tool-result',
|
|
580
|
+
toolName: OUTBOUND_ARTIFACT_TOOL,
|
|
487
581
|
});
|
|
488
582
|
const keyForTurn = turnKey(sessionId, turn);
|
|
489
583
|
let staged = this.#stagedTurns.get(keyForTurn);
|
|
@@ -526,6 +620,7 @@ export class OutboundArtifactRegistry {
|
|
|
526
620
|
const keyForTurn = turnKey(sessionId, turn);
|
|
527
621
|
const committed = this.#turns.get(keyForTurn);
|
|
528
622
|
this.#turns.delete(keyForTurn);
|
|
623
|
+
this.#adoptions.delete(keyForTurn);
|
|
529
624
|
if (!committed) return [];
|
|
530
625
|
if (signal?.aborted) {
|
|
531
626
|
for (const artifact of committed.values()) cleanupArtifactStorage(artifact);
|
|
@@ -553,6 +648,7 @@ export class OutboundArtifactRegistry {
|
|
|
553
648
|
]);
|
|
554
649
|
this.#turns.delete(keyForTurn);
|
|
555
650
|
this.#stagedTurns.delete(keyForTurn);
|
|
651
|
+
this.#adoptions.delete(keyForTurn);
|
|
556
652
|
for (const artifact of artifacts) cleanupArtifactStorage(artifact);
|
|
557
653
|
}
|
|
558
654
|
|
|
@@ -576,6 +672,7 @@ export class OutboundArtifactRegistry {
|
|
|
576
672
|
this.#consumersByPrompt.clear();
|
|
577
673
|
this.#consumersByTurn.clear();
|
|
578
674
|
this.#openTurns.clear();
|
|
675
|
+
this.#adoptions.clear();
|
|
579
676
|
}
|
|
580
677
|
|
|
581
678
|
#bindClaimSignal(turnKey, signal) {
|
|
@@ -732,7 +829,14 @@ export function installOutboundArtifactTool(ctx, { registry = outboundArtifactRe
|
|
|
732
829
|
ctx.on('agent/inbox/claimed', ({ agent, message, turn }) => {
|
|
733
830
|
registry.observeClaimedMessage(agent?.session, message, turn);
|
|
734
831
|
}, { global: true });
|
|
735
|
-
ctx.on('session/event', (session, event) =>
|
|
832
|
+
ctx.on('session/event', (session, event) => {
|
|
833
|
+
registry.observeSessionEvent(session, event, { logger });
|
|
834
|
+
if (event?.type === 'deliverables/presented') {
|
|
835
|
+
registry.adoptPresented(session, event, { logger })?.catch?.((error) => {
|
|
836
|
+
logger?.warn?.('[dsh-im] present adoption failed:', error?.message);
|
|
837
|
+
});
|
|
838
|
+
}
|
|
839
|
+
});
|
|
736
840
|
ctx.on('session/disposed', (session) => registry.disposeSession(session));
|
|
737
841
|
ctx.systemPrompt.context({
|
|
738
842
|
name: 'dsh-im:return-file',
|
|
@@ -79,7 +79,8 @@ function errorUnavailableReason(error) {
|
|
|
79
79
|
function mergeDefined(base, loaded) {
|
|
80
80
|
const merged = { ...base };
|
|
81
81
|
for (const key of [
|
|
82
|
-
'messageId', 'authorId', 'authorName', 'content', 'attachments', 'files', '
|
|
82
|
+
'messageId', 'authorId', 'authorName', 'content', 'attachments', 'files', 'images',
|
|
83
|
+
'unavailableReason',
|
|
83
84
|
]) {
|
|
84
85
|
if (loaded[key] !== undefined) merged[key] = loaded[key];
|
|
85
86
|
}
|
|
@@ -108,6 +109,7 @@ function normalizeReference(reference) {
|
|
|
108
109
|
const content = cleanString(reference.content, REPLY_CONTENT_MAX_CODE_POINTS, { multiline: true });
|
|
109
110
|
const { attachments, truncated: attachmentsTruncated } = cleanAttachments(reference.attachments);
|
|
110
111
|
const files = Array.isArray(reference.files) ? reference.files.filter((file) => file && typeof file.load === 'function') : [];
|
|
112
|
+
const images = Array.isArray(reference.images) ? reference.images.filter((image) => image && typeof image.load === 'function') : [];
|
|
111
113
|
let unavailableReason = cleanUnavailableReason(reference.unavailableReason);
|
|
112
114
|
if (!content.value && attachments.length === 0 && !unavailableReason) {
|
|
113
115
|
unavailableReason = 'not-delivered';
|
|
@@ -121,13 +123,14 @@ function normalizeReference(reference) {
|
|
|
121
123
|
...(content.value ? { content: content.value } : {}),
|
|
122
124
|
...(attachments.length > 0 ? { attachments } : {}),
|
|
123
125
|
...(files.length > 0 ? { files } : {}),
|
|
126
|
+
...(images.length > 0 ? { images } : {}),
|
|
124
127
|
...(unavailableReason ? { unavailableReason } : {}),
|
|
125
128
|
...(truncated ? { truncated: true } : {}),
|
|
126
129
|
};
|
|
127
130
|
}
|
|
128
131
|
|
|
129
132
|
function replyBlock(reference) {
|
|
130
|
-
const { files: _files, ...visibleReference } = reference;
|
|
133
|
+
const { files: _files, images: _images, ...visibleReference } = reference;
|
|
131
134
|
const json = JSON.stringify(visibleReference).replace(/[<>&]/gu, (character) => ({
|
|
132
135
|
'<': '\\u003c',
|
|
133
136
|
'>': '\\u003e',
|
|
@@ -142,7 +145,7 @@ export function hasReplyReference(message) {
|
|
|
142
145
|
|
|
143
146
|
export async function promptContentForInboundMessage(
|
|
144
147
|
message,
|
|
145
|
-
{ signal, deferImages = false, originalFiles } = {},
|
|
148
|
+
{ signal, deferImages = false, originalFiles, originalImages } = {},
|
|
146
149
|
) {
|
|
147
150
|
if (!hasReplyReference(message)) {
|
|
148
151
|
return promptContentForMessage(message, { signal, deferImages });
|
|
@@ -163,6 +166,18 @@ export async function promptContentForInboundMessage(
|
|
|
163
166
|
if (!Array.isArray(message.files)) message.files = [];
|
|
164
167
|
message.files.push(...reference.files);
|
|
165
168
|
}
|
|
169
|
+
// Images follow the same contract: they join the current message's images so
|
|
170
|
+
// the Harness downloads them together with the message's own pictures, and
|
|
171
|
+
// the quote block itself never carries their bytes or download URLs.
|
|
172
|
+
if (Array.isArray(originalImages)) {
|
|
173
|
+
if (!Array.isArray(message.images)) message.images = [];
|
|
174
|
+
message.images.length = 0;
|
|
175
|
+
message.images.push(...originalImages);
|
|
176
|
+
}
|
|
177
|
+
if (Array.isArray(reference.images) && reference.images.length > 0) {
|
|
178
|
+
if (!Array.isArray(message.images)) message.images = [];
|
|
179
|
+
message.images.push(...reference.images);
|
|
180
|
+
}
|
|
166
181
|
const currentContent = await promptContentForMessage(message, { signal, deferImages });
|
|
167
182
|
return [{ type: 'text', text: replyBlock(reference) }, ...currentContent];
|
|
168
183
|
}
|