@dsh-ray/assistant-delivery 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 +611 -2
- package/bin/dsh-restart-supervisor.js +102 -0
- package/cordis.patch.yml +29 -0
- package/lib/acceptance.d.ts +54 -0
- package/lib/acceptance.d.ts.map +1 -0
- package/lib/acceptance.js +2 -0
- package/lib/acceptance.js.map +1 -0
- package/lib/agent-runtime.d.ts +247 -0
- package/lib/agent-runtime.d.ts.map +1 -0
- package/lib/agent-runtime.js +4458 -0
- package/lib/agent-runtime.js.map +1 -0
- package/lib/approval-status-context.d.ts +8 -0
- package/lib/approval-status-context.d.ts.map +1 -0
- package/lib/approval-status-context.js +55 -0
- package/lib/approval-status-context.js.map +1 -0
- package/lib/attention-audit-store.d.ts +54 -0
- package/lib/attention-audit-store.d.ts.map +1 -0
- package/lib/attention-audit-store.js +213 -0
- package/lib/attention-audit-store.js.map +1 -0
- package/lib/attention-enforcement.d.ts +75 -0
- package/lib/attention-enforcement.d.ts.map +1 -0
- package/lib/attention-enforcement.js +84 -0
- package/lib/attention-enforcement.js.map +1 -0
- package/lib/attention.d.ts +208 -0
- package/lib/attention.d.ts.map +1 -0
- package/lib/attention.js +288 -0
- package/lib/attention.js.map +1 -0
- package/lib/canonical.d.ts +28 -0
- package/lib/canonical.d.ts.map +1 -0
- package/lib/canonical.js +190 -0
- package/lib/canonical.js.map +1 -0
- package/lib/coordinator.d.ts +134 -0
- package/lib/coordinator.d.ts.map +1 -0
- package/lib/coordinator.js +746 -0
- package/lib/coordinator.js.map +1 -0
- package/lib/feedback-command.d.ts +105 -0
- package/lib/feedback-command.d.ts.map +1 -0
- package/lib/feedback-command.js +547 -0
- package/lib/feedback-command.js.map +1 -0
- package/lib/foreground-observation.d.ts +66 -0
- package/lib/foreground-observation.d.ts.map +1 -0
- package/lib/foreground-observation.js +13 -0
- package/lib/foreground-observation.js.map +1 -0
- package/lib/foreground-termination.d.ts +31 -0
- package/lib/foreground-termination.d.ts.map +1 -0
- package/lib/foreground-termination.js +42 -0
- package/lib/foreground-termination.js.map +1 -0
- package/lib/goal-wake-types.d.ts +93 -0
- package/lib/goal-wake-types.d.ts.map +1 -0
- package/lib/goal-wake-types.js +70 -0
- package/lib/goal-wake-types.js.map +1 -0
- package/lib/in-process-reload-runtime.d.ts +120 -0
- package/lib/in-process-reload-runtime.d.ts.map +1 -0
- package/lib/in-process-reload-runtime.js +1280 -0
- package/lib/in-process-reload-runtime.js.map +1 -0
- package/lib/inbound-images.d.ts +38 -0
- package/lib/inbound-images.d.ts.map +1 -0
- package/lib/inbound-images.js +269 -0
- package/lib/inbound-images.js.map +1 -0
- package/lib/index.d.ts +41 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +25 -0
- package/lib/index.js.map +1 -0
- package/lib/learning-command.d.ts +40 -0
- package/lib/learning-command.d.ts.map +1 -0
- package/lib/learning-command.js +57 -0
- package/lib/learning-command.js.map +1 -0
- package/lib/native-termination.d.ts +12 -0
- package/lib/native-termination.d.ts.map +1 -0
- package/lib/native-termination.js +57 -0
- package/lib/native-termination.js.map +1 -0
- package/lib/native-web-owner.d.ts +97 -0
- package/lib/native-web-owner.d.ts.map +1 -0
- package/lib/native-web-owner.js +338 -0
- package/lib/native-web-owner.js.map +1 -0
- package/lib/operator-snapshot.d.ts +107 -0
- package/lib/operator-snapshot.d.ts.map +1 -0
- package/lib/operator-snapshot.js +1013 -0
- package/lib/operator-snapshot.js.map +1 -0
- package/lib/operator.d.ts +25 -0
- package/lib/operator.d.ts.map +1 -0
- package/lib/operator.js +48 -0
- package/lib/operator.js.map +1 -0
- package/lib/progress-attention.d.ts +55 -0
- package/lib/progress-attention.d.ts.map +1 -0
- package/lib/progress-attention.js +128 -0
- package/lib/progress-attention.js.map +1 -0
- package/lib/reply-replay.d.ts +52 -0
- package/lib/reply-replay.d.ts.map +1 -0
- package/lib/reply-replay.js +122 -0
- package/lib/reply-replay.js.map +1 -0
- package/lib/restart-native.d.ts +47 -0
- package/lib/restart-native.d.ts.map +1 -0
- package/lib/restart-native.js +170 -0
- package/lib/restart-native.js.map +1 -0
- package/lib/restart-runtime.d.ts +38 -0
- package/lib/restart-runtime.d.ts.map +1 -0
- package/lib/restart-runtime.js +335 -0
- package/lib/restart-runtime.js.map +1 -0
- package/lib/restart-store.d.ts +132 -0
- package/lib/restart-store.d.ts.map +1 -0
- package/lib/restart-store.js +757 -0
- package/lib/restart-store.js.map +1 -0
- package/lib/restart-supervisor.d.ts +129 -0
- package/lib/restart-supervisor.d.ts.map +1 -0
- package/lib/restart-supervisor.js +615 -0
- package/lib/restart-supervisor.js.map +1 -0
- package/lib/service.d.ts +1279 -0
- package/lib/service.d.ts.map +1 -0
- package/lib/service.js +8694 -0
- package/lib/service.js.map +1 -0
- package/lib/session-commands.d.ts +52 -0
- package/lib/session-commands.d.ts.map +1 -0
- package/lib/session-commands.js +180 -0
- package/lib/session-commands.js.map +1 -0
- package/lib/session-lease-runtime.d.ts +70 -0
- package/lib/session-lease-runtime.d.ts.map +1 -0
- package/lib/session-lease-runtime.js +395 -0
- package/lib/session-lease-runtime.js.map +1 -0
- package/lib/session-lease-types.d.ts +27 -0
- package/lib/session-lease-types.d.ts.map +1 -0
- package/lib/session-lease-types.js +2 -0
- package/lib/session-lease-types.js.map +1 -0
- package/lib/sqlite.d.ts +8 -0
- package/lib/sqlite.d.ts.map +1 -0
- package/lib/sqlite.js +1665 -0
- package/lib/sqlite.js.map +1 -0
- package/lib/store.d.ts +1267 -0
- package/lib/store.d.ts.map +1 -0
- package/lib/store.js +8039 -0
- package/lib/store.js.map +1 -0
- package/lib/tools.d.ts +4 -0
- package/lib/tools.d.ts.map +1 -0
- package/lib/tools.js +73 -0
- package/lib/tools.js.map +1 -0
- package/lib/types.d.ts +1091 -0
- package/lib/types.d.ts.map +1 -0
- package/lib/types.js +10 -0
- package/lib/types.js.map +1 -0
- package/lib/version-query.d.ts +77 -0
- package/lib/version-query.d.ts.map +1 -0
- package/lib/version-query.js +2208 -0
- package/lib/version-query.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/work-item-engineering-context.d.ts +127 -0
- package/lib/work-item-engineering-context.d.ts.map +1 -0
- package/lib/work-item-engineering-context.js +151 -0
- package/lib/work-item-engineering-context.js.map +1 -0
- package/lib/work-item-feedback-schema.d.ts +2 -0
- package/lib/work-item-feedback-schema.d.ts.map +1 -0
- package/lib/work-item-feedback-schema.js +29 -0
- package/lib/work-item-feedback-schema.js.map +1 -0
- package/lib/work-item-feedback-store.d.ts +29 -0
- package/lib/work-item-feedback-store.d.ts.map +1 -0
- package/lib/work-item-feedback-store.js +111 -0
- package/lib/work-item-feedback-store.js.map +1 -0
- package/lib/work-item-feedback.d.ts +157 -0
- package/lib/work-item-feedback.d.ts.map +1 -0
- package/lib/work-item-feedback.js +2 -0
- package/lib/work-item-feedback.js.map +1 -0
- package/lib/work-item-replies-schema.d.ts +3 -0
- package/lib/work-item-replies-schema.d.ts.map +1 -0
- package/lib/work-item-replies-schema.js +45 -0
- package/lib/work-item-replies-schema.js.map +1 -0
- package/lib/work-item-replies-store.d.ts +43 -0
- package/lib/work-item-replies-store.d.ts.map +1 -0
- package/lib/work-item-replies-store.js +203 -0
- package/lib/work-item-replies-store.js.map +1 -0
- package/lib/work-item-replies.d.ts +93 -0
- package/lib/work-item-replies.d.ts.map +1 -0
- package/lib/work-item-replies.js +15 -0
- package/lib/work-item-replies.js.map +1 -0
- package/lib/workflow-auto-producer.d.ts +37 -0
- package/lib/workflow-auto-producer.d.ts.map +1 -0
- package/lib/workflow-auto-producer.js +58 -0
- package/lib/workflow-auto-producer.js.map +1 -0
- package/lib/workflow-command.d.ts +16 -0
- package/lib/workflow-command.d.ts.map +1 -0
- package/lib/workflow-command.js +52 -0
- package/lib/workflow-command.js.map +1 -0
- package/package.json +181 -3
|
@@ -0,0 +1,4458 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { mkdir, stat } from 'node:fs/promises';
|
|
3
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
4
|
+
import { installModelSelection, } from '@deepseek-ai/dsh-agent';
|
|
5
|
+
import { contentHasImage, createUserMessage, ReasoningEffortId, } from '@deepseek-ai/dsh-llm';
|
|
6
|
+
import { TOOL_ABORTED_BEFORE_DISPATCH } from '@deepseek-ai/dsh-tools';
|
|
7
|
+
import { setSandboxMode } from '@deepseek-ai/dsh-sandbox-policy';
|
|
8
|
+
import { isAppendSurfaceEvent, SessionId } from '@deepseek-ai/dsh-session';
|
|
9
|
+
import { setApprovalPolicy, } from '@deepseek-ai/dsh-user-approval';
|
|
10
|
+
import { approvalReviewerOf, setApprovalReviewer, waitForApprovalReviewerSessionEventReady, } from '@dsh-ray/assistant-policy';
|
|
11
|
+
import { resolveLlmRouteCapability } from '@dsh-ray/llm-route-capabilities';
|
|
12
|
+
import { externalPrincipalId } from './canonical.js';
|
|
13
|
+
import { observeNativeTermination } from './native-termination.js';
|
|
14
|
+
import { feedbackSignalInput, feedbackUsage, parseFeedbackCommand, } from './feedback-command.js';
|
|
15
|
+
import { objectiveStateMessage } from './feedback-command.js';
|
|
16
|
+
import { learningCommandUsage, parseLearningCommand, serializeLearningExport, } from './learning-command.js';
|
|
17
|
+
import { attachRestartRun, restartDigest, restartContinuationText } from './restart-runtime.js';
|
|
18
|
+
import { admitRestartContinuation, createRestartContinuation } from './restart-native.js';
|
|
19
|
+
import { renderOwnerApprovalStatus } from './approval-status-context.js';
|
|
20
|
+
import { isExactDeliveryCommand, learningDispatchRecoveryCode, parseDeliveryCommand, parseOwnerSelfIterationCommand, parseOwnerVersionQuery, permissionDispatchRecoveryCode, } from './session-commands.js';
|
|
21
|
+
import { collectDeliveryVersionReport, formatAssistantVersionSummary, } from './version-query.js';
|
|
22
|
+
import { DeliveryStoreError } from './store.js';
|
|
23
|
+
import { SessionLeaseUnavailable } from './session-lease-runtime.js';
|
|
24
|
+
import { isDeliveryGoalWakeDeadline } from './goal-wake-types.js';
|
|
25
|
+
import { parseWorkflowCommand, workflowCommandUsage, } from './workflow-command.js';
|
|
26
|
+
const SAFE_NATIVE_COMMANDS = new Set(['compact']);
|
|
27
|
+
const ownerSelfIterationUsage = [
|
|
28
|
+
'自迭代控制命令(仅限 owner,不进入模型):',
|
|
29
|
+
'- /autonomy enable(或「开启自迭代」)',
|
|
30
|
+
'- /autonomy disable(或「关闭自迭代」)',
|
|
31
|
+
'- /autonomy upgrade(或「升级整体助手」)',
|
|
32
|
+
'- /autonomy version(或 /version:查看助手版本与自迭代统计)',
|
|
33
|
+
].join('\n');
|
|
34
|
+
function formatOwnerSelfIterationResult(action, result) {
|
|
35
|
+
if (result.ok) {
|
|
36
|
+
if (typeof result.message === 'string' && result.message.trim() !== '')
|
|
37
|
+
return result.message;
|
|
38
|
+
if (action === 'enableSelfIteration' || result.state === 'enabled') {
|
|
39
|
+
return '已开启当前助手自迭代能力;受保护的核心交互与策略组件保持启用。';
|
|
40
|
+
}
|
|
41
|
+
if (action === 'disableSelfIteration' || result.state === 'disabled') {
|
|
42
|
+
return '已关闭当前助手自迭代能力;核心对话与控制通道仍保持可用。';
|
|
43
|
+
}
|
|
44
|
+
return '已完成整体助手升级、健康检查与恢复;当前服务可用。';
|
|
45
|
+
}
|
|
46
|
+
const detail = result.error ?? result.message ?? result.reason;
|
|
47
|
+
const prefix = action === 'enableSelfIteration'
|
|
48
|
+
? '开启自迭代未完成'
|
|
49
|
+
: action === 'disableSelfIteration'
|
|
50
|
+
? '关闭自迭代未完成'
|
|
51
|
+
: '升级整体助手未完成';
|
|
52
|
+
return typeof detail === 'string' && detail.trim() !== ''
|
|
53
|
+
? `${prefix}:${detail}`
|
|
54
|
+
: `${prefix};未修改现有配置。`;
|
|
55
|
+
}
|
|
56
|
+
class AgentTaskTimeoutError extends Error {
|
|
57
|
+
constructor() {
|
|
58
|
+
super('assistant-delivery: foreground task exceeded its execution deadline');
|
|
59
|
+
this.name = 'AgentTaskTimeoutError';
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
class UserSessionCancellation extends Error {
|
|
63
|
+
command;
|
|
64
|
+
constructor(command) {
|
|
65
|
+
super(`assistant-delivery: session task cancelled by /${command}`);
|
|
66
|
+
this.command = command;
|
|
67
|
+
this.name = 'UserSessionCancellation';
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
const MAX_CATALOG_PROVIDERS = 20;
|
|
71
|
+
const MAX_CATALOG_MODELS = 200;
|
|
72
|
+
const MAX_PROGRESS_TODOS = 20;
|
|
73
|
+
const MAX_PROGRESS_TEXT_CHARS = 240;
|
|
74
|
+
const MAX_PROGRESS_TOOL_PREVIEW_CHARS = 1_500;
|
|
75
|
+
const MAX_PROGRESS_JSON_INPUT_CHARS = 32_768;
|
|
76
|
+
const MAX_PROGRESS_JSON_DEPTH = 16;
|
|
77
|
+
const MAX_PROGRESS_JSON_NODES = 500;
|
|
78
|
+
const MAX_PROGRESS_RESULT_BLOCKS = 100;
|
|
79
|
+
const REDACTED_PROGRESS_VALUE = '[REDACTED]';
|
|
80
|
+
const TRUNCATED_PROGRESS_VALUE = '[TRUNCATED]';
|
|
81
|
+
const PROGRESS_ASSIGNMENT_KEY = '([A-Za-z_][A-Za-z0-9_.-]{0,127})';
|
|
82
|
+
const PROGRESS_ASSIGNMENT_START = new RegExp(`(^|[^A-Za-z0-9_])(["']?)${PROGRESS_ASSIGNMENT_KEY}\\2(\\s*[:=]\\s*)`, 'giu');
|
|
83
|
+
const ESCAPED_QUOTED_PROGRESS_ASSIGNMENT_START = new RegExp(`(^|[^A-Za-z0-9_])\\\\+(["'])${PROGRESS_ASSIGNMENT_KEY}\\\\+\\2(\\s*[:=]\\s*)`, 'giu');
|
|
84
|
+
class DurableAgentIdentityError extends Error {
|
|
85
|
+
}
|
|
86
|
+
class AutomaticCompletionUnavailableError extends Error {
|
|
87
|
+
}
|
|
88
|
+
class AutomaticCompletionAuthorizationError extends Error {
|
|
89
|
+
state;
|
|
90
|
+
constructor(state) {
|
|
91
|
+
super(`assistant-delivery: automatic completion authorization is ${state}`);
|
|
92
|
+
this.state = state;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
class ApprovalReviewerReaderUnavailableError extends Error {
|
|
96
|
+
constructor(cause) {
|
|
97
|
+
super('assistant-delivery: approval reviewer persistence reader is not proven', { cause });
|
|
98
|
+
this.name = 'ApprovalReviewerReaderUnavailableError';
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
class AdapterToolCallProtocolError extends Error {
|
|
102
|
+
provider;
|
|
103
|
+
model;
|
|
104
|
+
presetId;
|
|
105
|
+
constructor(provider, model, presetId) {
|
|
106
|
+
super(`assistant-delivery: adapter ${provider}/${model} declares no DSH tool-call protocol`);
|
|
107
|
+
this.provider = provider;
|
|
108
|
+
this.model = model;
|
|
109
|
+
this.presetId = presetId;
|
|
110
|
+
this.name = 'AdapterToolCallProtocolError';
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
class ImageCapabilityAdmissionError extends Error {
|
|
114
|
+
provider;
|
|
115
|
+
model;
|
|
116
|
+
constructor(provider, model) {
|
|
117
|
+
super(`assistant-delivery: ${provider}/${model} does not declare image input support`);
|
|
118
|
+
this.provider = provider;
|
|
119
|
+
this.model = model;
|
|
120
|
+
this.name = 'ImageCapabilityAdmissionError';
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
function requireAdapterToolCallProtocol(llm, provider, model, presetId, toolCount) {
|
|
124
|
+
if (toolCount === 0)
|
|
125
|
+
return;
|
|
126
|
+
if (resolveLlmRouteCapability(llm, provider, model)?.toolCalls === 'none') {
|
|
127
|
+
throw new AdapterToolCallProtocolError(provider, model, presetId);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
function adapterToolCallProtocolReply(error) {
|
|
131
|
+
return {
|
|
132
|
+
text: `当前路由 ${error.provider}/${error.model} 的 adapter 明确声明未实现统一 DSH tool-call 协议,`
|
|
133
|
+
+ `因此无法承载 preset “${error.presetId}” 已挂载的工具。`
|
|
134
|
+
+ '这不是模型权限差异;请升级或修复该 provider adapter,使其实现 native/bridge 协议。',
|
|
135
|
+
format: 'plain',
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
function imageCapabilityReply(error) {
|
|
139
|
+
return {
|
|
140
|
+
text: `当前模型 ${error.provider}/${error.model} 不支持图片输入。`
|
|
141
|
+
+ '请发送 /model 切换到明确支持图片的模型后重新发送图片。',
|
|
142
|
+
format: 'plain',
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
async function requireImageCapability(llm, provider, model, signal) {
|
|
146
|
+
const info = await llm.resolveModelInfo(provider, model, signal);
|
|
147
|
+
if (info.inputModalities?.includes('image') !== true) {
|
|
148
|
+
throw new ImageCapabilityAdmissionError(provider, model);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
function boundedProgressText(value) {
|
|
152
|
+
return [...value].slice(0, MAX_PROGRESS_TEXT_CHARS).join('');
|
|
153
|
+
}
|
|
154
|
+
function boundedProgressToolPreview(value) {
|
|
155
|
+
const trimmed = value.trim();
|
|
156
|
+
const characters = [...trimmed];
|
|
157
|
+
return characters.length <= MAX_PROGRESS_TOOL_PREVIEW_CHARS
|
|
158
|
+
? trimmed
|
|
159
|
+
: `${characters.slice(0, MAX_PROGRESS_TOOL_PREVIEW_CHARS - 1).join('')}…`;
|
|
160
|
+
}
|
|
161
|
+
function redactProgressText(value) {
|
|
162
|
+
const common = redactEscapedKeyProgressAssignments(value)
|
|
163
|
+
.replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?(?:-----END [^-]*PRIVATE KEY-----|$)/giu, '[REDACTED PRIVATE KEY]')
|
|
164
|
+
.replace(/\b([a-z][a-z0-9+.-]*:\/\/)[^/\s@]+@/giu, '$1[REDACTED]@')
|
|
165
|
+
.replace(/\b((?:proxy-)?authorization\s*[:=]\s*)(?:basic|bearer)\s+[^\s,;]+/giu, '$1[REDACTED]');
|
|
166
|
+
return redactProgressAssignments(common)
|
|
167
|
+
.replace(/\b(?:github_pat_[A-Za-z0-9_]{20,}|gh[pousr]_[A-Za-z0-9]{20,}|(?:sk|xai)-[A-Za-z0-9_-]{8,})\b/gu, REDACTED_PROGRESS_VALUE)
|
|
168
|
+
.replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/gu, REDACTED_PROGRESS_VALUE);
|
|
169
|
+
}
|
|
170
|
+
function isSensitiveProgressKey(key) {
|
|
171
|
+
const words = key.normalize('NFKC')
|
|
172
|
+
.replace(/([a-z\d])([A-Z])/gu, '$1_$2')
|
|
173
|
+
.toLowerCase()
|
|
174
|
+
.split(/[^a-z\d]+/gu)
|
|
175
|
+
.filter(Boolean);
|
|
176
|
+
const joined = words.join('');
|
|
177
|
+
return words.some(word => [
|
|
178
|
+
'auth', 'authorization', 'bearer', 'cookie', 'cookies', 'credential', 'credentials',
|
|
179
|
+
'password', 'passwd', 'secret', 'session', 'token',
|
|
180
|
+
].includes(word))
|
|
181
|
+
|| ['apikey', 'accesskey', 'privatekey'].some(phrase => joined.includes(phrase))
|
|
182
|
+
|| words.some((word, index) => ['api', 'access', 'private'].includes(word) && words[index + 1] === 'key');
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Text credentials have no trustworthy terminator: quotes may be malformed or multiply escaped,
|
|
186
|
+
* while spaces, semicolons, and nested assignments can still belong to the value. Once a key is
|
|
187
|
+
* recognized, fail closed through the logical line instead of exposing an arbitrary suffix.
|
|
188
|
+
*/
|
|
189
|
+
function redactProgressAssignments(value) {
|
|
190
|
+
let retainedIndex = 0;
|
|
191
|
+
let redacted = '';
|
|
192
|
+
PROGRESS_ASSIGNMENT_START.lastIndex = 0;
|
|
193
|
+
for (let match = PROGRESS_ASSIGNMENT_START.exec(value); match !== null; match = PROGRESS_ASSIGNMENT_START.exec(value)) {
|
|
194
|
+
const key = match[3];
|
|
195
|
+
if (key === undefined || !isSensitiveProgressKey(key)) {
|
|
196
|
+
// The prefix regex consumes the separator of an innocent outer field. Resume inside that
|
|
197
|
+
// match so nested assignments on the same line remain visible to this scanner.
|
|
198
|
+
PROGRESS_ASSIGNMENT_START.lastIndex = match.index + 1;
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
201
|
+
const valueStart = match.index + match[0].length;
|
|
202
|
+
const lineEnd = progressRedactionEnd(value, valueStart);
|
|
203
|
+
redacted += value.slice(retainedIndex, valueStart) + REDACTED_PROGRESS_VALUE;
|
|
204
|
+
retainedIndex = lineEnd;
|
|
205
|
+
PROGRESS_ASSIGNMENT_START.lastIndex = lineEnd;
|
|
206
|
+
}
|
|
207
|
+
PROGRESS_ASSIGNMENT_START.lastIndex = 0;
|
|
208
|
+
return redacted + value.slice(retainedIndex);
|
|
209
|
+
}
|
|
210
|
+
/** Escaped JSON keys inside a log string cannot be parsed as the outer text; fail closed by line. */
|
|
211
|
+
function redactEscapedKeyProgressAssignments(value) {
|
|
212
|
+
let retainedIndex = 0;
|
|
213
|
+
let redacted = '';
|
|
214
|
+
ESCAPED_QUOTED_PROGRESS_ASSIGNMENT_START.lastIndex = 0;
|
|
215
|
+
for (let match = ESCAPED_QUOTED_PROGRESS_ASSIGNMENT_START.exec(value); match !== null; match = ESCAPED_QUOTED_PROGRESS_ASSIGNMENT_START.exec(value)) {
|
|
216
|
+
const key = match[3];
|
|
217
|
+
if (key === undefined || !isSensitiveProgressKey(key)) {
|
|
218
|
+
ESCAPED_QUOTED_PROGRESS_ASSIGNMENT_START.lastIndex = match.index + 1;
|
|
219
|
+
continue;
|
|
220
|
+
}
|
|
221
|
+
const valueStart = match.index + match[0].length;
|
|
222
|
+
const lineEnd = progressRedactionEnd(value, valueStart);
|
|
223
|
+
redacted += value.slice(retainedIndex, valueStart) + REDACTED_PROGRESS_VALUE;
|
|
224
|
+
retainedIndex = lineEnd;
|
|
225
|
+
ESCAPED_QUOTED_PROGRESS_ASSIGNMENT_START.lastIndex = lineEnd;
|
|
226
|
+
}
|
|
227
|
+
ESCAPED_QUOTED_PROGRESS_ASSIGNMENT_START.lastIndex = 0;
|
|
228
|
+
return redacted + value.slice(retainedIndex);
|
|
229
|
+
}
|
|
230
|
+
function progressRedactionEnd(value, start) {
|
|
231
|
+
let cursor = start;
|
|
232
|
+
while (cursor < value.length) {
|
|
233
|
+
const carriageReturn = value.indexOf('\r', cursor);
|
|
234
|
+
const lineFeed = value.indexOf('\n', cursor);
|
|
235
|
+
const candidates = [carriageReturn, lineFeed].filter(index => index >= 0);
|
|
236
|
+
if (candidates.length === 0)
|
|
237
|
+
return value.length;
|
|
238
|
+
const boundary = Math.min(...candidates);
|
|
239
|
+
if (value[boundary - 1] !== '\\')
|
|
240
|
+
return boundary;
|
|
241
|
+
cursor = boundary + (value[boundary] === '\r' && value[boundary + 1] === '\n' ? 2 : 1);
|
|
242
|
+
}
|
|
243
|
+
return value.length;
|
|
244
|
+
}
|
|
245
|
+
function redactProgressJson(value, state, depth = 0) {
|
|
246
|
+
state.nodes += 1;
|
|
247
|
+
if (depth > MAX_PROGRESS_JSON_DEPTH || state.nodes > MAX_PROGRESS_JSON_NODES) {
|
|
248
|
+
return TRUNCATED_PROGRESS_VALUE;
|
|
249
|
+
}
|
|
250
|
+
if (Array.isArray(value)) {
|
|
251
|
+
const items = value.slice(0, 100).map(item => redactProgressJson(item, state, depth + 1));
|
|
252
|
+
if (value.length > items.length)
|
|
253
|
+
items.push(TRUNCATED_PROGRESS_VALUE);
|
|
254
|
+
return items;
|
|
255
|
+
}
|
|
256
|
+
if (value !== null && typeof value === 'object') {
|
|
257
|
+
const entries = Object.entries(value).slice(0, 100).map(([key, item]) => [
|
|
258
|
+
key,
|
|
259
|
+
isSensitiveProgressKey(key)
|
|
260
|
+
? REDACTED_PROGRESS_VALUE
|
|
261
|
+
: redactProgressJson(item, state, depth + 1),
|
|
262
|
+
]);
|
|
263
|
+
if (Object.keys(value).length > entries.length)
|
|
264
|
+
entries.push(['…', TRUNCATED_PROGRESS_VALUE]);
|
|
265
|
+
return Object.fromEntries(entries);
|
|
266
|
+
}
|
|
267
|
+
return typeof value === 'string' ? redactProgressText(value) : value;
|
|
268
|
+
}
|
|
269
|
+
function progressArgumentsPlaceholder(value) {
|
|
270
|
+
const characters = [...redactProgressText(value.slice(0, MAX_PROGRESS_JSON_INPUT_CHARS))];
|
|
271
|
+
let retained = Math.min(characters.length, MAX_PROGRESS_TOOL_PREVIEW_CHARS);
|
|
272
|
+
while (retained >= 0) {
|
|
273
|
+
const encoded = JSON.stringify({
|
|
274
|
+
truncated: true,
|
|
275
|
+
preview: characters.slice(0, retained).join(''),
|
|
276
|
+
});
|
|
277
|
+
if ([...encoded].length <= MAX_PROGRESS_TOOL_PREVIEW_CHARS)
|
|
278
|
+
return encoded;
|
|
279
|
+
retained = retained === 0 ? -1 : Math.floor(retained * 0.75);
|
|
280
|
+
}
|
|
281
|
+
return '{"truncated":true}';
|
|
282
|
+
}
|
|
283
|
+
function progressArgumentsPreview(value) {
|
|
284
|
+
if (value.trim() === '')
|
|
285
|
+
return '{}';
|
|
286
|
+
// Never publish raw malformed or oversized model output. Normal tool calls are valid JSON; when
|
|
287
|
+
// that invariant fails, a status marker is more useful than a best-effort secret scrubber.
|
|
288
|
+
if (value.length > MAX_PROGRESS_JSON_INPUT_CHARS)
|
|
289
|
+
return '{"truncated":true}';
|
|
290
|
+
try {
|
|
291
|
+
const encoded = JSON.stringify(redactProgressJson(JSON.parse(value), { nodes: 0 }), null, 2);
|
|
292
|
+
if (encoded === undefined)
|
|
293
|
+
return '{"invalidJson":true}';
|
|
294
|
+
return [...encoded].length <= MAX_PROGRESS_TOOL_PREVIEW_CHARS
|
|
295
|
+
? encoded
|
|
296
|
+
: progressArgumentsPlaceholder(encoded);
|
|
297
|
+
}
|
|
298
|
+
catch {
|
|
299
|
+
return '{"invalidJson":true}';
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
function redactProgressResultText(value) {
|
|
303
|
+
if (value.length > MAX_PROGRESS_JSON_INPUT_CHARS)
|
|
304
|
+
return '{"truncated":true}';
|
|
305
|
+
const trimmed = value.trim();
|
|
306
|
+
if ((trimmed.startsWith('{') && trimmed.endsWith('}'))
|
|
307
|
+
|| (trimmed.startsWith('[') && trimmed.endsWith(']'))) {
|
|
308
|
+
try {
|
|
309
|
+
const encoded = JSON.stringify(redactProgressJson(JSON.parse(trimmed), { nodes: 0 }), null, 2);
|
|
310
|
+
if (encoded !== undefined)
|
|
311
|
+
return encoded;
|
|
312
|
+
}
|
|
313
|
+
catch {
|
|
314
|
+
// Fall through to conservative line-oriented handling for JSON-like logs and fragments.
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
return redactProgressText(value);
|
|
318
|
+
}
|
|
319
|
+
/** Bounded, common-credential-shape filtering for an owner learning reply. */
|
|
320
|
+
export function redactOwnerLearningReply(value, maxBytes) {
|
|
321
|
+
const filtered = redactProgressResultText(value);
|
|
322
|
+
const bytes = Buffer.from(filtered, 'utf8');
|
|
323
|
+
let end = Math.min(bytes.length, maxBytes);
|
|
324
|
+
while (end > 0 && end < bytes.length && (bytes[end] & 0xc0) === 0x80)
|
|
325
|
+
end--;
|
|
326
|
+
return Object.freeze({ text: bytes.subarray(0, end).toString('utf8'), truncated: end < bytes.length,
|
|
327
|
+
redacted: filtered !== value });
|
|
328
|
+
}
|
|
329
|
+
function progressResultPreview(content, depth = 0) {
|
|
330
|
+
if (depth > 4)
|
|
331
|
+
return TRUNCATED_PROGRESS_VALUE;
|
|
332
|
+
const parts = [];
|
|
333
|
+
let approximateLength = 0;
|
|
334
|
+
const append = (value) => {
|
|
335
|
+
if (approximateLength >= MAX_PROGRESS_TOOL_PREVIEW_CHARS * 2 || value === '')
|
|
336
|
+
return;
|
|
337
|
+
const retained = value.slice(0, MAX_PROGRESS_TOOL_PREVIEW_CHARS * 2 - approximateLength);
|
|
338
|
+
parts.push(retained);
|
|
339
|
+
approximateLength += retained.length;
|
|
340
|
+
};
|
|
341
|
+
let blockCount = 0;
|
|
342
|
+
for (const block of content) {
|
|
343
|
+
if (approximateLength >= MAX_PROGRESS_TOOL_PREVIEW_CHARS * 2)
|
|
344
|
+
break;
|
|
345
|
+
if (blockCount >= MAX_PROGRESS_RESULT_BLOCKS) {
|
|
346
|
+
append(TRUNCATED_PROGRESS_VALUE);
|
|
347
|
+
break;
|
|
348
|
+
}
|
|
349
|
+
blockCount += 1;
|
|
350
|
+
if (block.type === 'text')
|
|
351
|
+
append(redactProgressResultText(block.text));
|
|
352
|
+
else if (block.type === 'image')
|
|
353
|
+
append('[图片]');
|
|
354
|
+
else if (block.type === 'tool-call') {
|
|
355
|
+
append(`${block.name}\n${progressArgumentsPreview(block.arguments)}`);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
return boundedProgressToolPreview(redactProgressText(parts.join('\n')));
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* Convert one durable session fact into a bounded, user-visible progress update.
|
|
362
|
+
* Reasoning/thinking content and provider error messages never cross this boundary. Tool calls/results
|
|
363
|
+
* contribute bounded previews with common credential shapes redacted; the channel still decides
|
|
364
|
+
* whether its current audience is private enough to render those previews.
|
|
365
|
+
*
|
|
366
|
+
* A DSH `reasoning` block is explicitly thinking content and is not guaranteed to be a public
|
|
367
|
+
* summary, even after assembly into `assistant/message`. `step/start` therefore provides the only
|
|
368
|
+
* reasoning-independent phase label, so a turn reports progress without exposing hidden thought.
|
|
369
|
+
*/
|
|
370
|
+
export function deliveryProgressFromSessionEvent(event) {
|
|
371
|
+
if (event.type === 'step/start') {
|
|
372
|
+
const step = Number(event.data.step);
|
|
373
|
+
return {
|
|
374
|
+
kind: 'step',
|
|
375
|
+
text: Number.isSafeInteger(step) && step > 1 ? `正在继续处理(第 ${step} 步)…` : '正在处理请求…',
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
if (event.type === 'assistant/message') {
|
|
379
|
+
return undefined;
|
|
380
|
+
}
|
|
381
|
+
if (event.type === 'approval/asked') {
|
|
382
|
+
// approval/asked is appended before the review waterfall runs, so this label
|
|
383
|
+
// must stay accurate for both the (usually fast) automatic review and a real
|
|
384
|
+
// human escalation (which additionally renders a separate allow/reject card).
|
|
385
|
+
// A tool name here is policy-controlled, but bound it like every other field.
|
|
386
|
+
return { kind: 'step', text: `正在确认工具「${boundedProgressText(event.data.toolName)}」的调用权限…` };
|
|
387
|
+
}
|
|
388
|
+
if (event.type === 'approval/decided') {
|
|
389
|
+
switch (event.data.outcome) {
|
|
390
|
+
case 'allowed-once': return { kind: 'step', text: '已获批准,继续执行…' };
|
|
391
|
+
case 'rejected': return { kind: 'step', text: '您已拒绝本次操作,该操作不会执行。' };
|
|
392
|
+
case 'cancelled': return { kind: 'step', text: '本次审批已取消,该操作不会执行。' };
|
|
393
|
+
case 'unavailable': return { kind: 'step', text: '审批通道不可用或等待已超时,该操作不会执行。请检查审批卡片或 Web 连接后重新发起。' };
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
if (event.type === 'tool/call') {
|
|
397
|
+
if (event.data.name === 'ask_user_question') {
|
|
398
|
+
return { kind: 'step', text: '等待您的回答…' };
|
|
399
|
+
}
|
|
400
|
+
const argumentsPreview = progressArgumentsPreview(event.data.arguments);
|
|
401
|
+
return {
|
|
402
|
+
kind: 'tool-started',
|
|
403
|
+
callId: String(event.data.callId),
|
|
404
|
+
toolName: boundedProgressText(event.data.name),
|
|
405
|
+
...(argumentsPreview === '' ? {} : { argumentsPreview }),
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
if (event.type === 'tool/result') {
|
|
409
|
+
// Replacement copies belong only to the model-visible surface (for example after compaction).
|
|
410
|
+
// Human progress is an append-origin transcript, so projecting a replacement would make an
|
|
411
|
+
// old tool result look like a tool invocation from the active turn.
|
|
412
|
+
if (!isAppendSurfaceEvent(event))
|
|
413
|
+
return undefined;
|
|
414
|
+
const result = event.data.message;
|
|
415
|
+
const callId = result.toolCallId;
|
|
416
|
+
if (callId === undefined)
|
|
417
|
+
return undefined;
|
|
418
|
+
const resultPreview = progressResultPreview(result.content);
|
|
419
|
+
const code = event.data.error?.code;
|
|
420
|
+
return {
|
|
421
|
+
kind: 'tool-finished',
|
|
422
|
+
callId: String(callId),
|
|
423
|
+
failed: event.data.error !== undefined || result.isError === true,
|
|
424
|
+
...(resultPreview === '' ? {} : { resultPreview }),
|
|
425
|
+
...(code === undefined ? {} : { code: boundedProgressText(code) }),
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
if (event.type === 'todo/write') {
|
|
429
|
+
return { kind: 'todos', todos: event.data.todos.slice(0, MAX_PROGRESS_TODOS).map(todo => ({
|
|
430
|
+
content: boundedProgressText(todo.content),
|
|
431
|
+
status: todo.status,
|
|
432
|
+
})) };
|
|
433
|
+
}
|
|
434
|
+
return undefined;
|
|
435
|
+
}
|
|
436
|
+
function parseModelRoute(value) {
|
|
437
|
+
const separator = value.indexOf('/');
|
|
438
|
+
if (separator <= 0 || separator === value.length - 1)
|
|
439
|
+
return undefined;
|
|
440
|
+
const provider = value.slice(0, separator).trim();
|
|
441
|
+
const model = value.slice(separator + 1).trim();
|
|
442
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$/u.test(provider)
|
|
443
|
+
|| model.length > 512 || /[\s\p{Cc}]/u.test(model))
|
|
444
|
+
return undefined;
|
|
445
|
+
return { provider, model };
|
|
446
|
+
}
|
|
447
|
+
function parseModelUseTarget(value) {
|
|
448
|
+
const tokens = value === '' ? [] : value.split(/\s+/u);
|
|
449
|
+
if (tokens.length < 1 || tokens.length > 2)
|
|
450
|
+
return undefined;
|
|
451
|
+
const base = parseModelRoute(tokens[0]);
|
|
452
|
+
if (base === undefined)
|
|
453
|
+
return undefined;
|
|
454
|
+
if (tokens.length === 1)
|
|
455
|
+
return base;
|
|
456
|
+
const effort = tokens[1];
|
|
457
|
+
if (effort.length === 0 || effort.length > 128 || /[\s\p{Cc}]/u.test(effort))
|
|
458
|
+
return undefined;
|
|
459
|
+
return { ...base, reasoningEffort: effort };
|
|
460
|
+
}
|
|
461
|
+
function modelCommand(command) {
|
|
462
|
+
return command?.name === 'model' ? command.rawInput.trim() : undefined;
|
|
463
|
+
}
|
|
464
|
+
function permissionCommand(command) {
|
|
465
|
+
return command?.name === 'permission' || command?.name === 'permissions'
|
|
466
|
+
? command.rawInput.trim()
|
|
467
|
+
: undefined;
|
|
468
|
+
}
|
|
469
|
+
function parsePermissionCommand(argument) {
|
|
470
|
+
const tokens = argument === '' ? [] : argument.split(/\s+/u);
|
|
471
|
+
if (tokens.length === 0)
|
|
472
|
+
return { kind: 'show' };
|
|
473
|
+
if (tokens.length === 1 && tokens[0] === 'ask')
|
|
474
|
+
return { kind: 'switch', level: 'ask' };
|
|
475
|
+
if (tokens.length === 1 && tokens[0] === 'auto')
|
|
476
|
+
return { kind: 'switch', level: 'auto' };
|
|
477
|
+
if (tokens.length === 1 && tokens[0] === 'full')
|
|
478
|
+
return { kind: 'warn-full' };
|
|
479
|
+
if (tokens.length === 2 && tokens[0] === 'full' && tokens[1] === 'confirm') {
|
|
480
|
+
return { kind: 'switch', level: 'full' };
|
|
481
|
+
}
|
|
482
|
+
return { kind: 'invalid' };
|
|
483
|
+
}
|
|
484
|
+
const PERMISSION_PICKER_OPERATION_METADATA = 'permission-picker-operation';
|
|
485
|
+
const PERMISSION_PICKER_STATE_METADATA = 'permission-picker-state';
|
|
486
|
+
const PERMISSION_PICKER_EXPIRY_METADATA = 'permission-picker-expires-at';
|
|
487
|
+
const PERMISSION_PICKER_EMERGENCY_VERSION_METADATA = 'permission-picker-emergency-version';
|
|
488
|
+
function permissionPickerGuard(envelope) {
|
|
489
|
+
const operationId = envelope.metadata?.[PERMISSION_PICKER_OPERATION_METADATA];
|
|
490
|
+
const expectedStateHash = envelope.metadata?.[PERMISSION_PICKER_STATE_METADATA];
|
|
491
|
+
const expiresAtText = envelope.metadata?.[PERMISSION_PICKER_EXPIRY_METADATA];
|
|
492
|
+
const emergencyStopVersionText = envelope.metadata?.[PERMISSION_PICKER_EMERGENCY_VERSION_METADATA];
|
|
493
|
+
if (operationId === undefined && expectedStateHash === undefined && expiresAtText === undefined
|
|
494
|
+
&& emergencyStopVersionText === undefined)
|
|
495
|
+
return undefined;
|
|
496
|
+
if (operationId === undefined || expectedStateHash === undefined || expiresAtText === undefined
|
|
497
|
+
|| emergencyStopVersionText === undefined
|
|
498
|
+
|| !/^permission-picker-[a-f0-9]{32}$/u.test(operationId)
|
|
499
|
+
|| !/^[a-f0-9]{64}$/u.test(expectedStateHash)
|
|
500
|
+
|| !/^[1-9][0-9]{0,15}$/u.test(expiresAtText)
|
|
501
|
+
|| !/^(?:0|[1-9][0-9]{0,15})$/u.test(emergencyStopVersionText))
|
|
502
|
+
return 'invalid';
|
|
503
|
+
const expiresAt = Number(expiresAtText);
|
|
504
|
+
const emergencyStopVersion = Number(emergencyStopVersionText);
|
|
505
|
+
if (!Number.isSafeInteger(expiresAt) || !Number.isSafeInteger(emergencyStopVersion))
|
|
506
|
+
return 'invalid';
|
|
507
|
+
return { operationId, expectedStateHash, expiresAt, emergencyStopVersion };
|
|
508
|
+
}
|
|
509
|
+
function permissionPresetTargets(service) {
|
|
510
|
+
const workspace = [];
|
|
511
|
+
const full = [];
|
|
512
|
+
const table = [];
|
|
513
|
+
for (const name of service.names) {
|
|
514
|
+
const spec = service.resolve(name);
|
|
515
|
+
table.push([name, spec.sandbox, spec.approval]);
|
|
516
|
+
// Keep the reserved Harness preset in the picker fence, but never select it.
|
|
517
|
+
if (name === 'auto')
|
|
518
|
+
continue;
|
|
519
|
+
if (spec.sandbox === 'workspace-write' && spec.approval === 'ask')
|
|
520
|
+
workspace.push(name);
|
|
521
|
+
if (spec.sandbox === 'danger-full-access' && spec.approval === 'never')
|
|
522
|
+
full.push(name);
|
|
523
|
+
}
|
|
524
|
+
if (workspace.length > 2 || full.length > 1) {
|
|
525
|
+
throw new Error('ambiguous permission preset table');
|
|
526
|
+
}
|
|
527
|
+
const ask = workspace[0];
|
|
528
|
+
const auto = workspace[1] ?? ask;
|
|
529
|
+
return {
|
|
530
|
+
...(ask === undefined ? {} : { ask, auto: auto }),
|
|
531
|
+
...(full[0] === undefined ? {} : { full: full[0] }),
|
|
532
|
+
tableFingerprint: createHash('sha256').update(JSON.stringify(table)).digest('hex'),
|
|
533
|
+
};
|
|
534
|
+
}
|
|
535
|
+
function missingPermissionBundle(targets) {
|
|
536
|
+
if (targets.ask === undefined || targets.auto === undefined)
|
|
537
|
+
return 'workspace-write + ask';
|
|
538
|
+
return targets.full === undefined ? 'danger-full-access + never' : undefined;
|
|
539
|
+
}
|
|
540
|
+
function explicitSandboxMode(events) {
|
|
541
|
+
const event = events.findLast(candidate => candidate.type === 'sandbox/mode');
|
|
542
|
+
if (event?.data.mode === 'workspace-write' || event?.data.mode === 'danger-full-access')
|
|
543
|
+
return event.data.mode;
|
|
544
|
+
return undefined;
|
|
545
|
+
}
|
|
546
|
+
function explicitApprovalPolicy(events) {
|
|
547
|
+
const event = events.findLast(candidate => candidate.type === 'approval/policy');
|
|
548
|
+
if (event?.data.policy === 'ask' || event?.data.policy === 'never')
|
|
549
|
+
return event.data.policy;
|
|
550
|
+
return undefined;
|
|
551
|
+
}
|
|
552
|
+
async function appendApprovalReviewer(session, reviewer) {
|
|
553
|
+
try {
|
|
554
|
+
await waitForApprovalReviewerSessionEventReady(session);
|
|
555
|
+
return setApprovalReviewer(session, reviewer);
|
|
556
|
+
}
|
|
557
|
+
catch (error) {
|
|
558
|
+
throw new ApprovalReviewerReaderUnavailableError(error);
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
function currentPermissionLevel(service, targets, session) {
|
|
562
|
+
const events = session.snapshotEvents();
|
|
563
|
+
if (events.findLast(event => event.type === 'permission/preset')?.data.preset === 'auto')
|
|
564
|
+
return 'custom';
|
|
565
|
+
const current = service.current(session);
|
|
566
|
+
const reviewer = approvalReviewerOf(events, session.header.version);
|
|
567
|
+
if (current === targets.full) {
|
|
568
|
+
return explicitSandboxMode(events) === 'danger-full-access'
|
|
569
|
+
&& explicitApprovalPolicy(events) === 'never'
|
|
570
|
+
&& reviewer === 'none'
|
|
571
|
+
? 'full'
|
|
572
|
+
: 'custom';
|
|
573
|
+
}
|
|
574
|
+
if (explicitApprovalPolicy(events) !== 'ask')
|
|
575
|
+
return 'custom';
|
|
576
|
+
if (current === targets.auto && targets.auto !== targets.ask) {
|
|
577
|
+
return explicitSandboxMode(events) === service.resolve(targets.auto).sandbox
|
|
578
|
+
&& reviewer === 'auto-review' ? 'auto' : 'custom';
|
|
579
|
+
}
|
|
580
|
+
if (explicitSandboxMode(events) !== service.resolve(targets.ask).sandbox)
|
|
581
|
+
return 'custom';
|
|
582
|
+
if (targets.ask === targets.auto && current === targets.ask)
|
|
583
|
+
return reviewer === 'auto-review' ? 'auto' : 'ask';
|
|
584
|
+
if (current === targets.ask)
|
|
585
|
+
return reviewer === 'user' ? 'ask' : 'custom';
|
|
586
|
+
return 'custom';
|
|
587
|
+
}
|
|
588
|
+
function canonicalPresetReviewer(name) {
|
|
589
|
+
if (name === 'workspace-write')
|
|
590
|
+
return 'user';
|
|
591
|
+
if (name === 'danger-full-access')
|
|
592
|
+
return 'none';
|
|
593
|
+
return undefined;
|
|
594
|
+
}
|
|
595
|
+
async function ensurePermissionReviewer(session, preset, reviewer) {
|
|
596
|
+
let events = session.snapshotEvents();
|
|
597
|
+
if (events.findLast(event => event.type === 'permission/preset')?.data.preset === 'auto') {
|
|
598
|
+
// Native set can be a no-op when the knobs already match the target.
|
|
599
|
+
// Supersede the stale reserved selector before opting into project review.
|
|
600
|
+
session.append('permission/preset', { preset });
|
|
601
|
+
events = session.snapshotEvents();
|
|
602
|
+
}
|
|
603
|
+
if (approvalReviewerOf(events, session.header.version) === reviewer)
|
|
604
|
+
return;
|
|
605
|
+
if (canonicalPresetReviewer(preset) === reviewer) {
|
|
606
|
+
// PermissionPresetService deliberately makes a net-zero selection a no-op.
|
|
607
|
+
// Re-append its official event when an older legacy reviewer event would
|
|
608
|
+
// otherwise remain newer and incorrectly win the durable fold.
|
|
609
|
+
session.append('permission/preset', { preset });
|
|
610
|
+
return;
|
|
611
|
+
}
|
|
612
|
+
await appendApprovalReviewer(session, reviewer);
|
|
613
|
+
}
|
|
614
|
+
function ensureSandboxMode(session, mode) {
|
|
615
|
+
if (explicitSandboxMode(session.snapshotEvents()) === mode)
|
|
616
|
+
return;
|
|
617
|
+
setSandboxMode(session, mode);
|
|
618
|
+
if (explicitSandboxMode(session.snapshotEvents()) !== mode)
|
|
619
|
+
session.append('sandbox/mode', { mode });
|
|
620
|
+
}
|
|
621
|
+
function ensureApprovalPolicy(session, policy) {
|
|
622
|
+
if (explicitApprovalPolicy(session.snapshotEvents()) === policy)
|
|
623
|
+
return;
|
|
624
|
+
setApprovalPolicy(session, policy);
|
|
625
|
+
if (explicitApprovalPolicy(session.snapshotEvents()) !== policy)
|
|
626
|
+
session.append('approval/policy', { policy });
|
|
627
|
+
}
|
|
628
|
+
function permissionLevelLabel(level) {
|
|
629
|
+
if (level === 'ask')
|
|
630
|
+
return '请求批准(ask)';
|
|
631
|
+
if (level === 'auto')
|
|
632
|
+
return '帮我批准(auto)';
|
|
633
|
+
if (level === 'full')
|
|
634
|
+
return '完全访问权限(full)';
|
|
635
|
+
return '自定义安全组合(custom)';
|
|
636
|
+
}
|
|
637
|
+
export function permissionStateHash(events, tableFingerprint = '') {
|
|
638
|
+
const facts = events
|
|
639
|
+
.filter(event => [
|
|
640
|
+
'permission/preset',
|
|
641
|
+
'sandbox/mode',
|
|
642
|
+
'approval/policy',
|
|
643
|
+
'assistant-policy/approval-reviewer',
|
|
644
|
+
].includes(String(event.type)))
|
|
645
|
+
.map(event => ({ seq: event.seq, type: String(event.type), data: event.data }));
|
|
646
|
+
return createHash('sha256')
|
|
647
|
+
.update('assistant-delivery:permission-state:v2\0')
|
|
648
|
+
.update(JSON.stringify([tableFingerprint, facts]))
|
|
649
|
+
.digest('hex');
|
|
650
|
+
}
|
|
651
|
+
export function permissionPickerOperationId(conversation, eventId) {
|
|
652
|
+
return `permission-picker-${createHash('sha256').update(JSON.stringify({
|
|
653
|
+
channel: conversation.channel,
|
|
654
|
+
account: conversation.account,
|
|
655
|
+
tenant: conversation.tenant,
|
|
656
|
+
kind: conversation.kind,
|
|
657
|
+
chat: conversation.chat,
|
|
658
|
+
thread: conversation.thread ?? null,
|
|
659
|
+
eventId,
|
|
660
|
+
})).digest('hex').slice(0, 32)}`;
|
|
661
|
+
}
|
|
662
|
+
function permissionOverview(level, picker) {
|
|
663
|
+
const text = [
|
|
664
|
+
`当前权限:${permissionLevelLabel(level)}`,
|
|
665
|
+
'',
|
|
666
|
+
'三档说明:',
|
|
667
|
+
'- 请求批准(ask):仅可写工作区;需要授权时由你确认。',
|
|
668
|
+
'- 帮我批准(auto):仅可写工作区;由自动审核器处理授权请求。',
|
|
669
|
+
'- 完全访问权限(full):🟠 Host sandbox 可访问网络及任意文件,且不再请求批准;管理员 Policy 硬门仍生效。',
|
|
670
|
+
'',
|
|
671
|
+
'档位只控制运行权限,不会安装或挂载技能/插件;已挂载工具还必须有 Policy 可达规则。',
|
|
672
|
+
'full 仍不绕过显式 Policy 拒绝、紧急停止、身份和预算硬门。',
|
|
673
|
+
'',
|
|
674
|
+
'切换:/permission ask、/permission auto、/permission full confirm',
|
|
675
|
+
].join('\n');
|
|
676
|
+
return {
|
|
677
|
+
text,
|
|
678
|
+
format: picker === undefined ? 'plain' : 'permission-picker',
|
|
679
|
+
...(picker === undefined ? {} : { permissionPicker: picker, fallbackText: text }),
|
|
680
|
+
};
|
|
681
|
+
}
|
|
682
|
+
const PERMISSION_USAGE = {
|
|
683
|
+
text: '用法:/permission、/permission ask、/permission auto、/permission full confirm',
|
|
684
|
+
format: 'plain',
|
|
685
|
+
};
|
|
686
|
+
const PERMISSION_FULL_WARNING = {
|
|
687
|
+
text: '🟠 危险:full 会启用 danger-full-access,可访问网络及任意文件,并关闭批准请求。'
|
|
688
|
+
+ '管理员 Policy 的显式拒绝、紧急停止、身份和预算硬门仍生效。'
|
|
689
|
+
+ '如确需切换,请明确发送 /permission full confirm。当前权限未改变。',
|
|
690
|
+
format: 'plain',
|
|
691
|
+
};
|
|
692
|
+
function routeLabel(route) {
|
|
693
|
+
return `${route.provider}/${route.model}${route.reasoningEffort === undefined ? '' : `,effort:${route.reasoningEffort}`}`;
|
|
694
|
+
}
|
|
695
|
+
function displayName(value) {
|
|
696
|
+
return [...value].slice(0, 120).join('');
|
|
697
|
+
}
|
|
698
|
+
export function modelPickerOperationId(conversation, eventId) {
|
|
699
|
+
return `model-picker-${createHash('sha256').update(JSON.stringify({
|
|
700
|
+
channel: conversation.channel,
|
|
701
|
+
account: conversation.account,
|
|
702
|
+
tenant: conversation.tenant,
|
|
703
|
+
kind: conversation.kind,
|
|
704
|
+
chat: conversation.chat,
|
|
705
|
+
thread: conversation.thread ?? null,
|
|
706
|
+
eventId,
|
|
707
|
+
})).digest('hex').slice(0, 32)}`;
|
|
708
|
+
}
|
|
709
|
+
function toModelRoute(route) {
|
|
710
|
+
return {
|
|
711
|
+
provider: route.provider,
|
|
712
|
+
model: route.model,
|
|
713
|
+
...(route.reasoningEffort === undefined ? {} : { reasoningEffort: route.reasoningEffort }),
|
|
714
|
+
};
|
|
715
|
+
}
|
|
716
|
+
function agentSelection(route) {
|
|
717
|
+
return {
|
|
718
|
+
provider: route.provider,
|
|
719
|
+
model: route.model,
|
|
720
|
+
...(route.reasoningEffort === undefined
|
|
721
|
+
? {}
|
|
722
|
+
: { reasoningEffort: ReasoningEffortId(route.reasoningEffort) }),
|
|
723
|
+
};
|
|
724
|
+
}
|
|
725
|
+
function errorHasCode(error, code) {
|
|
726
|
+
let current = error;
|
|
727
|
+
const visited = new Set();
|
|
728
|
+
while (typeof current === 'object' && current !== null && !visited.has(current)) {
|
|
729
|
+
visited.add(current);
|
|
730
|
+
if ('code' in current && current.code === code)
|
|
731
|
+
return true;
|
|
732
|
+
current = current instanceof Error ? current.cause : undefined;
|
|
733
|
+
}
|
|
734
|
+
return false;
|
|
735
|
+
}
|
|
736
|
+
function waitWithAbort(operation, signal) {
|
|
737
|
+
if (signal.aborted) {
|
|
738
|
+
void operation.catch(() => undefined);
|
|
739
|
+
return Promise.reject(signal.reason instanceof Error ? signal.reason : new Error('aborted'));
|
|
740
|
+
}
|
|
741
|
+
return new Promise((resolve, reject) => {
|
|
742
|
+
const onAbort = () => {
|
|
743
|
+
reject(signal.reason instanceof Error ? signal.reason : new Error('aborted'));
|
|
744
|
+
};
|
|
745
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
746
|
+
void operation.then(value => {
|
|
747
|
+
signal.removeEventListener('abort', onAbort);
|
|
748
|
+
resolve(value);
|
|
749
|
+
}, error => {
|
|
750
|
+
signal.removeEventListener('abort', onAbort);
|
|
751
|
+
reject(error);
|
|
752
|
+
});
|
|
753
|
+
});
|
|
754
|
+
}
|
|
755
|
+
function allocateCatalogModels(catalogs, current) {
|
|
756
|
+
const nonEmpty = catalogs.filter((catalog) => catalog.models !== undefined && catalog.models.length > 0);
|
|
757
|
+
let selected = nonEmpty;
|
|
758
|
+
if (nonEmpty.length > MAX_CATALOG_PROVIDERS) {
|
|
759
|
+
selected = nonEmpty.slice(0, MAX_CATALOG_PROVIDERS);
|
|
760
|
+
if (!selected.some(catalog => catalog.provider.id === current.provider)) {
|
|
761
|
+
const currentCatalog = nonEmpty.find(catalog => catalog.provider.id === current.provider);
|
|
762
|
+
if (currentCatalog !== undefined) {
|
|
763
|
+
selected = [...selected.slice(0, MAX_CATALOG_PROVIDERS - 1), currentCatalog];
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
const quotas = selected.map(catalog => ({
|
|
768
|
+
catalog,
|
|
769
|
+
allocated: 0,
|
|
770
|
+
isCurrent: catalog.provider.id === current.provider,
|
|
771
|
+
}));
|
|
772
|
+
let remaining = MAX_CATALOG_MODELS;
|
|
773
|
+
while (remaining > 0) {
|
|
774
|
+
const active = quotas.filter(entry => entry.allocated < entry.catalog.models.length);
|
|
775
|
+
if (active.length === 0)
|
|
776
|
+
break;
|
|
777
|
+
const share = Math.floor(remaining / active.length);
|
|
778
|
+
if (share === 0) {
|
|
779
|
+
const ordered = [...active].sort((left, right) => Number(right.isCurrent) - Number(left.isCurrent));
|
|
780
|
+
for (const entry of ordered) {
|
|
781
|
+
if (remaining === 0)
|
|
782
|
+
break;
|
|
783
|
+
entry.allocated += 1;
|
|
784
|
+
remaining -= 1;
|
|
785
|
+
}
|
|
786
|
+
break;
|
|
787
|
+
}
|
|
788
|
+
for (const entry of active) {
|
|
789
|
+
const take = Math.min(share, entry.catalog.models.length - entry.allocated);
|
|
790
|
+
entry.allocated += take;
|
|
791
|
+
remaining -= take;
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
const visibleByProvider = new Map();
|
|
795
|
+
for (const { catalog, allocated, isCurrent } of quotas) {
|
|
796
|
+
if (allocated <= 0)
|
|
797
|
+
continue;
|
|
798
|
+
const slice = catalog.models.slice(0, allocated);
|
|
799
|
+
if (isCurrent && !slice.some(model => model.id === current.model)) {
|
|
800
|
+
const currentEntry = catalog.models.find(model => model.id === current.model);
|
|
801
|
+
if (currentEntry !== undefined) {
|
|
802
|
+
slice[slice.length - 1] = currentEntry;
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
visibleByProvider.set(catalog.provider.id, slice);
|
|
806
|
+
}
|
|
807
|
+
return visibleByProvider;
|
|
808
|
+
}
|
|
809
|
+
async function modelCatalog(llm, conversation, current, isDefault, eventId, expiresAt, signal) {
|
|
810
|
+
const providers = llm.listProviders();
|
|
811
|
+
const catalogs = await Promise.all(providers.map(async (provider) => {
|
|
812
|
+
try {
|
|
813
|
+
return { provider, models: await llm.listModels(provider.id) };
|
|
814
|
+
}
|
|
815
|
+
catch {
|
|
816
|
+
return { provider, models: undefined };
|
|
817
|
+
}
|
|
818
|
+
}));
|
|
819
|
+
const visibleByProvider = allocateCatalogModels(catalogs, current);
|
|
820
|
+
const fallback = [
|
|
821
|
+
`当前模型:${routeLabel(current)}${isDefault ? '(默认)' : ''}`,
|
|
822
|
+
'',
|
|
823
|
+
'可用模型(来自 DSH 实时目录):',
|
|
824
|
+
];
|
|
825
|
+
const models = [];
|
|
826
|
+
const visibleProviders = new Map();
|
|
827
|
+
let hidden = 0;
|
|
828
|
+
for (const catalog of catalogs) {
|
|
829
|
+
fallback.push(`${catalog.provider.name} [${catalog.provider.id}]`);
|
|
830
|
+
if (catalog.models === undefined) {
|
|
831
|
+
fallback.push('- 目录暂不可用');
|
|
832
|
+
continue;
|
|
833
|
+
}
|
|
834
|
+
if (catalog.models.length === 0) {
|
|
835
|
+
fallback.push('- 未提供可枚举模型');
|
|
836
|
+
continue;
|
|
837
|
+
}
|
|
838
|
+
const visibleModels = visibleByProvider.get(catalog.provider.id) ?? [];
|
|
839
|
+
hidden += catalog.models.length - visibleModels.length;
|
|
840
|
+
for (const model of visibleModels) {
|
|
841
|
+
const route = `${catalog.provider.id}/${model.id}`;
|
|
842
|
+
const marker = catalog.provider.id === current.provider && model.id === current.model ? '(当前)' : '';
|
|
843
|
+
const display = model.name === model.id ? '' : ` — ${model.name}`;
|
|
844
|
+
fallback.push(`- ${route}${display}${marker}`);
|
|
845
|
+
visibleProviders.set(catalog.provider.id, {
|
|
846
|
+
id: catalog.provider.id,
|
|
847
|
+
name: displayName(catalog.provider.name),
|
|
848
|
+
});
|
|
849
|
+
models.push({ provider: catalog.provider.id, id: model.id, name: displayName(model.name), effortIds: [] });
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
if (providers.length === 0)
|
|
853
|
+
fallback.push('- 当前没有已注册的模型 provider');
|
|
854
|
+
if (hidden > 0)
|
|
855
|
+
fallback.push(`- 另有 ${hidden} 个模型未展示`);
|
|
856
|
+
fallback.push('', '切换:/model use <provider/model> [effort]', '恢复默认:/model reset');
|
|
857
|
+
if (models.length === 0)
|
|
858
|
+
return { text: fallback.join('\n'), format: 'plain' };
|
|
859
|
+
const resolved = await Promise.allSettled(models.map(model => llm.resolveModelInfo(model.provider, model.id, signal)));
|
|
860
|
+
const efforts = new Map();
|
|
861
|
+
const linkedModels = models.map((model, index) => {
|
|
862
|
+
const result = resolved[index];
|
|
863
|
+
if (result?.status !== 'fulfilled')
|
|
864
|
+
return model;
|
|
865
|
+
const effortIds = new Set();
|
|
866
|
+
for (const effort of result.value.reasoning?.efforts ?? []) {
|
|
867
|
+
const id = String(effort.id);
|
|
868
|
+
if (!efforts.has(id) && efforts.size >= 20)
|
|
869
|
+
continue;
|
|
870
|
+
efforts.set(id, displayName(effort.name));
|
|
871
|
+
if (effortIds.size < 20)
|
|
872
|
+
effortIds.add(id);
|
|
873
|
+
}
|
|
874
|
+
return { ...model, effortIds: [...effortIds] };
|
|
875
|
+
});
|
|
876
|
+
return {
|
|
877
|
+
text: `当前模型:${routeLabel(current)}${isDefault ? '(默认)' : ''}`,
|
|
878
|
+
format: 'model-picker',
|
|
879
|
+
modelPicker: {
|
|
880
|
+
operationId: modelPickerOperationId(conversation, eventId),
|
|
881
|
+
expiresAt,
|
|
882
|
+
current,
|
|
883
|
+
providers: [...visibleProviders.values()],
|
|
884
|
+
models: linkedModels,
|
|
885
|
+
efforts: [...efforts].map(([id, name]) => ({ id, name })),
|
|
886
|
+
},
|
|
887
|
+
fallbackText: fallback.join('\n'),
|
|
888
|
+
};
|
|
889
|
+
}
|
|
890
|
+
async function runModelCommand(argument, llm, conversation, defaults, options, signal, eventId) {
|
|
891
|
+
const current = options.getModelSelection(conversation);
|
|
892
|
+
const route = toModelRoute(current ?? defaults);
|
|
893
|
+
if (argument === '') {
|
|
894
|
+
return modelCatalog(llm, conversation, route, current === undefined, eventId, Date.now() + options.modelPickerTtlMs, signal);
|
|
895
|
+
}
|
|
896
|
+
if (argument === 'reset') {
|
|
897
|
+
const epoch = options.beginModelCommand(conversation);
|
|
898
|
+
const committed = options.commitModelCommand({ conversation, expectedEpoch: epoch });
|
|
899
|
+
if (!committed.applied)
|
|
900
|
+
return { text: '模型选择已被更晚的操作取代,请重新发送 /model。' };
|
|
901
|
+
const changed = current !== undefined;
|
|
902
|
+
return { text: changed
|
|
903
|
+
? `已恢复默认模型 ${routeLabel(defaults)}。\n下一条消息起生效,上下文保留。`
|
|
904
|
+
: `本会话已在使用默认模型 ${routeLabel(defaults)}。` };
|
|
905
|
+
}
|
|
906
|
+
if (!argument.startsWith('use ')) {
|
|
907
|
+
return { text: '用法:/model、/model use <provider/model> [effort]、/model reset' };
|
|
908
|
+
}
|
|
909
|
+
const target = argument.slice('use '.length).trim();
|
|
910
|
+
const selected = parseModelUseTarget(target);
|
|
911
|
+
if (selected === undefined)
|
|
912
|
+
return { text: '用法:/model use <provider/model> [effort]' };
|
|
913
|
+
if (!llm.listProviders().some(provider => provider.id === selected.provider)) {
|
|
914
|
+
return { text: `没有注册 provider “${selected.provider}”。发送 /model 查看当前可用模型。` };
|
|
915
|
+
}
|
|
916
|
+
const epoch = options.beginModelCommand(conversation);
|
|
917
|
+
let info;
|
|
918
|
+
try {
|
|
919
|
+
info = await llm.resolveModelInfo(selected.provider, selected.model, signal);
|
|
920
|
+
if (selected.reasoningEffort !== undefined
|
|
921
|
+
&& !info.reasoning?.efforts.some(effort => String(effort.id) === selected.reasoningEffort)) {
|
|
922
|
+
try {
|
|
923
|
+
await waitWithAbort(llm.listModels(selected.provider), signal);
|
|
924
|
+
}
|
|
925
|
+
catch (listError) {
|
|
926
|
+
if (signal.aborted)
|
|
927
|
+
throw listError;
|
|
928
|
+
}
|
|
929
|
+
info = await llm.resolveModelInfo(selected.provider, selected.model, signal);
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
catch (error) {
|
|
933
|
+
if (signal.aborted)
|
|
934
|
+
throw error;
|
|
935
|
+
const code = typeof error === 'object' && error !== null && 'code' in error
|
|
936
|
+
&& typeof error.code === 'string'
|
|
937
|
+
? `(${error.code})`
|
|
938
|
+
: '';
|
|
939
|
+
return { text: `模型 ${routeLabel(selected)} 当前不可用${code}。发送 /model 重新选择。` };
|
|
940
|
+
}
|
|
941
|
+
if (selected.reasoningEffort !== undefined
|
|
942
|
+
&& !info.reasoning?.efforts.some(effort => String(effort.id) === selected.reasoningEffort)) {
|
|
943
|
+
const supported = info.reasoning?.efforts.map(effort => String(effort.id)) ?? [];
|
|
944
|
+
const hint = supported.length > 0
|
|
945
|
+
? `(可用档位:${supported.join('、')})`
|
|
946
|
+
: '(该模型无可选 effort 档位)';
|
|
947
|
+
return { text: `模型 ${selected.provider}/${selected.model} 不支持 effort “${selected.reasoningEffort}”${hint}。发送 /model 重新选择。` };
|
|
948
|
+
}
|
|
949
|
+
const same = current !== undefined
|
|
950
|
+
&& current.provider === selected.provider
|
|
951
|
+
&& current.model === selected.model
|
|
952
|
+
&& current.reasoningEffort === selected.reasoningEffort;
|
|
953
|
+
if (same)
|
|
954
|
+
return { text: `本会话已在使用 ${routeLabel(selected)}。` };
|
|
955
|
+
const committed = options.commitModelCommand({ conversation, expectedEpoch: epoch, route: selected });
|
|
956
|
+
if (!committed.applied)
|
|
957
|
+
return { text: '模型选择已被更晚的操作取代,请重新发送 /model。' };
|
|
958
|
+
return { text: `已切换到 ${routeLabel(selected)}。\n下一条消息起生效,上下文保留。` };
|
|
959
|
+
}
|
|
960
|
+
function modelCommandFailure(error) {
|
|
961
|
+
const deterministic = error instanceof DeliveryStoreError
|
|
962
|
+
&& (error.code === 'invalid-intent' || error.code === 'invalid-binding');
|
|
963
|
+
return {
|
|
964
|
+
outcome: 'not-processed',
|
|
965
|
+
failureCode: deterministic ? 'model-command-invalid' : 'model-command-failed',
|
|
966
|
+
retryable: !deterministic,
|
|
967
|
+
};
|
|
968
|
+
}
|
|
969
|
+
function sessionId(namespace, conversation, generation) {
|
|
970
|
+
const hash = createHash('sha256')
|
|
971
|
+
.update(JSON.stringify({ namespace, conversation, generation }))
|
|
972
|
+
.digest('hex')
|
|
973
|
+
.slice(0, 32);
|
|
974
|
+
return SessionId(`delivery-${hash}-g${generation}`);
|
|
975
|
+
}
|
|
976
|
+
async function ensureWorkspace(workspace) {
|
|
977
|
+
try {
|
|
978
|
+
await mkdir(workspace, { recursive: true, mode: 0o700 });
|
|
979
|
+
}
|
|
980
|
+
catch (error) {
|
|
981
|
+
throw new Error(`assistant-delivery: failed to ensure workspace "${workspace}": ${String(error)}`, {
|
|
982
|
+
cause: error,
|
|
983
|
+
});
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
async function requireWorkspace(workspace) {
|
|
987
|
+
try {
|
|
988
|
+
const metadata = await stat(workspace);
|
|
989
|
+
if (!metadata.isDirectory())
|
|
990
|
+
throw new Error('path is not a directory');
|
|
991
|
+
}
|
|
992
|
+
catch (error) {
|
|
993
|
+
throw new Error(`assistant-delivery: durable workspace "${workspace}" is unavailable: ${String(error)}`, {
|
|
994
|
+
cause: error,
|
|
995
|
+
});
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
function causedByDurableIdentity(error) {
|
|
999
|
+
let current = error;
|
|
1000
|
+
const visited = new Set();
|
|
1001
|
+
while (current instanceof Error && !visited.has(current)) {
|
|
1002
|
+
if (current instanceof DurableAgentIdentityError)
|
|
1003
|
+
return true;
|
|
1004
|
+
visited.add(current);
|
|
1005
|
+
current = current.cause;
|
|
1006
|
+
}
|
|
1007
|
+
return false;
|
|
1008
|
+
}
|
|
1009
|
+
function causedByUserCancellation(error) {
|
|
1010
|
+
let current = error;
|
|
1011
|
+
const visited = new Set();
|
|
1012
|
+
while (current instanceof Error && !visited.has(current)) {
|
|
1013
|
+
if (current instanceof UserSessionCancellation)
|
|
1014
|
+
return true;
|
|
1015
|
+
visited.add(current);
|
|
1016
|
+
current = current.cause;
|
|
1017
|
+
}
|
|
1018
|
+
return false;
|
|
1019
|
+
}
|
|
1020
|
+
function errorChainHasName(error, expected) {
|
|
1021
|
+
let current = error;
|
|
1022
|
+
const visited = new Set();
|
|
1023
|
+
while (current instanceof Error && !visited.has(current)) {
|
|
1024
|
+
if (current.name === expected)
|
|
1025
|
+
return true;
|
|
1026
|
+
visited.add(current);
|
|
1027
|
+
current = current.cause;
|
|
1028
|
+
}
|
|
1029
|
+
return false;
|
|
1030
|
+
}
|
|
1031
|
+
function isAcceptanceConfigurationError(error) {
|
|
1032
|
+
let current = error;
|
|
1033
|
+
const visited = new Set();
|
|
1034
|
+
while (current instanceof Error && !visited.has(current)) {
|
|
1035
|
+
if (current.message.includes('no Host-approved acceptance profile matches')
|
|
1036
|
+
|| current.message.includes('required task acceptance profile did not produce a contract')) {
|
|
1037
|
+
return true;
|
|
1038
|
+
}
|
|
1039
|
+
visited.add(current);
|
|
1040
|
+
current = current.cause;
|
|
1041
|
+
}
|
|
1042
|
+
return false;
|
|
1043
|
+
}
|
|
1044
|
+
function assertAdoptableUnstartedSession(session, workspace, presetId) {
|
|
1045
|
+
if (session.header.cwd !== workspace || session.header.agentPreset !== presetId) {
|
|
1046
|
+
throw new DurableAgentIdentityError('assistant-delivery: durable orphan session identity does not match the requested generation');
|
|
1047
|
+
}
|
|
1048
|
+
if (session.snapshotEvents().some(event => event.type === 'turn/start' || event.type === 'user/message')
|
|
1049
|
+
|| session.deriveMessages().length > 0) {
|
|
1050
|
+
throw new DurableAgentIdentityError('assistant-delivery: refusing to adopt a deterministic session that already started a user turn');
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
1053
|
+
function sessionResumeFailureCode(error) {
|
|
1054
|
+
if (causedByDurableIdentity(error))
|
|
1055
|
+
return 'agent-identity-mismatch';
|
|
1056
|
+
if (errorChainHasName(error, 'SessionFormatUnsupportedError'))
|
|
1057
|
+
return 'session-format-unsupported';
|
|
1058
|
+
if (errorChainHasName(error, 'SessionPersistenceCorruptionError'))
|
|
1059
|
+
return 'session-persistence-corrupt';
|
|
1060
|
+
return 'session-resume-unavailable';
|
|
1061
|
+
}
|
|
1062
|
+
function sessionFormatUnsupportedReply() {
|
|
1063
|
+
return {
|
|
1064
|
+
text: '旧会话格式无法由当前 Host 恢复,记录已保留。请使用 /new 开启会话。',
|
|
1065
|
+
format: 'plain',
|
|
1066
|
+
};
|
|
1067
|
+
}
|
|
1068
|
+
function sessionFingerprint(value) {
|
|
1069
|
+
return createHash('sha256').update(value).digest('hex').slice(0, 8);
|
|
1070
|
+
}
|
|
1071
|
+
const AGENT_OUTPUT_TRUNCATED_CODE = 'agent-output-truncated';
|
|
1072
|
+
const AGENT_EMPTY_RESPONSE_CODE = 'agent-empty-response';
|
|
1073
|
+
const AUTOMATIC_COMPLETION_TOOL_DENIAL = 'assistant-delivery: automatic answer completion disables tool execution';
|
|
1074
|
+
function utf8Prefix(value, maxBytes) {
|
|
1075
|
+
const bytes = Buffer.from(value, 'utf8');
|
|
1076
|
+
if (bytes.length <= maxBytes)
|
|
1077
|
+
return value;
|
|
1078
|
+
let end = maxBytes;
|
|
1079
|
+
while (end > 0 && (bytes[end] & 0xc0) === 0x80)
|
|
1080
|
+
end -= 1;
|
|
1081
|
+
return bytes.subarray(0, end).toString('utf8');
|
|
1082
|
+
}
|
|
1083
|
+
function fittingNotice(candidates, maxBytes) {
|
|
1084
|
+
return candidates.find(value => Buffer.byteLength(value, 'utf8') <= maxBytes) ?? '!';
|
|
1085
|
+
}
|
|
1086
|
+
function truncatedAgentReply(text, maxBytes) {
|
|
1087
|
+
const notice = fittingNotice([
|
|
1088
|
+
'⚠️ 本次回答未能完整生成;以下内容可能不完整。',
|
|
1089
|
+
'本次回答未完整生成。',
|
|
1090
|
+
'回答不完整。',
|
|
1091
|
+
'retry',
|
|
1092
|
+
'!',
|
|
1093
|
+
], maxBytes);
|
|
1094
|
+
if (text.trim() === '')
|
|
1095
|
+
return fittingNotice([
|
|
1096
|
+
'本次未能生成可发送的完整回答。请稍后重试或缩小问题范围。',
|
|
1097
|
+
'本次未能生成完整回答,请重试。',
|
|
1098
|
+
'未生成回答,请重试。',
|
|
1099
|
+
'retry',
|
|
1100
|
+
'!',
|
|
1101
|
+
], maxBytes);
|
|
1102
|
+
const separator = '\n\n> ';
|
|
1103
|
+
const suffix = `${separator}${notice}`;
|
|
1104
|
+
const prefixBudget = maxBytes - Buffer.byteLength(suffix, 'utf8');
|
|
1105
|
+
if (prefixBudget <= 0)
|
|
1106
|
+
return notice;
|
|
1107
|
+
const prefix = utf8Prefix(text, prefixBudget);
|
|
1108
|
+
return prefix.trim() === '' ? notice : `${prefix}${suffix}`;
|
|
1109
|
+
}
|
|
1110
|
+
function emptyAgentReply(maxBytes) {
|
|
1111
|
+
return fittingNotice([
|
|
1112
|
+
'模型本轮未生成可发送的回答。请重试;如果问题较长,也可以拆成更小的步骤。',
|
|
1113
|
+
'模型未生成回答,请重试。',
|
|
1114
|
+
'请重试。',
|
|
1115
|
+
'retry',
|
|
1116
|
+
'!',
|
|
1117
|
+
], maxBytes);
|
|
1118
|
+
}
|
|
1119
|
+
function mergeContinuationText(current, continuation) {
|
|
1120
|
+
if (current === '')
|
|
1121
|
+
return { text: continuation, added: continuation !== '' };
|
|
1122
|
+
if (continuation === '')
|
|
1123
|
+
return { text: current, added: false };
|
|
1124
|
+
if (continuation.startsWith(current)) {
|
|
1125
|
+
const suffix = continuation.slice(current.length);
|
|
1126
|
+
const added = suffix.trim() !== '';
|
|
1127
|
+
return { text: added ? continuation : current, added };
|
|
1128
|
+
}
|
|
1129
|
+
if (current.endsWith(continuation))
|
|
1130
|
+
return { text: current, added: false };
|
|
1131
|
+
const currentPoints = [...current];
|
|
1132
|
+
const continuationPoints = [...continuation];
|
|
1133
|
+
const maxOverlap = Math.min(currentPoints.length, continuationPoints.length, 4_096);
|
|
1134
|
+
for (let length = maxOverlap; length >= 2; length -= 1) {
|
|
1135
|
+
const currentOverlap = currentPoints.slice(-length);
|
|
1136
|
+
if (length < 16) {
|
|
1137
|
+
const hanCount = currentOverlap.filter(point => /^\p{Script=Han}$/u.test(point)).length;
|
|
1138
|
+
if (hanCount < 2 || currentOverlap.some(point => !/^[\p{Script=Han}\p{P}\p{Z}]$/u.test(point)))
|
|
1139
|
+
continue;
|
|
1140
|
+
}
|
|
1141
|
+
if (currentOverlap.join('') !== continuationPoints.slice(0, length).join(''))
|
|
1142
|
+
continue;
|
|
1143
|
+
const suffix = continuationPoints.slice(length).join('');
|
|
1144
|
+
const added = suffix.trim() !== '';
|
|
1145
|
+
return { text: added ? current + suffix : current, added };
|
|
1146
|
+
}
|
|
1147
|
+
return { text: current + continuation, added: continuation.trim() !== '' };
|
|
1148
|
+
}
|
|
1149
|
+
function automaticCompletionPrompt(kind, maxTextBytes, maxOutputTokens) {
|
|
1150
|
+
const marker = '[DSH automatic answer completion notice]';
|
|
1151
|
+
const scope = 'Work only on the current task: the most recent user request before the first marked notice '
|
|
1152
|
+
+ 'in this trailing recovery sequence, plus assistant answer segments after that request. '
|
|
1153
|
+
+ 'Ignore all earlier completed tasks, and treat every marked notice as an instruction rather than answer content.';
|
|
1154
|
+
const common = 'Do not call tools, repeat actions, discuss this recovery instruction, or add a preamble.';
|
|
1155
|
+
if (kind === 'continue') {
|
|
1156
|
+
return `${marker} ${scope} The immediately preceding assistant answer segment was cut off by an output limit. `
|
|
1157
|
+
+ `Continue exactly from its last character and finish the current answer. Return only the missing remainder `
|
|
1158
|
+
+ `without repeating earlier text. ${common}`;
|
|
1159
|
+
}
|
|
1160
|
+
if (kind === 'compact') {
|
|
1161
|
+
const approximateCjkCharacters = Math.max(1, Math.floor(maxTextBytes / 4));
|
|
1162
|
+
const targetTokens = Math.max(1, Math.min(Math.floor(maxOutputTokens / 2), approximateCjkCharacters));
|
|
1163
|
+
return `${marker} ${scope} Rewrite the current task result as one complete, self-contained, concise final answer `
|
|
1164
|
+
+ `using at most ${targetTokens} tokens `
|
|
1165
|
+
+ `and under ${maxTextBytes} UTF-8 bytes (about ${approximateCjkCharacters} CJK characters). `
|
|
1166
|
+
+ 'Preserve the conclusion and essential facts, '
|
|
1167
|
+
+ `but remove repetition and nonessential detail. ${common}`;
|
|
1168
|
+
}
|
|
1169
|
+
return `${marker} ${scope} The preceding attempt produced no sendable answer. Answer the current request now `
|
|
1170
|
+
+ `with one complete, self-contained and concise final response. ${common}`;
|
|
1171
|
+
}
|
|
1172
|
+
function finalAssistant(events, from, expectedTurn) {
|
|
1173
|
+
if (expectedTurn === undefined) {
|
|
1174
|
+
return { text: '', completed: false, truncated: false, stopped: false, hasUnpairedToolCall: false, hadToolCall: false };
|
|
1175
|
+
}
|
|
1176
|
+
let text = '';
|
|
1177
|
+
let completed = false;
|
|
1178
|
+
let truncated = false;
|
|
1179
|
+
let stopped = false;
|
|
1180
|
+
const unpairedToolCalls = new Set();
|
|
1181
|
+
let hadToolCall = false;
|
|
1182
|
+
let failureCode;
|
|
1183
|
+
for (const event of events.slice(from)) {
|
|
1184
|
+
if (event.type === 'assistant/message' && event.data.turn === expectedTurn) {
|
|
1185
|
+
text = event.data.message.content.filter(block => block.type === 'text')
|
|
1186
|
+
.map(block => block.type === 'text' ? block.text : '').join('');
|
|
1187
|
+
for (const block of event.data.message.content) {
|
|
1188
|
+
if (block.type === 'tool-call') {
|
|
1189
|
+
hadToolCall = true;
|
|
1190
|
+
unpairedToolCalls.add(String(block.id));
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
if (event.type === 'tool/result' && event.data.turn === expectedTurn) {
|
|
1195
|
+
const callId = event.data.message.toolCallId;
|
|
1196
|
+
if (callId !== undefined)
|
|
1197
|
+
unpairedToolCalls.delete(String(callId));
|
|
1198
|
+
}
|
|
1199
|
+
if (event.type === 'turn/end' && event.data.turn === expectedTurn) {
|
|
1200
|
+
const reason = event.data.reason;
|
|
1201
|
+
completed = typeof reason === 'object' && reason !== null && 'kind' in reason
|
|
1202
|
+
&& reason.kind === 'completed';
|
|
1203
|
+
truncated = typeof reason === 'object' && reason !== null && 'kind' in reason
|
|
1204
|
+
&& reason.kind === 'max-tokens';
|
|
1205
|
+
stopped = typeof reason === 'object' && reason !== null
|
|
1206
|
+
&& reason.kind === 'aborted'
|
|
1207
|
+
&& typeof reason.reason === 'object'
|
|
1208
|
+
&& reason.reason?.kind === 'user';
|
|
1209
|
+
// Keep only the short upstream code: the provider message can quote the prompt or payload.
|
|
1210
|
+
const error = typeof reason === 'object' && reason !== null && 'error' in reason
|
|
1211
|
+
? reason.error
|
|
1212
|
+
: undefined;
|
|
1213
|
+
failureCode = completed || truncated || typeof error?.code !== 'string' ? undefined : error.code;
|
|
1214
|
+
}
|
|
1215
|
+
}
|
|
1216
|
+
return {
|
|
1217
|
+
text,
|
|
1218
|
+
completed,
|
|
1219
|
+
truncated,
|
|
1220
|
+
stopped,
|
|
1221
|
+
hasUnpairedToolCall: unpairedToolCalls.size > 0,
|
|
1222
|
+
hadToolCall,
|
|
1223
|
+
...(failureCode === undefined ? {} : { failureCode }),
|
|
1224
|
+
};
|
|
1225
|
+
}
|
|
1226
|
+
function isScheduledGoalRuntimeContext(source) {
|
|
1227
|
+
return source.kind === 'runtime-context'
|
|
1228
|
+
|| (source.kind === 'skill-catalog' && source.form === 'catalog');
|
|
1229
|
+
}
|
|
1230
|
+
/**
|
|
1231
|
+
* Trusted Host clarification injected after the human deliberately cancels a
|
|
1232
|
+
* tool call before it dispatched.
|
|
1233
|
+
*
|
|
1234
|
+
* Why this exists: when a turn is aborted by the human, the agent loop persists
|
|
1235
|
+
* a `tool/result` pair whose ONLY model-visible text is the bare technical
|
|
1236
|
+
* string "Error: tool call aborted before dispatch" (`isError: true`). The
|
|
1237
|
+
* accurate structured facts — `error.code = ABORTED_BEFORE_DISPATCH` and the
|
|
1238
|
+
* `turn/end` reason `{ aborted, reason: { user } }` — are not surface events,
|
|
1239
|
+
* so the model never sees them. A string of those error-looking results makes a
|
|
1240
|
+
* later no-op message (e.g. "hi") look like "retry the fetch the system kept
|
|
1241
|
+
* interrupting", causing the model to re-fire the cancelled tool unprompted.
|
|
1242
|
+
*
|
|
1243
|
+
* This text is a FIXED Host constant. It never interpolates message content,
|
|
1244
|
+
* tool names, or arguments, so untrusted input cannot flow into the trusted
|
|
1245
|
+
* snapshot. The predicate keys only off structured, Host-owned fields.
|
|
1246
|
+
*/
|
|
1247
|
+
const USER_CANCELLED_TOOL_NOTICE = [
|
|
1248
|
+
'The most recent turn was stopped deliberately by the human (they pressed stop or declined the tool permission).',
|
|
1249
|
+
'Any earlier tool result reading "Error: tool call aborted before dispatch" is that human cancellation, NOT a tool or system failure and NOT an instruction to retry.',
|
|
1250
|
+
'Do not retry, resume, restart, or continue any tool call or task that was interrupted by that stop.',
|
|
1251
|
+
'Respond only to the human\'s latest message on its own terms. Resume the earlier work only if the human explicitly asks for it again.',
|
|
1252
|
+
].join(' ');
|
|
1253
|
+
/** Whether a `turn/end` reason is a human-initiated abort (stop, /new, or a declined approval). */
|
|
1254
|
+
function isUserAbortedTurnEnd(reason) {
|
|
1255
|
+
return typeof reason === 'object' && reason !== null
|
|
1256
|
+
&& reason.kind === 'aborted'
|
|
1257
|
+
&& typeof reason.reason === 'object'
|
|
1258
|
+
&& reason.reason?.kind === 'user';
|
|
1259
|
+
}
|
|
1260
|
+
/**
|
|
1261
|
+
* Returns the fixed Host clarification when the most recent turn boundary is a
|
|
1262
|
+
* human abort whose turn contains an aborted-before-dispatch tool result;
|
|
1263
|
+
* otherwise `''`. Pure over the supplied events so the projection dedups stable
|
|
1264
|
+
* text across repeated no-op messages and flips to empty once a turn completes.
|
|
1265
|
+
*/
|
|
1266
|
+
function userCancelledToolNotice(events) {
|
|
1267
|
+
let lastEnd;
|
|
1268
|
+
for (let index = events.length - 1; index >= 0; index -= 1) {
|
|
1269
|
+
const event = events[index];
|
|
1270
|
+
if (event?.type === 'turn/end') {
|
|
1271
|
+
lastEnd = event;
|
|
1272
|
+
break;
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
if (lastEnd === undefined || !isUserAbortedTurnEnd(lastEnd.data.reason))
|
|
1276
|
+
return '';
|
|
1277
|
+
const abortedBeforeDispatch = events.some(event => event.type === 'tool/result'
|
|
1278
|
+
&& event.data.turn === lastEnd.data.turn
|
|
1279
|
+
&& event.data.error?.code === TOOL_ABORTED_BEFORE_DISPATCH);
|
|
1280
|
+
return abortedBeforeDispatch ? USER_CANCELLED_TOOL_NOTICE : '';
|
|
1281
|
+
}
|
|
1282
|
+
export class DshDeliveryRuntime {
|
|
1283
|
+
ctx;
|
|
1284
|
+
policy;
|
|
1285
|
+
options;
|
|
1286
|
+
restartRuns = new WeakMap();
|
|
1287
|
+
canRequestRestart(agent) { return this.restartRuns.get(agent)?.canRequest() === true; }
|
|
1288
|
+
requestRestart(agent, reason) {
|
|
1289
|
+
const run = this.restartRuns.get(agent);
|
|
1290
|
+
if (run === undefined)
|
|
1291
|
+
throw new Error('assistant-delivery: this foreground task has no restart authority');
|
|
1292
|
+
const record = run.request(reason);
|
|
1293
|
+
return { id: record.id, status: record.status };
|
|
1294
|
+
}
|
|
1295
|
+
async resumeRestart(record, binding, envelope, signal) {
|
|
1296
|
+
const restart = this.options.restart;
|
|
1297
|
+
if (restart === undefined || !restart.authorize(record))
|
|
1298
|
+
throw new Error('assistant-delivery: restart continuation is not authorized');
|
|
1299
|
+
return await this.process(binding, envelope, signal, undefined, () => {
|
|
1300
|
+
if (!restart.authorize(record))
|
|
1301
|
+
throw new Error('assistant-delivery: restart continuation authority changed');
|
|
1302
|
+
}, record);
|
|
1303
|
+
}
|
|
1304
|
+
dispatchControl = 'explicit';
|
|
1305
|
+
activeSessionControls = new Map();
|
|
1306
|
+
sessionLeases;
|
|
1307
|
+
constructor(ctx, policy, options) {
|
|
1308
|
+
this.ctx = ctx;
|
|
1309
|
+
this.policy = policy;
|
|
1310
|
+
this.options = options;
|
|
1311
|
+
this.sessionLeases = options.sessionLeases;
|
|
1312
|
+
}
|
|
1313
|
+
async resumeAgent(options) {
|
|
1314
|
+
const id = String(options.resumeSessionId);
|
|
1315
|
+
this.sessionLeases.assert(id);
|
|
1316
|
+
return this.sessionLeases.resume(this.ctx, options);
|
|
1317
|
+
}
|
|
1318
|
+
async cancelActive(binding, command) {
|
|
1319
|
+
const sessionId = binding.sessionId;
|
|
1320
|
+
const control = this.activeSessionControls.get(sessionId);
|
|
1321
|
+
const agents = this.ctx.get('agents');
|
|
1322
|
+
const agent = agents?.get(SessionId(sessionId));
|
|
1323
|
+
const activeAgent = agent !== undefined && agent.status !== 'idle';
|
|
1324
|
+
if (control === undefined && !activeAgent)
|
|
1325
|
+
return false;
|
|
1326
|
+
if (control !== undefined) {
|
|
1327
|
+
// A generation boundary is stronger than a stop acknowledgement. Never
|
|
1328
|
+
// let a later `/stop` downgrade an in-flight `/new` cancellation.
|
|
1329
|
+
control.command = control.command === 'new' || command === 'new' ? 'new' : 'stop';
|
|
1330
|
+
control.resolveCancelRequested();
|
|
1331
|
+
if (!control.controller.signal.aborted) {
|
|
1332
|
+
control.controller.abort(new UserSessionCancellation(control.command));
|
|
1333
|
+
}
|
|
1334
|
+
this.sessionLeases.cancel(sessionId, new UserSessionCancellation(control.command));
|
|
1335
|
+
}
|
|
1336
|
+
// `whenIdle()` follows every later wakeup. Waiting on it here lets an
|
|
1337
|
+
// unrelated followup keep `/stop` or `/new` alive forever. Clear pending
|
|
1338
|
+
// input and wait only for Delivery's exact reply-scheduling boundary.
|
|
1339
|
+
if (activeAgent)
|
|
1340
|
+
agent.cancel({ kind: 'user' });
|
|
1341
|
+
if (control !== undefined)
|
|
1342
|
+
await control.replySafe;
|
|
1343
|
+
return true;
|
|
1344
|
+
}
|
|
1345
|
+
beginSessionControl(sessionId, outer) {
|
|
1346
|
+
if (this.activeSessionControls.has(sessionId)) {
|
|
1347
|
+
throw new Error(`assistant-delivery: session ${sessionFingerprint(sessionId)} is already processing an inbound`);
|
|
1348
|
+
}
|
|
1349
|
+
const controller = new AbortController();
|
|
1350
|
+
let resolveCancelRequested;
|
|
1351
|
+
let resolveReplySafe;
|
|
1352
|
+
const cancelRequested = new Promise(resolve => { resolveCancelRequested = resolve; });
|
|
1353
|
+
const replySafe = new Promise(resolve => { resolveReplySafe = resolve; });
|
|
1354
|
+
const abort = () => controller.abort(outer.reason);
|
|
1355
|
+
outer.addEventListener('abort', abort, { once: true });
|
|
1356
|
+
if (outer.aborted)
|
|
1357
|
+
abort();
|
|
1358
|
+
const control = {
|
|
1359
|
+
controller,
|
|
1360
|
+
cancelRequested,
|
|
1361
|
+
replySafe,
|
|
1362
|
+
removeOuterAbort: () => outer.removeEventListener('abort', abort),
|
|
1363
|
+
resolveCancelRequested,
|
|
1364
|
+
resolveReplySafe,
|
|
1365
|
+
};
|
|
1366
|
+
this.activeSessionControls.set(sessionId, control);
|
|
1367
|
+
return control;
|
|
1368
|
+
}
|
|
1369
|
+
endSessionControl(sessionId, control) {
|
|
1370
|
+
control.removeOuterAbort();
|
|
1371
|
+
control.resolveReplySafe();
|
|
1372
|
+
if (this.activeSessionControls.get(sessionId) === control)
|
|
1373
|
+
this.activeSessionControls.delete(sessionId);
|
|
1374
|
+
}
|
|
1375
|
+
/**
|
|
1376
|
+
* Keep one Delivery-owned handle alive just long enough for the host's native
|
|
1377
|
+
* goal driver to retire the exact armed goal it observed. Delivery never
|
|
1378
|
+
* queues a round itself: the driver remains the only continuation producer.
|
|
1379
|
+
*/
|
|
1380
|
+
waitForNativeGoalContinuation(binding, envelope, agent, signal) {
|
|
1381
|
+
if (this.options.goalContinuationTimeoutMs === 0)
|
|
1382
|
+
return undefined;
|
|
1383
|
+
const goals = this.ctx.get('goals');
|
|
1384
|
+
const agents = this.ctx.get('agents');
|
|
1385
|
+
if (goals === undefined || agents?.get(agent.id) !== agent)
|
|
1386
|
+
return undefined;
|
|
1387
|
+
let initial;
|
|
1388
|
+
try {
|
|
1389
|
+
initial = goals.get(agent);
|
|
1390
|
+
}
|
|
1391
|
+
catch {
|
|
1392
|
+
return undefined;
|
|
1393
|
+
}
|
|
1394
|
+
// Install this watcher before the foreground followup. A goal can be
|
|
1395
|
+
// resumed or created by that turn, and the native round driver observes
|
|
1396
|
+
// the same idle boundary immediately afterwards.
|
|
1397
|
+
if (initial?.phase !== 'active' || initial.activation !== 'armed')
|
|
1398
|
+
initial = undefined;
|
|
1399
|
+
let goalId = initial === undefined ? undefined : String(initial.id);
|
|
1400
|
+
const session = agent.session;
|
|
1401
|
+
let settled = false;
|
|
1402
|
+
let settledQuiescent = false;
|
|
1403
|
+
// `goal/changed` is synchronous. In particular, disarming our own goal can
|
|
1404
|
+
// emit it before cancelUnknown() has reached finish(false), so remember that
|
|
1405
|
+
// this is a forced, unknown outcome before mutating the native goal.
|
|
1406
|
+
let cancelling = false;
|
|
1407
|
+
let activeGoalSteps = 0;
|
|
1408
|
+
let settleRequested = false;
|
|
1409
|
+
let resolve;
|
|
1410
|
+
const completion = new Promise(done => { resolve = done; });
|
|
1411
|
+
let timeout;
|
|
1412
|
+
let deadlineAt;
|
|
1413
|
+
let removeGoalChanged;
|
|
1414
|
+
let removeStatus;
|
|
1415
|
+
let removeAbort;
|
|
1416
|
+
let removePreStep;
|
|
1417
|
+
let removeRequest;
|
|
1418
|
+
let removePreExecute;
|
|
1419
|
+
let removeToolGuard;
|
|
1420
|
+
const releaseFences = () => {
|
|
1421
|
+
removeGoalChanged?.();
|
|
1422
|
+
removeStatus?.();
|
|
1423
|
+
removeAbort?.();
|
|
1424
|
+
removePreStep?.();
|
|
1425
|
+
removeRequest?.();
|
|
1426
|
+
removePreExecute?.();
|
|
1427
|
+
removeToolGuard?.();
|
|
1428
|
+
removeGoalChanged = undefined;
|
|
1429
|
+
removeStatus = undefined;
|
|
1430
|
+
removeAbort = undefined;
|
|
1431
|
+
removePreStep = undefined;
|
|
1432
|
+
removeRequest = undefined;
|
|
1433
|
+
removePreExecute = undefined;
|
|
1434
|
+
removeToolGuard = undefined;
|
|
1435
|
+
};
|
|
1436
|
+
const finish = (quiescent) => {
|
|
1437
|
+
if (settled)
|
|
1438
|
+
return;
|
|
1439
|
+
settled = true;
|
|
1440
|
+
settledQuiescent = quiescent;
|
|
1441
|
+
resolve(quiescent);
|
|
1442
|
+
};
|
|
1443
|
+
const isAuthorized = () => {
|
|
1444
|
+
try {
|
|
1445
|
+
return this.options.isInboundAuthorized(binding, envelope);
|
|
1446
|
+
}
|
|
1447
|
+
catch {
|
|
1448
|
+
return false;
|
|
1449
|
+
}
|
|
1450
|
+
};
|
|
1451
|
+
const pinArmedGoal = () => {
|
|
1452
|
+
if (goalId !== undefined || settleRequested)
|
|
1453
|
+
return goalId !== undefined;
|
|
1454
|
+
try {
|
|
1455
|
+
const current = goals.get(agent);
|
|
1456
|
+
if (current?.phase !== 'active' || current.activation !== 'armed')
|
|
1457
|
+
return false;
|
|
1458
|
+
initial = current;
|
|
1459
|
+
goalId = String(current.id);
|
|
1460
|
+
return true;
|
|
1461
|
+
}
|
|
1462
|
+
catch {
|
|
1463
|
+
return false;
|
|
1464
|
+
}
|
|
1465
|
+
};
|
|
1466
|
+
const disposition = () => {
|
|
1467
|
+
// A replacement is deliberately not adopted. It needs its own explicit
|
|
1468
|
+
// foreground owner/acceptance boundary.
|
|
1469
|
+
if (goalId === undefined || initial === undefined)
|
|
1470
|
+
return 'still-running';
|
|
1471
|
+
if (agents?.get(agent.id) !== agent || agent.session !== session)
|
|
1472
|
+
return 'unavailable';
|
|
1473
|
+
try {
|
|
1474
|
+
const current = goals.get(agent);
|
|
1475
|
+
if (current === undefined)
|
|
1476
|
+
return 'settled';
|
|
1477
|
+
if (String(current.id) !== goalId)
|
|
1478
|
+
return 'replacement';
|
|
1479
|
+
return current.phase !== 'active' || current.activation !== 'armed'
|
|
1480
|
+
? 'settled'
|
|
1481
|
+
: 'still-running';
|
|
1482
|
+
}
|
|
1483
|
+
catch {
|
|
1484
|
+
return 'unavailable';
|
|
1485
|
+
}
|
|
1486
|
+
};
|
|
1487
|
+
const disarmAndCancel = (reason) => {
|
|
1488
|
+
try {
|
|
1489
|
+
const current = goals.get(agent);
|
|
1490
|
+
if (goalId !== undefined && current !== undefined && String(current.id) === goalId
|
|
1491
|
+
&& current.phase === 'active' && current.activation === 'armed') {
|
|
1492
|
+
goals.disarm(agent);
|
|
1493
|
+
}
|
|
1494
|
+
}
|
|
1495
|
+
catch { }
|
|
1496
|
+
try {
|
|
1497
|
+
agent.cancel({ kind: 'hook', reason });
|
|
1498
|
+
}
|
|
1499
|
+
catch { }
|
|
1500
|
+
};
|
|
1501
|
+
const finishNaturally = () => {
|
|
1502
|
+
// Goal state is only an observation. It cannot turn a cancelled or
|
|
1503
|
+
// revoked foreground authority into a successful, quiescent outcome.
|
|
1504
|
+
if (signal.aborted) {
|
|
1505
|
+
cancelUnknown('assistant-delivery-goal-continuation-cancelled');
|
|
1506
|
+
}
|
|
1507
|
+
else if (!isAuthorized()) {
|
|
1508
|
+
cancelUnknown('assistant-delivery-goal-continuation-authorization-revoked');
|
|
1509
|
+
}
|
|
1510
|
+
else {
|
|
1511
|
+
finish(true);
|
|
1512
|
+
}
|
|
1513
|
+
};
|
|
1514
|
+
const maybeFinish = () => {
|
|
1515
|
+
if (settled || cancelling || activeGoalSteps !== 0 || goalId === undefined)
|
|
1516
|
+
return;
|
|
1517
|
+
// A terminal goal record does not prove that its final model/tool turn
|
|
1518
|
+
// has retired. `whenIdle()` is deliberately avoided here because it
|
|
1519
|
+
// can follow a later wakeup forever; the current Agent state and inbox
|
|
1520
|
+
// are the bounded observation needed before declaring quiescence.
|
|
1521
|
+
if (agent.status !== 'idle' || (agent.inbox.nextTurn.length > 0 || agent.inbox.nextStep.length > 0))
|
|
1522
|
+
return;
|
|
1523
|
+
const current = disposition();
|
|
1524
|
+
if (current === 'settled')
|
|
1525
|
+
finishNaturally();
|
|
1526
|
+
// Missing identity/readback and replacement are intentionally unknown:
|
|
1527
|
+
// neither proves that the exact pinned goal drained.
|
|
1528
|
+
else if (current !== 'still-running')
|
|
1529
|
+
finish(false);
|
|
1530
|
+
};
|
|
1531
|
+
const cancelUnknown = (reason) => {
|
|
1532
|
+
if (cancelling)
|
|
1533
|
+
return;
|
|
1534
|
+
cancelling = true;
|
|
1535
|
+
disarmAndCancel(reason);
|
|
1536
|
+
// A hard timeout or /stop must settle this foreground operation even if
|
|
1537
|
+
// a third-party tool ignores cancellation. Keep the fences until the
|
|
1538
|
+
// Delivery-owned handle is disposed, rather than waiting for idle here.
|
|
1539
|
+
if (!settled)
|
|
1540
|
+
finish(false);
|
|
1541
|
+
};
|
|
1542
|
+
const guardContinuationAuthorization = () => {
|
|
1543
|
+
if (cancelling)
|
|
1544
|
+
return false;
|
|
1545
|
+
if (isAuthorized())
|
|
1546
|
+
return true;
|
|
1547
|
+
cancelUnknown('assistant-delivery-goal-continuation-authorization-revoked');
|
|
1548
|
+
return false;
|
|
1549
|
+
};
|
|
1550
|
+
const teardownTimeoutMs = () => deadlineAt === undefined
|
|
1551
|
+
? undefined
|
|
1552
|
+
: Math.max(0, deadlineAt - Date.now());
|
|
1553
|
+
const isQuiescent = () => {
|
|
1554
|
+
if (!settledQuiescent || cancelling)
|
|
1555
|
+
return false;
|
|
1556
|
+
// The goal can reach a terminal native state before the Agent scope has
|
|
1557
|
+
// finished disposing. Authority is still live at that point.
|
|
1558
|
+
if (signal.aborted || !isAuthorized()) {
|
|
1559
|
+
cancelUnknown(signal.aborted
|
|
1560
|
+
? 'assistant-delivery-goal-continuation-cancelled'
|
|
1561
|
+
: 'assistant-delivery-goal-continuation-authorization-revoked');
|
|
1562
|
+
return false;
|
|
1563
|
+
}
|
|
1564
|
+
return true;
|
|
1565
|
+
};
|
|
1566
|
+
removeGoalChanged = this.ctx.on('goal/changed', ({ agent: changed }) => {
|
|
1567
|
+
if (changed !== agent)
|
|
1568
|
+
return;
|
|
1569
|
+
pinArmedGoal();
|
|
1570
|
+
maybeFinish();
|
|
1571
|
+
});
|
|
1572
|
+
removeStatus = this.ctx.on('agent/status', ({ agent: changed, status }) => {
|
|
1573
|
+
// The round driver can wake after an idle status, so idle alone is not a
|
|
1574
|
+
// completion signal. It is only useful after the goal itself disarmed.
|
|
1575
|
+
if (changed === agent && status === 'idle')
|
|
1576
|
+
maybeFinish();
|
|
1577
|
+
});
|
|
1578
|
+
const aborted = () => cancelUnknown('assistant-delivery-goal-continuation-cancelled');
|
|
1579
|
+
signal.addEventListener('abort', aborted, { once: true });
|
|
1580
|
+
removeAbort = () => signal.removeEventListener('abort', aborted);
|
|
1581
|
+
removePreStep = agent.ctx.on('agent/pre-step', async (_input, next) => {
|
|
1582
|
+
// The native loop supplies only the inbox claim for a later model step;
|
|
1583
|
+
// after a tool result it need not repeat the original `goal` source.
|
|
1584
|
+
// Once this watcher fixed a GoalId, every later model step on the owned
|
|
1585
|
+
// Agent is therefore fenced until its handle tears down.
|
|
1586
|
+
if (goalId === undefined)
|
|
1587
|
+
return await next();
|
|
1588
|
+
if (!guardContinuationAuthorization())
|
|
1589
|
+
return { kind: 'reject' };
|
|
1590
|
+
activeGoalSteps += 1;
|
|
1591
|
+
try {
|
|
1592
|
+
const result = await next();
|
|
1593
|
+
// A pre-step waterfall's `next()` can finish before the next model
|
|
1594
|
+
// boundary. Recheck immediately after it so a revocation in that
|
|
1595
|
+
// window still cancels the owned Agent before another request/tool.
|
|
1596
|
+
if (!guardContinuationAuthorization())
|
|
1597
|
+
return { kind: 'reject' };
|
|
1598
|
+
return result;
|
|
1599
|
+
}
|
|
1600
|
+
finally {
|
|
1601
|
+
activeGoalSteps -= 1;
|
|
1602
|
+
// Do not wait for `whenIdle()`: an uncooperative tool can keep it
|
|
1603
|
+
// pending forever. The timeout/cancellation path already settled
|
|
1604
|
+
// non-quiescent, and the fences remain until handle teardown.
|
|
1605
|
+
maybeFinish();
|
|
1606
|
+
}
|
|
1607
|
+
}, { prepend: true });
|
|
1608
|
+
removeRequest = agent.ctx.on('agent/request', async (_payload, next) => {
|
|
1609
|
+
if (goalId === undefined)
|
|
1610
|
+
return await next();
|
|
1611
|
+
if (!guardContinuationAuthorization()) {
|
|
1612
|
+
throw new Error('assistant-delivery: goal continuation authorization revoked before model request');
|
|
1613
|
+
}
|
|
1614
|
+
const request = await next();
|
|
1615
|
+
if (!guardContinuationAuthorization()) {
|
|
1616
|
+
throw new Error('assistant-delivery: goal continuation authorization revoked while preparing model request');
|
|
1617
|
+
}
|
|
1618
|
+
return request;
|
|
1619
|
+
}, { prepend: true });
|
|
1620
|
+
removePreExecute = agent.ctx.on('tools/pre-execute', async (_execution, next) => {
|
|
1621
|
+
if (guardContinuationAuthorization())
|
|
1622
|
+
return await next();
|
|
1623
|
+
return { kind: 'deny', reason: 'assistant-delivery: goal continuation authorization revoked' };
|
|
1624
|
+
}, { prepend: true });
|
|
1625
|
+
removeToolGuard = agent.ctx.tools.guard(() => guardContinuationAuthorization()
|
|
1626
|
+
? undefined
|
|
1627
|
+
: 'assistant-delivery: goal continuation authorization revoked');
|
|
1628
|
+
const beginSettling = () => {
|
|
1629
|
+
if (!settleRequested) {
|
|
1630
|
+
settleRequested = true;
|
|
1631
|
+
// A goal may create and complete during the foreground pre-step,
|
|
1632
|
+
// before Delivery reaches `settle()`. That still leaves its Agent
|
|
1633
|
+
// scope to tear down, so it needs the same bounded deadline.
|
|
1634
|
+
deadlineAt = Date.now() + this.options.goalContinuationTimeoutMs;
|
|
1635
|
+
}
|
|
1636
|
+
if (settled)
|
|
1637
|
+
return completion;
|
|
1638
|
+
if (goalId === undefined) {
|
|
1639
|
+
finishNaturally();
|
|
1640
|
+
return completion;
|
|
1641
|
+
}
|
|
1642
|
+
timeout = setTimeout(() => cancelUnknown('assistant-delivery-goal-continuation-timeout'), this.options.goalContinuationTimeoutMs);
|
|
1643
|
+
timeout.unref?.();
|
|
1644
|
+
// A driver may have already claimed its first round before the original
|
|
1645
|
+
// Delivery turn reached its reply boundary. All step and tool guards
|
|
1646
|
+
// were installed above, before that round could begin.
|
|
1647
|
+
if (signal.aborted)
|
|
1648
|
+
cancelUnknown('assistant-delivery-goal-continuation-cancelled');
|
|
1649
|
+
else if (!isAuthorized())
|
|
1650
|
+
cancelUnknown('assistant-delivery-goal-continuation-authorization-revoked');
|
|
1651
|
+
else
|
|
1652
|
+
maybeFinish();
|
|
1653
|
+
return completion;
|
|
1654
|
+
};
|
|
1655
|
+
if (signal.aborted)
|
|
1656
|
+
aborted();
|
|
1657
|
+
return {
|
|
1658
|
+
settle: beginSettling,
|
|
1659
|
+
pinActiveArmedGoal: pinArmedGoal,
|
|
1660
|
+
teardownTimeoutMs,
|
|
1661
|
+
isQuiescent,
|
|
1662
|
+
dispose: () => {
|
|
1663
|
+
if (timeout !== undefined)
|
|
1664
|
+
clearTimeout(timeout);
|
|
1665
|
+
if (!settled)
|
|
1666
|
+
cancelUnknown('assistant-delivery-goal-continuation-teardown');
|
|
1667
|
+
releaseFences();
|
|
1668
|
+
},
|
|
1669
|
+
};
|
|
1670
|
+
}
|
|
1671
|
+
async disposeAfterReplyBoundary(sessionId, handle, afterDisposed, abandonDisposal = false, timeoutMs) {
|
|
1672
|
+
const control = this.activeSessionControls.get(sessionId);
|
|
1673
|
+
control?.resolveReplySafe();
|
|
1674
|
+
if (handle === undefined) {
|
|
1675
|
+
afterDisposed?.();
|
|
1676
|
+
return true;
|
|
1677
|
+
}
|
|
1678
|
+
const disposal = Promise.resolve().then(() => handle.dispose());
|
|
1679
|
+
let clearDeadline;
|
|
1680
|
+
const deadline = timeoutMs === undefined
|
|
1681
|
+
? undefined
|
|
1682
|
+
: timeoutMs <= 0
|
|
1683
|
+
? Promise.resolve('timed-out')
|
|
1684
|
+
: new Promise(resolve => {
|
|
1685
|
+
const timeout = setTimeout(() => resolve('timed-out'), timeoutMs);
|
|
1686
|
+
timeout.unref?.();
|
|
1687
|
+
clearDeadline = () => clearTimeout(timeout);
|
|
1688
|
+
});
|
|
1689
|
+
let removeAbort;
|
|
1690
|
+
const aborted = control === undefined
|
|
1691
|
+
? undefined
|
|
1692
|
+
: new Promise(resolve => {
|
|
1693
|
+
const abort = () => resolve('aborted');
|
|
1694
|
+
control.controller.signal.addEventListener('abort', abort, { once: true });
|
|
1695
|
+
removeAbort = () => control.controller.signal.removeEventListener('abort', abort);
|
|
1696
|
+
if (control.controller.signal.aborted)
|
|
1697
|
+
abort();
|
|
1698
|
+
});
|
|
1699
|
+
let released = false;
|
|
1700
|
+
const releaseAfterDisposal = () => {
|
|
1701
|
+
if (released)
|
|
1702
|
+
return;
|
|
1703
|
+
released = true;
|
|
1704
|
+
try {
|
|
1705
|
+
afterDisposed?.();
|
|
1706
|
+
}
|
|
1707
|
+
catch (error) {
|
|
1708
|
+
this.ctx.logger.warn(`assistant-delivery: continuation fence release failed: ${String(error)}`);
|
|
1709
|
+
}
|
|
1710
|
+
};
|
|
1711
|
+
let disposition;
|
|
1712
|
+
try {
|
|
1713
|
+
disposition = control === undefined
|
|
1714
|
+
? (abandonDisposal ? 'abandoned' : await Promise.race([
|
|
1715
|
+
disposal.then(() => 'disposed', () => 'rejected'),
|
|
1716
|
+
...(deadline === undefined ? [] : [deadline]),
|
|
1717
|
+
]))
|
|
1718
|
+
: await Promise.race([
|
|
1719
|
+
disposal.then(() => 'disposed', () => 'rejected'),
|
|
1720
|
+
control.cancelRequested.then(() => 'cancelled'),
|
|
1721
|
+
...(aborted === undefined ? [] : [aborted]),
|
|
1722
|
+
...(deadline === undefined ? [] : [deadline]),
|
|
1723
|
+
...(abandonDisposal ? [Promise.resolve('abandoned')] : []),
|
|
1724
|
+
]);
|
|
1725
|
+
}
|
|
1726
|
+
finally {
|
|
1727
|
+
removeAbort?.();
|
|
1728
|
+
clearDeadline?.();
|
|
1729
|
+
}
|
|
1730
|
+
if (disposition === 'cancelled' || disposition === 'abandoned'
|
|
1731
|
+
|| disposition === 'aborted' || disposition === 'timed-out') {
|
|
1732
|
+
// The Delivery turn is already cancelled and cannot enqueue another
|
|
1733
|
+
// reply. Teardown remains owned, but a third-party disposer must not
|
|
1734
|
+
// hold the conversation transition or its fresh generation hostage.
|
|
1735
|
+
void disposal.then(() => releaseAfterDisposal(), error => {
|
|
1736
|
+
this.ctx.logger.warn(`assistant-delivery: detached session disposer failed for ${sessionFingerprint(sessionId)}: ${String(error)}`);
|
|
1737
|
+
releaseAfterDisposal();
|
|
1738
|
+
});
|
|
1739
|
+
return false;
|
|
1740
|
+
}
|
|
1741
|
+
releaseAfterDisposal();
|
|
1742
|
+
if (disposition === 'rejected') {
|
|
1743
|
+
this.ctx.logger.warn(`assistant-delivery: session disposer failed for ${sessionFingerprint(sessionId)}`);
|
|
1744
|
+
return false;
|
|
1745
|
+
}
|
|
1746
|
+
return true;
|
|
1747
|
+
}
|
|
1748
|
+
/** Wait for only the turn that claims Delivery's exact message identity. */
|
|
1749
|
+
followupTurn(agent, message, onClaimed, onSettled, admit, signal) {
|
|
1750
|
+
return new Promise((resolve, reject) => {
|
|
1751
|
+
let claimedTurn;
|
|
1752
|
+
let settled = false;
|
|
1753
|
+
let abortDeadline;
|
|
1754
|
+
const cleanup = () => {
|
|
1755
|
+
if (abortDeadline !== undefined)
|
|
1756
|
+
clearTimeout(abortDeadline);
|
|
1757
|
+
signal?.removeEventListener('abort', aborted);
|
|
1758
|
+
removeClaimed();
|
|
1759
|
+
removeDiscarded();
|
|
1760
|
+
removeSessionEvent();
|
|
1761
|
+
};
|
|
1762
|
+
const settle = (turn) => {
|
|
1763
|
+
if (settled)
|
|
1764
|
+
return;
|
|
1765
|
+
settled = true;
|
|
1766
|
+
cleanup();
|
|
1767
|
+
resolve(turn);
|
|
1768
|
+
};
|
|
1769
|
+
const fail = (error) => {
|
|
1770
|
+
if (settled)
|
|
1771
|
+
return;
|
|
1772
|
+
settled = true;
|
|
1773
|
+
cleanup();
|
|
1774
|
+
reject(error);
|
|
1775
|
+
};
|
|
1776
|
+
const aborted = () => {
|
|
1777
|
+
// Let cooperative native cancellation persist its tool result and
|
|
1778
|
+
// turn/end before disposing. Uncooperative tools get only this grace.
|
|
1779
|
+
abortDeadline ??= setTimeout(() => fail(signal?.reason
|
|
1780
|
+
?? new Error('assistant-delivery: execution aborted')), 1_000);
|
|
1781
|
+
abortDeadline.unref?.();
|
|
1782
|
+
};
|
|
1783
|
+
const removeClaimed = this.ctx.on('agent/inbox/claimed', event => {
|
|
1784
|
+
if (event.agent === agent && event.message.id === message.id) {
|
|
1785
|
+
claimedTurn = event.turn;
|
|
1786
|
+
onClaimed?.(event.turn);
|
|
1787
|
+
}
|
|
1788
|
+
});
|
|
1789
|
+
const removeDiscarded = this.ctx.on('agent/inbox/discarded', event => {
|
|
1790
|
+
if (event.agent !== agent || event.message.id !== message.id)
|
|
1791
|
+
return;
|
|
1792
|
+
try {
|
|
1793
|
+
onSettled?.();
|
|
1794
|
+
}
|
|
1795
|
+
catch (error) {
|
|
1796
|
+
fail(error);
|
|
1797
|
+
return;
|
|
1798
|
+
}
|
|
1799
|
+
settle(undefined);
|
|
1800
|
+
});
|
|
1801
|
+
const removeSessionEvent = this.ctx.on('session/event', (session, event) => {
|
|
1802
|
+
if (session === agent.session && event.type === 'turn/end' && event.data.turn === claimedTurn) {
|
|
1803
|
+
try {
|
|
1804
|
+
onSettled?.();
|
|
1805
|
+
}
|
|
1806
|
+
catch (error) {
|
|
1807
|
+
fail(error);
|
|
1808
|
+
return;
|
|
1809
|
+
}
|
|
1810
|
+
settle(claimedTurn);
|
|
1811
|
+
}
|
|
1812
|
+
});
|
|
1813
|
+
signal?.addEventListener('abort', aborted, { once: true });
|
|
1814
|
+
if (signal?.aborted) {
|
|
1815
|
+
fail(signal.reason);
|
|
1816
|
+
return;
|
|
1817
|
+
}
|
|
1818
|
+
try {
|
|
1819
|
+
if (admit === undefined)
|
|
1820
|
+
agent.followup(message);
|
|
1821
|
+
else
|
|
1822
|
+
void admit().then(state => {
|
|
1823
|
+
if (state.kind === 'settled')
|
|
1824
|
+
settle(state.turn);
|
|
1825
|
+
else if (state.kind !== 'pending')
|
|
1826
|
+
fail(new Error('assistant-delivery: continuation was already dispatched without a settled result'));
|
|
1827
|
+
}, fail);
|
|
1828
|
+
}
|
|
1829
|
+
catch (error) {
|
|
1830
|
+
fail(error);
|
|
1831
|
+
}
|
|
1832
|
+
});
|
|
1833
|
+
}
|
|
1834
|
+
/** Wait only for scheduling quiescence; exact turn ownership still comes from followupTurn(). */
|
|
1835
|
+
async waitForAgentIdle(agent, signal) {
|
|
1836
|
+
signal.throwIfAborted();
|
|
1837
|
+
while (true) {
|
|
1838
|
+
await new Promise((resolve, reject) => {
|
|
1839
|
+
let settled = false;
|
|
1840
|
+
const cleanup = () => signal.removeEventListener('abort', aborted);
|
|
1841
|
+
const finish = () => {
|
|
1842
|
+
if (settled)
|
|
1843
|
+
return;
|
|
1844
|
+
settled = true;
|
|
1845
|
+
cleanup();
|
|
1846
|
+
resolve();
|
|
1847
|
+
};
|
|
1848
|
+
const fail = (error) => {
|
|
1849
|
+
if (settled)
|
|
1850
|
+
return;
|
|
1851
|
+
settled = true;
|
|
1852
|
+
cleanup();
|
|
1853
|
+
reject(error);
|
|
1854
|
+
};
|
|
1855
|
+
const aborted = () => {
|
|
1856
|
+
try {
|
|
1857
|
+
signal.throwIfAborted();
|
|
1858
|
+
}
|
|
1859
|
+
catch (error) {
|
|
1860
|
+
fail(error);
|
|
1861
|
+
}
|
|
1862
|
+
};
|
|
1863
|
+
signal.addEventListener('abort', aborted, { once: true });
|
|
1864
|
+
void agent.whenIdle().then(finish, fail);
|
|
1865
|
+
if (signal.aborted)
|
|
1866
|
+
aborted();
|
|
1867
|
+
});
|
|
1868
|
+
signal.throwIfAborted();
|
|
1869
|
+
if (agent.status === 'idle')
|
|
1870
|
+
return;
|
|
1871
|
+
}
|
|
1872
|
+
}
|
|
1873
|
+
/**
|
|
1874
|
+
* Queue a synthetic completion turn only after the previous exact turn retired. The runtime may still
|
|
1875
|
+
* serialize scoped tool schemas, but every call is denied before approval/execution while this
|
|
1876
|
+
* turn owns the Agent, so recovering prose cannot repeat an external side effect.
|
|
1877
|
+
*/
|
|
1878
|
+
async automaticCompletionTurn(agent, message, signal, expectedPreviousTurn, authorize, onClaimed) {
|
|
1879
|
+
await this.waitForAgentIdle(agent, signal);
|
|
1880
|
+
signal.throwIfAborted();
|
|
1881
|
+
let liftPreExecute;
|
|
1882
|
+
let liftRestriction;
|
|
1883
|
+
let liftGuard;
|
|
1884
|
+
let submitted = false;
|
|
1885
|
+
let exactTurnSettled = false;
|
|
1886
|
+
const releaseToolBarriers = () => {
|
|
1887
|
+
let firstError;
|
|
1888
|
+
if (liftGuard !== undefined) {
|
|
1889
|
+
try {
|
|
1890
|
+
liftGuard();
|
|
1891
|
+
liftGuard = undefined;
|
|
1892
|
+
}
|
|
1893
|
+
catch (error) {
|
|
1894
|
+
firstError ??= error;
|
|
1895
|
+
}
|
|
1896
|
+
}
|
|
1897
|
+
if (liftRestriction !== undefined) {
|
|
1898
|
+
try {
|
|
1899
|
+
liftRestriction();
|
|
1900
|
+
liftRestriction = undefined;
|
|
1901
|
+
}
|
|
1902
|
+
catch (error) {
|
|
1903
|
+
firstError ??= error;
|
|
1904
|
+
}
|
|
1905
|
+
}
|
|
1906
|
+
if (liftPreExecute !== undefined) {
|
|
1907
|
+
try {
|
|
1908
|
+
liftPreExecute();
|
|
1909
|
+
liftPreExecute = undefined;
|
|
1910
|
+
}
|
|
1911
|
+
catch (error) {
|
|
1912
|
+
firstError ??= error;
|
|
1913
|
+
}
|
|
1914
|
+
}
|
|
1915
|
+
if (firstError !== undefined)
|
|
1916
|
+
throw firstError;
|
|
1917
|
+
};
|
|
1918
|
+
try {
|
|
1919
|
+
liftPreExecute = agent.ctx.on('tools/pre-execute', () => Promise.resolve({
|
|
1920
|
+
kind: 'deny',
|
|
1921
|
+
reason: AUTOMATIC_COMPLETION_TOOL_DENIAL,
|
|
1922
|
+
}), { prepend: true });
|
|
1923
|
+
liftRestriction = agent.ctx.tools.restrict({ allow: [] });
|
|
1924
|
+
liftGuard = agent.ctx.tools.guard(() => AUTOMATIC_COMPLETION_TOOL_DENIAL);
|
|
1925
|
+
signal.throwIfAborted();
|
|
1926
|
+
if (agent.status !== 'idle' || (agent.inbox.nextTurn.length > 0 || agent.inbox.nextStep.length > 0)) {
|
|
1927
|
+
throw new AutomaticCompletionUnavailableError('assistant-delivery: automatic completion lost the idle scheduling boundary');
|
|
1928
|
+
}
|
|
1929
|
+
const latestBoundary = agent.session.snapshotEvents().findLast(event => event.type === 'turn/start' || event.type === 'turn/end');
|
|
1930
|
+
if (latestBoundary?.type !== 'turn/end' || latestBoundary.data.turn !== expectedPreviousTurn) {
|
|
1931
|
+
throw new AutomaticCompletionUnavailableError('assistant-delivery: another turn crossed the automatic completion boundary');
|
|
1932
|
+
}
|
|
1933
|
+
const authorization = authorize();
|
|
1934
|
+
if (authorization !== 'authorized')
|
|
1935
|
+
throw new AutomaticCompletionAuthorizationError(authorization);
|
|
1936
|
+
submitted = true;
|
|
1937
|
+
return await this.followupTurn(agent, message, onClaimed, () => {
|
|
1938
|
+
exactTurnSettled = true;
|
|
1939
|
+
releaseToolBarriers();
|
|
1940
|
+
}, undefined, signal);
|
|
1941
|
+
}
|
|
1942
|
+
catch (error) {
|
|
1943
|
+
if (signal.aborted)
|
|
1944
|
+
signal.throwIfAborted();
|
|
1945
|
+
if (submitted || error instanceof AutomaticCompletionAuthorizationError
|
|
1946
|
+
|| error instanceof AutomaticCompletionUnavailableError)
|
|
1947
|
+
throw error;
|
|
1948
|
+
throw new AutomaticCompletionUnavailableError('assistant-delivery: automatic completion safety guard was unavailable', { cause: error });
|
|
1949
|
+
}
|
|
1950
|
+
finally {
|
|
1951
|
+
// A submitted message may already be pending or running even when followup() throws.
|
|
1952
|
+
// Keep the barriers attached to the Agent scope until exact settlement or handle teardown.
|
|
1953
|
+
if (!submitted || exactTurnSettled)
|
|
1954
|
+
releaseToolBarriers();
|
|
1955
|
+
}
|
|
1956
|
+
}
|
|
1957
|
+
async setupAgent(agentCtx, preparedAgent, workspace, presetId, principal, selected, agentPresets, initiator = 'external') {
|
|
1958
|
+
const agent = preparedAgent;
|
|
1959
|
+
if (agent === undefined)
|
|
1960
|
+
throw new Error('assistant-delivery: unpublished Agent identity is missing');
|
|
1961
|
+
if (agent.session.header.cwd !== workspace || agent.session.header.agentPreset !== presetId) {
|
|
1962
|
+
throw new DurableAgentIdentityError('assistant-delivery: durable Agent identity does not match its conversation binding');
|
|
1963
|
+
}
|
|
1964
|
+
const unbind = this.policy.bindInitiator(agent, initiator, principal);
|
|
1965
|
+
agentCtx.effect(() => unbind, `assistant-delivery.${initiator}-initiator`);
|
|
1966
|
+
installModelSelection(agentCtx);
|
|
1967
|
+
agent.model.select(selected);
|
|
1968
|
+
// The trusted post-cancellation clarification is installed LAZILY and only
|
|
1969
|
+
// for a session whose history actually contains a human-aborted turn with an
|
|
1970
|
+
// aborted-before-dispatch tool result. Merely registering a runtime context
|
|
1971
|
+
// flips the system-prompt assembly out of its empty baseline and perturbs the
|
|
1972
|
+
// cold-resume/lease-recovery accounting for EVERY ordinary session (a
|
|
1973
|
+
// permission /stop compensation run has no such tool result, yet regressed
|
|
1974
|
+
// when the context was registered unconditionally). Keep the exact baseline —
|
|
1975
|
+
// no contribution installed at all — until the Host-owned predicate matches.
|
|
1976
|
+
let cancelNoticeInstalled = false;
|
|
1977
|
+
const installUserCancelledToolNotice = () => {
|
|
1978
|
+
if (cancelNoticeInstalled)
|
|
1979
|
+
return;
|
|
1980
|
+
if (!userCancelledToolNotice(agent.session.snapshotEvents()))
|
|
1981
|
+
return;
|
|
1982
|
+
cancelNoticeInstalled = true;
|
|
1983
|
+
agentCtx.inject(['systemPrompt'], promptCtx => promptCtx.systemPrompt.context({
|
|
1984
|
+
name: 'assistant-delivery:user-cancelled-tool-notice',
|
|
1985
|
+
order: 260,
|
|
1986
|
+
text: () => userCancelledToolNotice(agent.session.snapshotEvents()),
|
|
1987
|
+
}));
|
|
1988
|
+
};
|
|
1989
|
+
// A cold resume may already carry the abort (the real Feishu sequence did).
|
|
1990
|
+
installUserCancelledToolNotice();
|
|
1991
|
+
// A live abort only becomes visible once its turn/end + tool/result land.
|
|
1992
|
+
agentCtx.on('session/event', (eventSession, event) => {
|
|
1993
|
+
if (eventSession !== agent.session)
|
|
1994
|
+
return;
|
|
1995
|
+
if (event.type === 'turn/end' || event.type === 'tool/result')
|
|
1996
|
+
installUserCancelledToolNotice();
|
|
1997
|
+
});
|
|
1998
|
+
// A context registration changes native cold-resume accounting even if its
|
|
1999
|
+
// text is empty. Install only after a real proposal is visible (or a read
|
|
2000
|
+
// failed), then re-read on every prompt assembly. Live proposal creation
|
|
2001
|
+
// becomes visible after the tool result/turn settles.
|
|
2002
|
+
let approvalStatusInstalled = false;
|
|
2003
|
+
const currentApprovalStatus = () => {
|
|
2004
|
+
try {
|
|
2005
|
+
return this.options.readOwnerApprovalStatus(agent);
|
|
2006
|
+
}
|
|
2007
|
+
catch {
|
|
2008
|
+
return 'unavailable';
|
|
2009
|
+
}
|
|
2010
|
+
};
|
|
2011
|
+
const installApprovalStatus = () => {
|
|
2012
|
+
if (approvalStatusInstalled)
|
|
2013
|
+
return;
|
|
2014
|
+
const status = currentApprovalStatus();
|
|
2015
|
+
if (status === undefined || (status !== 'unavailable'
|
|
2016
|
+
&& status.memory.proposals.length === 0 && status.wiki.proposals.length === 0))
|
|
2017
|
+
return;
|
|
2018
|
+
approvalStatusInstalled = true;
|
|
2019
|
+
agentCtx.inject(['systemPrompt'], promptCtx => promptCtx.systemPrompt.context({
|
|
2020
|
+
name: 'assistant-delivery:owner-approval-status',
|
|
2021
|
+
order: 261,
|
|
2022
|
+
text: () => {
|
|
2023
|
+
const current = currentApprovalStatus();
|
|
2024
|
+
return current === undefined ? '' : renderOwnerApprovalStatus(current);
|
|
2025
|
+
},
|
|
2026
|
+
}));
|
|
2027
|
+
};
|
|
2028
|
+
installApprovalStatus();
|
|
2029
|
+
agentCtx.on('session/event', (eventSession, event) => {
|
|
2030
|
+
if (eventSession === agent.session && (event.type === 'tool/result' || event.type === 'turn/end'
|
|
2031
|
+
|| event.type === 'user/message'))
|
|
2032
|
+
installApprovalStatus();
|
|
2033
|
+
});
|
|
2034
|
+
await agentPresets?.mount(agentCtx, presetId);
|
|
2035
|
+
}
|
|
2036
|
+
/**
|
|
2037
|
+
* DSH validates an explicit reasoning effort before calling an adapter. That is normally the
|
|
2038
|
+
* right contract, but a persisted external-channel selection can outlive a provider's live
|
|
2039
|
+
* model directory. Clear only that stale persisted effort before a prompt crosses the durable
|
|
2040
|
+
* dispatch boundary; TraeX still rechecks the newly created ACP session afterwards.
|
|
2041
|
+
*/
|
|
2042
|
+
async resolveExecutionRoute(conversation, persisted, route, signal) {
|
|
2043
|
+
if (route.reasoningEffort === undefined)
|
|
2044
|
+
return { route };
|
|
2045
|
+
const llm = this.ctx.get('llm');
|
|
2046
|
+
if (llm === undefined)
|
|
2047
|
+
throw new Error('assistant-delivery: llm service is required');
|
|
2048
|
+
const requestConfig = {
|
|
2049
|
+
provider: route.provider,
|
|
2050
|
+
model: route.model,
|
|
2051
|
+
reasoningEffort: ReasoningEffortId(route.reasoningEffort),
|
|
2052
|
+
};
|
|
2053
|
+
try {
|
|
2054
|
+
await llm.resolveCallConfig(requestConfig, signal);
|
|
2055
|
+
return { route };
|
|
2056
|
+
}
|
|
2057
|
+
catch (error) {
|
|
2058
|
+
if (signal.aborted || !errorHasCode(error, 'UNSUPPORTED_REASONING_EFFORT'))
|
|
2059
|
+
throw error;
|
|
2060
|
+
// Dynamic-catalog adapters (such as local ACP providers) keep resolveModel process-free
|
|
2061
|
+
// and populate per-model reasoning metadata via prompt-free listModels(). Warm the
|
|
2062
|
+
// provider catalog once before treating a persisted effort as genuinely stale.
|
|
2063
|
+
let warmed = false;
|
|
2064
|
+
try {
|
|
2065
|
+
await waitWithAbort(llm.listModels(route.provider), signal);
|
|
2066
|
+
warmed = true;
|
|
2067
|
+
}
|
|
2068
|
+
catch (listError) {
|
|
2069
|
+
if (signal.aborted)
|
|
2070
|
+
throw listError;
|
|
2071
|
+
}
|
|
2072
|
+
if (warmed) {
|
|
2073
|
+
try {
|
|
2074
|
+
await llm.resolveCallConfig(requestConfig, signal);
|
|
2075
|
+
return { route };
|
|
2076
|
+
}
|
|
2077
|
+
catch (retryError) {
|
|
2078
|
+
if (signal.aborted || !errorHasCode(retryError, 'UNSUPPORTED_REASONING_EFFORT'))
|
|
2079
|
+
throw retryError;
|
|
2080
|
+
}
|
|
2081
|
+
}
|
|
2082
|
+
const fallback = { provider: route.provider, model: route.model };
|
|
2083
|
+
// Do not turn an invalid model/default into a silent recovery. This is the same core
|
|
2084
|
+
// preflight without the stale explicit effort, still before an Agent turn is dispatched.
|
|
2085
|
+
await llm.resolveCallConfig(fallback, signal);
|
|
2086
|
+
if (persisted === undefined) {
|
|
2087
|
+
this.ctx.logger.warn(`assistant-delivery: using provider default after unsupported reasoning effort for ${route.provider}/${route.model}`);
|
|
2088
|
+
return { route: fallback };
|
|
2089
|
+
}
|
|
2090
|
+
const recovered = this.options.clearStaleModelReasoningEffort(conversation, persisted);
|
|
2091
|
+
if (!recovered.applied)
|
|
2092
|
+
return { retry: true };
|
|
2093
|
+
this.ctx.logger.warn(`assistant-delivery: cleared stale reasoning effort for ${route.provider}/${route.model} before dispatch`);
|
|
2094
|
+
return { route: toModelRoute(recovered.selection) };
|
|
2095
|
+
}
|
|
2096
|
+
}
|
|
2097
|
+
async reconcileNativeFullPermissionReviewer(session) {
|
|
2098
|
+
this.sessionLeases.assert(String(session.id));
|
|
2099
|
+
const result = await this.policy.reconcileNativeFullReviewer(session);
|
|
2100
|
+
this.sessionLeases.assert(String(session.id));
|
|
2101
|
+
if (result === 'unavailable') {
|
|
2102
|
+
throw new ApprovalReviewerReaderUnavailableError(new Error('assistant-policy: native full reviewer reconciliation is unavailable'));
|
|
2103
|
+
}
|
|
2104
|
+
}
|
|
2105
|
+
async runPermissionCommand(argument, binding, envelope, signal, markDispatching, recovery) {
|
|
2106
|
+
let dispatchMarked = false;
|
|
2107
|
+
const markPermissionDispatch = () => {
|
|
2108
|
+
signal.throwIfAborted();
|
|
2109
|
+
if (dispatchMarked)
|
|
2110
|
+
return;
|
|
2111
|
+
markDispatching();
|
|
2112
|
+
dispatchMarked = true;
|
|
2113
|
+
};
|
|
2114
|
+
const checkController = () => {
|
|
2115
|
+
try {
|
|
2116
|
+
return this.options.isPermissionController(binding, envelope) ? 'authorized' : 'revoked';
|
|
2117
|
+
}
|
|
2118
|
+
catch {
|
|
2119
|
+
return 'check-failed';
|
|
2120
|
+
}
|
|
2121
|
+
};
|
|
2122
|
+
const checkEmergencyStopVersion = (expected) => {
|
|
2123
|
+
if (expected === undefined)
|
|
2124
|
+
return 'authorized';
|
|
2125
|
+
try {
|
|
2126
|
+
const emergencyStop = this.policy.getEmergencyStop();
|
|
2127
|
+
return !emergencyStop.enabled && emergencyStop.version === expected ? 'authorized' : 'revoked';
|
|
2128
|
+
}
|
|
2129
|
+
catch {
|
|
2130
|
+
return 'check-failed';
|
|
2131
|
+
}
|
|
2132
|
+
};
|
|
2133
|
+
const authorizationFailure = (state, committed = false) => state === 'revoked'
|
|
2134
|
+
? { outcome: 'not-processed', failureCode: 'permission-authorization-revoked', retryable: false }
|
|
2135
|
+
: { outcome: 'not-processed', failureCode: 'permission-authorization-check-failed', retryable: !committed };
|
|
2136
|
+
const reply = (input, committed = false) => {
|
|
2137
|
+
const authorization = checkController();
|
|
2138
|
+
if (authorization !== 'authorized')
|
|
2139
|
+
return authorizationFailure(authorization, committed);
|
|
2140
|
+
markPermissionDispatch();
|
|
2141
|
+
signal.throwIfAborted();
|
|
2142
|
+
try {
|
|
2143
|
+
this.options.replyCommand(binding, envelope.eventId, input);
|
|
2144
|
+
return { outcome: 'processed' };
|
|
2145
|
+
}
|
|
2146
|
+
catch {
|
|
2147
|
+
if (input.format === 'permission-picker' && input.fallbackText !== undefined) {
|
|
2148
|
+
try {
|
|
2149
|
+
this.options.replyCommand(binding, envelope.eventId, { text: input.fallbackText, format: 'plain' });
|
|
2150
|
+
return { outcome: 'processed' };
|
|
2151
|
+
}
|
|
2152
|
+
catch { }
|
|
2153
|
+
}
|
|
2154
|
+
return { outcome: 'not-processed', failureCode: 'permission-command-reply-failed', retryable: !committed };
|
|
2155
|
+
}
|
|
2156
|
+
};
|
|
2157
|
+
const retryPermissionRecovery = (mode = recovery ?? 'failure-notice') => ({
|
|
2158
|
+
outcome: 'not-processed',
|
|
2159
|
+
failureCode: permissionDispatchRecoveryCode(mode),
|
|
2160
|
+
retryable: true,
|
|
2161
|
+
});
|
|
2162
|
+
const preservePermissionRecovery = (result, mode) => result.outcome === 'processed' ? result : retryPermissionRecovery(mode);
|
|
2163
|
+
const authorizeTerminalReply = () => {
|
|
2164
|
+
try {
|
|
2165
|
+
return this.options.authorizePermissionReply(binding, envelope);
|
|
2166
|
+
}
|
|
2167
|
+
catch {
|
|
2168
|
+
return false;
|
|
2169
|
+
}
|
|
2170
|
+
};
|
|
2171
|
+
const action = parsePermissionCommand(argument);
|
|
2172
|
+
if (recovery === undefined) {
|
|
2173
|
+
const initialAuthorization = checkController();
|
|
2174
|
+
if (initialAuthorization !== 'authorized')
|
|
2175
|
+
return authorizationFailure(initialAuthorization);
|
|
2176
|
+
if (!authorizeTerminalReply()) {
|
|
2177
|
+
return {
|
|
2178
|
+
outcome: 'not-processed',
|
|
2179
|
+
failureCode: 'permission-reply-authorization-denied',
|
|
2180
|
+
retryable: false,
|
|
2181
|
+
};
|
|
2182
|
+
}
|
|
2183
|
+
}
|
|
2184
|
+
if (recovery === undefined && action.kind === 'invalid')
|
|
2185
|
+
return reply(PERMISSION_USAGE);
|
|
2186
|
+
if (recovery === undefined && action.kind === 'warn-full')
|
|
2187
|
+
return reply(PERMISSION_FULL_WARNING);
|
|
2188
|
+
const parsedPickerGuard = permissionPickerGuard(envelope);
|
|
2189
|
+
if (parsedPickerGuard === 'invalid' && recovery === undefined) {
|
|
2190
|
+
return reply({ text: '权限卡片来源无效;当前权限未改变。请重新发送 /permissions。', format: 'plain' });
|
|
2191
|
+
}
|
|
2192
|
+
const pickerGuard = parsedPickerGuard === 'invalid' ? undefined : parsedPickerGuard;
|
|
2193
|
+
if (pickerGuard !== undefined && Date.now() >= pickerGuard.expiresAt && recovery === undefined) {
|
|
2194
|
+
return reply({ text: '权限卡片已过期;当前权限未改变。请重新发送 /permissions。', format: 'plain' });
|
|
2195
|
+
}
|
|
2196
|
+
const agents = this.ctx.get('agents');
|
|
2197
|
+
const sessions = this.ctx.get('sessions');
|
|
2198
|
+
const permissionPresets = this.ctx.get('permissionPresets');
|
|
2199
|
+
const approval = this.ctx.get('approval');
|
|
2200
|
+
if (agents === undefined || sessions === undefined || permissionPresets === undefined || approval === undefined) {
|
|
2201
|
+
if (recovery !== undefined)
|
|
2202
|
+
return retryPermissionRecovery(recovery);
|
|
2203
|
+
return reply({ text: '权限服务不可用,当前权限未改变。', format: 'plain' });
|
|
2204
|
+
}
|
|
2205
|
+
let partialTargets;
|
|
2206
|
+
try {
|
|
2207
|
+
partialTargets = permissionPresetTargets(permissionPresets);
|
|
2208
|
+
}
|
|
2209
|
+
catch {
|
|
2210
|
+
if (recovery !== undefined)
|
|
2211
|
+
return retryPermissionRecovery(recovery);
|
|
2212
|
+
return reply({ text: '权限服务不可用,无法安全解析权限组合;当前权限未改变。', format: 'plain' });
|
|
2213
|
+
}
|
|
2214
|
+
if (recovery === undefined) {
|
|
2215
|
+
const afterResolutionAuthorization = checkController();
|
|
2216
|
+
if (afterResolutionAuthorization !== 'authorized')
|
|
2217
|
+
return authorizationFailure(afterResolutionAuthorization);
|
|
2218
|
+
}
|
|
2219
|
+
const missingBundle = missingPermissionBundle(partialTargets);
|
|
2220
|
+
if (missingBundle !== undefined) {
|
|
2221
|
+
if (recovery !== undefined)
|
|
2222
|
+
return retryPermissionRecovery(recovery);
|
|
2223
|
+
return reply({ text: `权限配置缺少 ${missingBundle} 组合,已拒绝切换。`, format: 'plain' });
|
|
2224
|
+
}
|
|
2225
|
+
const targets = partialTargets;
|
|
2226
|
+
const selected = agentSelection(toModelRoute(this.options.getModelSelection(envelope.conversation)
|
|
2227
|
+
?? { provider: this.options.provider, model: this.options.model }));
|
|
2228
|
+
let handle;
|
|
2229
|
+
let mutationAttempted = false;
|
|
2230
|
+
let compensateToAsk;
|
|
2231
|
+
try {
|
|
2232
|
+
const agentPresets = this.options.getAgentPresets();
|
|
2233
|
+
const presetId = agentPresets === undefined
|
|
2234
|
+
? binding.agentPreset
|
|
2235
|
+
: (await agentPresets.resolve(binding.agentPreset)).id;
|
|
2236
|
+
signal.throwIfAborted();
|
|
2237
|
+
await requireWorkspace(binding.workspace);
|
|
2238
|
+
signal.throwIfAborted();
|
|
2239
|
+
handle = await this.resumeAgent({
|
|
2240
|
+
resumeSessionId: SessionId(binding.sessionId),
|
|
2241
|
+
signal,
|
|
2242
|
+
agentOptions: {
|
|
2243
|
+
provider: selected.provider,
|
|
2244
|
+
model: selected.model,
|
|
2245
|
+
maxTokens: this.options.maxOutputTokens,
|
|
2246
|
+
},
|
|
2247
|
+
setup: async (agentCtx, preparedAgent) => {
|
|
2248
|
+
await this.setupAgent(agentCtx, preparedAgent, binding.workspace, presetId, externalPrincipalId(binding.principal), selected, agentPresets);
|
|
2249
|
+
},
|
|
2250
|
+
});
|
|
2251
|
+
signal.throwIfAborted();
|
|
2252
|
+
if (recovery === undefined) {
|
|
2253
|
+
const afterResumeAuthorization = checkController();
|
|
2254
|
+
if (afterResumeAuthorization !== 'authorized')
|
|
2255
|
+
return authorizationFailure(afterResumeAuthorization);
|
|
2256
|
+
}
|
|
2257
|
+
const agent = handle.agent;
|
|
2258
|
+
const session = agent.session;
|
|
2259
|
+
await this.reconcileNativeFullPermissionReviewer(session);
|
|
2260
|
+
compensateToAsk = async () => {
|
|
2261
|
+
// Try the bundle first for its audit marker, then independently force
|
|
2262
|
+
// both execution knobs through their canonical writers. This remains
|
|
2263
|
+
// fail-closed even when a preset observer throws partway through.
|
|
2264
|
+
// Every operation is best-effort because the original mutation has
|
|
2265
|
+
// already become ambiguous.
|
|
2266
|
+
try {
|
|
2267
|
+
permissionPresets.set(session, targets.ask);
|
|
2268
|
+
}
|
|
2269
|
+
catch { }
|
|
2270
|
+
try {
|
|
2271
|
+
ensureSandboxMode(session, 'workspace-write');
|
|
2272
|
+
}
|
|
2273
|
+
catch { }
|
|
2274
|
+
try {
|
|
2275
|
+
ensureApprovalPolicy(session, 'ask');
|
|
2276
|
+
}
|
|
2277
|
+
catch { }
|
|
2278
|
+
let reviewerReady = true;
|
|
2279
|
+
try {
|
|
2280
|
+
await ensurePermissionReviewer(session, targets.ask, 'user');
|
|
2281
|
+
}
|
|
2282
|
+
catch {
|
|
2283
|
+
reviewerReady = false;
|
|
2284
|
+
}
|
|
2285
|
+
try {
|
|
2286
|
+
const flushed = await sessions.flush(session);
|
|
2287
|
+
return reviewerReady
|
|
2288
|
+
&& flushed
|
|
2289
|
+
&& currentPermissionLevel(permissionPresets, targets, session) === 'ask';
|
|
2290
|
+
}
|
|
2291
|
+
catch {
|
|
2292
|
+
return false;
|
|
2293
|
+
}
|
|
2294
|
+
};
|
|
2295
|
+
const recoveryReply = (input, mode) => {
|
|
2296
|
+
if (!authorizeTerminalReply())
|
|
2297
|
+
return retryPermissionRecovery(mode);
|
|
2298
|
+
return preservePermissionRecovery(reply(input, true), mode);
|
|
2299
|
+
};
|
|
2300
|
+
const reportPermissionFailure = (safeAskPersisted) => {
|
|
2301
|
+
if (!safeAskPersisted)
|
|
2302
|
+
return retryPermissionRecovery('failure-notice');
|
|
2303
|
+
return preservePermissionRecovery(reply({
|
|
2304
|
+
text: '权限切换失败;已安全恢复并持久化为请求批准(ask)。请重新发送 /permissions 核对。',
|
|
2305
|
+
format: 'plain',
|
|
2306
|
+
}, true), 'failure-notice');
|
|
2307
|
+
};
|
|
2308
|
+
const reportCommittedReplyFailure = (safeAskPersisted) => {
|
|
2309
|
+
if (!safeAskPersisted)
|
|
2310
|
+
return retryPermissionRecovery('failure-notice');
|
|
2311
|
+
const authorization = checkController();
|
|
2312
|
+
if (authorization !== 'authorized')
|
|
2313
|
+
return retryPermissionRecovery('failure-notice');
|
|
2314
|
+
signal.throwIfAborted();
|
|
2315
|
+
try {
|
|
2316
|
+
this.options.replyCommand(binding, envelope.eventId, {
|
|
2317
|
+
text: '权限切换的成功回复入队失败;为避免静默保留新权限,已安全恢复并持久化为请求批准(ask)。请重新发送 /permissions 核对。',
|
|
2318
|
+
format: 'plain',
|
|
2319
|
+
}, `inbound:${envelope.eventId}:reply`);
|
|
2320
|
+
return { outcome: 'processed' };
|
|
2321
|
+
}
|
|
2322
|
+
catch {
|
|
2323
|
+
return retryPermissionRecovery('failure-notice');
|
|
2324
|
+
}
|
|
2325
|
+
};
|
|
2326
|
+
if (recovery === 'cancelled' || recovery === 'failure-notice') {
|
|
2327
|
+
mutationAttempted = true;
|
|
2328
|
+
const safeAskPersisted = await compensateToAsk();
|
|
2329
|
+
signal.throwIfAborted();
|
|
2330
|
+
if (!safeAskPersisted)
|
|
2331
|
+
return retryPermissionRecovery(recovery);
|
|
2332
|
+
return recoveryReply({
|
|
2333
|
+
text: recovery === 'cancelled'
|
|
2334
|
+
? '权限切换已停止;已安全恢复并持久化为请求批准(ask)。'
|
|
2335
|
+
: '权限切换未完成;已安全恢复并持久化为请求批准(ask)。请重新发送 /permissions 核对。',
|
|
2336
|
+
format: 'plain',
|
|
2337
|
+
}, recovery);
|
|
2338
|
+
}
|
|
2339
|
+
if (recovery === 'commit' && action.kind !== 'switch') {
|
|
2340
|
+
mutationAttempted = true;
|
|
2341
|
+
const safeAskPersisted = await compensateToAsk();
|
|
2342
|
+
signal.throwIfAborted();
|
|
2343
|
+
if (!safeAskPersisted)
|
|
2344
|
+
return retryPermissionRecovery('commit');
|
|
2345
|
+
return recoveryReply({
|
|
2346
|
+
text: '权限恢复记录无效;已安全保持并持久化为请求批准(ask)。请重新选择。',
|
|
2347
|
+
format: 'plain',
|
|
2348
|
+
}, 'commit');
|
|
2349
|
+
}
|
|
2350
|
+
if (action.kind === 'invalid' || action.kind === 'warn-full') {
|
|
2351
|
+
return retryPermissionRecovery(recovery ?? 'failure-notice');
|
|
2352
|
+
}
|
|
2353
|
+
const currentStateHash = permissionStateHash(session.snapshotEvents(), targets.tableFingerprint);
|
|
2354
|
+
const beforeLevel = currentPermissionLevel(permissionPresets, targets, session);
|
|
2355
|
+
const recoveredCommittedTarget = recovery === 'commit'
|
|
2356
|
+
&& action.kind === 'switch'
|
|
2357
|
+
&& beforeLevel === action.level;
|
|
2358
|
+
if (recovery === 'commit' && action.kind === 'switch') {
|
|
2359
|
+
if (recoveredCommittedTarget) {
|
|
2360
|
+
if (!authorizeTerminalReply()) {
|
|
2361
|
+
mutationAttempted = true;
|
|
2362
|
+
await compensateToAsk();
|
|
2363
|
+
signal.throwIfAborted();
|
|
2364
|
+
return retryPermissionRecovery('commit');
|
|
2365
|
+
}
|
|
2366
|
+
const recoveredReply = reply({
|
|
2367
|
+
text: `已恢复确认:当前为 ${permissionLevelLabel(beforeLevel)}。`,
|
|
2368
|
+
format: 'plain',
|
|
2369
|
+
}, true);
|
|
2370
|
+
if (recoveredReply.outcome === 'processed')
|
|
2371
|
+
return recoveredReply;
|
|
2372
|
+
mutationAttempted = true;
|
|
2373
|
+
await compensateToAsk();
|
|
2374
|
+
signal.throwIfAborted();
|
|
2375
|
+
return retryPermissionRecovery('commit');
|
|
2376
|
+
}
|
|
2377
|
+
// The dispatch fence may have been written before the first permission
|
|
2378
|
+
// event. Only an already-durable target proves that replay is a
|
|
2379
|
+
// terminal reconciliation. Otherwise converge to ask; never recreate
|
|
2380
|
+
// a possibly cancelled elevation from the original command text. This
|
|
2381
|
+
// recovery decision deliberately precedes picker TTL/state checks:
|
|
2382
|
+
// stale callback metadata must not strand a partial permission state.
|
|
2383
|
+
mutationAttempted = true;
|
|
2384
|
+
const safeAskPersisted = await compensateToAsk();
|
|
2385
|
+
signal.throwIfAborted();
|
|
2386
|
+
if (!safeAskPersisted)
|
|
2387
|
+
return retryPermissionRecovery('commit');
|
|
2388
|
+
return recoveryReply({
|
|
2389
|
+
text: '权限切换在确认持久化前中断;已安全保持并持久化为请求批准(ask)。请重新选择。',
|
|
2390
|
+
format: 'plain',
|
|
2391
|
+
}, 'commit');
|
|
2392
|
+
}
|
|
2393
|
+
if (pickerGuard !== undefined && !recoveredCommittedTarget
|
|
2394
|
+
&& currentStateHash !== pickerGuard.expectedStateHash) {
|
|
2395
|
+
return reply({ text: '权限卡片已过期或状态已变化;当前权限未改变。请重新发送 /permissions。', format: 'plain' });
|
|
2396
|
+
}
|
|
2397
|
+
if (action.kind === 'show') {
|
|
2398
|
+
const level = currentPermissionLevel(permissionPresets, targets, session);
|
|
2399
|
+
const emergencyStop = this.policy.getEmergencyStop();
|
|
2400
|
+
if (emergencyStop.enabled)
|
|
2401
|
+
return authorizationFailure('revoked');
|
|
2402
|
+
const issuedAt = Date.now();
|
|
2403
|
+
const picker = envelope.conversation.kind !== 'dm'
|
|
2404
|
+
? undefined
|
|
2405
|
+
: {
|
|
2406
|
+
operationId: permissionPickerOperationId(envelope.conversation, envelope.eventId),
|
|
2407
|
+
issuedAt,
|
|
2408
|
+
expiresAt: issuedAt + this.options.permissionPickerTtlMs,
|
|
2409
|
+
current: level,
|
|
2410
|
+
expectedStateHash: permissionStateHash(session.snapshotEvents(), targets.tableFingerprint),
|
|
2411
|
+
emergencyStopVersion: emergencyStop.version,
|
|
2412
|
+
bindingVersion: binding.version,
|
|
2413
|
+
sessionId: binding.sessionId,
|
|
2414
|
+
};
|
|
2415
|
+
return reply(permissionOverview(level, picker));
|
|
2416
|
+
}
|
|
2417
|
+
if (pickerGuard !== undefined && !recoveredCommittedTarget && Date.now() >= pickerGuard.expiresAt) {
|
|
2418
|
+
return reply({ text: '权限卡片已过期;当前权限未改变。请重新发送 /permissions。', format: 'plain' });
|
|
2419
|
+
}
|
|
2420
|
+
const beforeMutationAuthorization = checkController();
|
|
2421
|
+
if (beforeMutationAuthorization !== 'authorized')
|
|
2422
|
+
return authorizationFailure(beforeMutationAuthorization);
|
|
2423
|
+
markPermissionDispatch();
|
|
2424
|
+
signal.throwIfAborted();
|
|
2425
|
+
const fencedAuthorization = checkController();
|
|
2426
|
+
if (fencedAuthorization !== 'authorized')
|
|
2427
|
+
return authorizationFailure(fencedAuthorization);
|
|
2428
|
+
const emergencyFence = checkEmergencyStopVersion(pickerGuard?.emergencyStopVersion);
|
|
2429
|
+
if (emergencyFence !== 'authorized')
|
|
2430
|
+
return authorizationFailure(emergencyFence);
|
|
2431
|
+
// A callback can enter the durable Inbox just before its deadline and
|
|
2432
|
+
// then wait on workspace/preset/session I/O. Recheck at the final fence,
|
|
2433
|
+
// immediately before any permission event is appended.
|
|
2434
|
+
if (pickerGuard !== undefined && Date.now() >= pickerGuard.expiresAt) {
|
|
2435
|
+
return reply({ text: '权限卡片已过期;当前权限未改变。请重新发送 /permissions。', format: 'plain' });
|
|
2436
|
+
}
|
|
2437
|
+
mutationAttempted = true;
|
|
2438
|
+
if (action.level === 'full') {
|
|
2439
|
+
// Close approval before widening the sandbox. Canonical full derives
|
|
2440
|
+
// reviewer=none from its official preset; legacy dynamic bundles add
|
|
2441
|
+
// their compatibility reviewer only after both execution knobs match.
|
|
2442
|
+
ensureApprovalPolicy(session, 'never');
|
|
2443
|
+
permissionPresets.set(session, targets.full);
|
|
2444
|
+
// Preset setters intentionally omit overrides that equal deployment
|
|
2445
|
+
// defaults. Persist the exact execution facts anyway so full access
|
|
2446
|
+
// cannot depend on an implicit default or a future default change.
|
|
2447
|
+
ensureSandboxMode(session, 'danger-full-access');
|
|
2448
|
+
await ensurePermissionReviewer(session, targets.full, 'none');
|
|
2449
|
+
}
|
|
2450
|
+
else {
|
|
2451
|
+
// Confinement comes first when leaving full access. The preset setter
|
|
2452
|
+
// writes sandbox before approval; only then may the reviewer be enabled.
|
|
2453
|
+
const target = action.level === 'auto' ? targets.auto : targets.ask;
|
|
2454
|
+
permissionPresets.set(session, target);
|
|
2455
|
+
// Legacy/seeded sessions may have no explicit knob events even when
|
|
2456
|
+
// their effective defaults match this preset. Materialize both facts
|
|
2457
|
+
// before changing the project reviewer inside the workspace sandbox.
|
|
2458
|
+
ensureSandboxMode(session, permissionPresets.resolve(target).sandbox);
|
|
2459
|
+
ensureApprovalPolicy(session, 'ask');
|
|
2460
|
+
const reviewer = action.level === 'auto' ? 'auto-review' : 'user';
|
|
2461
|
+
await ensurePermissionReviewer(session, target, reviewer);
|
|
2462
|
+
}
|
|
2463
|
+
const afterReviewerEmergencyFence = checkEmergencyStopVersion(pickerGuard?.emergencyStopVersion);
|
|
2464
|
+
if (afterReviewerEmergencyFence !== 'authorized') {
|
|
2465
|
+
await compensateToAsk();
|
|
2466
|
+
signal.throwIfAborted();
|
|
2467
|
+
return retryPermissionRecovery('failure-notice');
|
|
2468
|
+
}
|
|
2469
|
+
const flushed = await sessions.flush(session);
|
|
2470
|
+
signal.throwIfAborted();
|
|
2471
|
+
if (!flushed) {
|
|
2472
|
+
const safeAskPersisted = await compensateToAsk();
|
|
2473
|
+
signal.throwIfAborted();
|
|
2474
|
+
return reportPermissionFailure(safeAskPersisted);
|
|
2475
|
+
}
|
|
2476
|
+
const finalAuthorization = checkController();
|
|
2477
|
+
const finalEmergencyFence = checkEmergencyStopVersion(pickerGuard?.emergencyStopVersion);
|
|
2478
|
+
if (finalAuthorization !== 'authorized' || finalEmergencyFence !== 'authorized') {
|
|
2479
|
+
await compensateToAsk();
|
|
2480
|
+
signal.throwIfAborted();
|
|
2481
|
+
return retryPermissionRecovery('failure-notice');
|
|
2482
|
+
}
|
|
2483
|
+
const afterLevel = currentPermissionLevel(permissionPresets, targets, session);
|
|
2484
|
+
if (afterLevel !== action.level) {
|
|
2485
|
+
const safeAskPersisted = await compensateToAsk();
|
|
2486
|
+
signal.throwIfAborted();
|
|
2487
|
+
return reportPermissionFailure(safeAskPersisted);
|
|
2488
|
+
}
|
|
2489
|
+
const successReply = reply({
|
|
2490
|
+
text: beforeLevel === afterLevel
|
|
2491
|
+
? `当前已是 ${permissionLevelLabel(afterLevel)}。`
|
|
2492
|
+
: `已切换到 ${permissionLevelLabel(afterLevel)}。`,
|
|
2493
|
+
format: 'plain',
|
|
2494
|
+
}, true);
|
|
2495
|
+
if (successReply.outcome === 'processed')
|
|
2496
|
+
return successReply;
|
|
2497
|
+
const safeAskPersisted = await compensateToAsk();
|
|
2498
|
+
signal.throwIfAborted();
|
|
2499
|
+
return reportCommittedReplyFailure(safeAskPersisted);
|
|
2500
|
+
}
|
|
2501
|
+
catch (error) {
|
|
2502
|
+
if (recovery !== undefined) {
|
|
2503
|
+
if (mutationAttempted)
|
|
2504
|
+
await compensateToAsk?.();
|
|
2505
|
+
return retryPermissionRecovery(recovery);
|
|
2506
|
+
}
|
|
2507
|
+
if (mutationAttempted) {
|
|
2508
|
+
const safeAskPersisted = await compensateToAsk?.() ?? false;
|
|
2509
|
+
if (signal.aborted || causedByUserCancellation(error)) {
|
|
2510
|
+
return {
|
|
2511
|
+
outcome: 'not-processed',
|
|
2512
|
+
failureCode: permissionDispatchRecoveryCode('cancelled'),
|
|
2513
|
+
retryable: true,
|
|
2514
|
+
};
|
|
2515
|
+
}
|
|
2516
|
+
if (errorChainHasName(error, 'ApprovalReviewerReaderUnavailableError')) {
|
|
2517
|
+
return retryPermissionRecovery('failure-notice');
|
|
2518
|
+
}
|
|
2519
|
+
if (!safeAskPersisted)
|
|
2520
|
+
return retryPermissionRecovery('failure-notice');
|
|
2521
|
+
return preservePermissionRecovery(reply({
|
|
2522
|
+
text: '权限切换失败;已安全恢复并持久化为请求批准(ask)。请重新发送 /permissions 核对。',
|
|
2523
|
+
format: 'plain',
|
|
2524
|
+
}, true), 'failure-notice');
|
|
2525
|
+
}
|
|
2526
|
+
if (signal.aborted)
|
|
2527
|
+
throw error;
|
|
2528
|
+
if (errorChainHasName(error, 'ApprovalReviewerReaderUnavailableError')) {
|
|
2529
|
+
return {
|
|
2530
|
+
outcome: 'not-processed',
|
|
2531
|
+
failureCode: 'permission-reviewer-reader-unavailable',
|
|
2532
|
+
retryable: true,
|
|
2533
|
+
};
|
|
2534
|
+
}
|
|
2535
|
+
const finalAuthorization = checkController();
|
|
2536
|
+
if (finalAuthorization !== 'authorized')
|
|
2537
|
+
return authorizationFailure(finalAuthorization);
|
|
2538
|
+
if (causedByDurableIdentity(error)) {
|
|
2539
|
+
return { outcome: 'not-processed', failureCode: 'permission-session-mismatch', retryable: false };
|
|
2540
|
+
}
|
|
2541
|
+
return reply({
|
|
2542
|
+
text: '权限命令未完成;当前权限保持或收紧,未确认任何权限提升。',
|
|
2543
|
+
format: 'plain',
|
|
2544
|
+
});
|
|
2545
|
+
}
|
|
2546
|
+
finally {
|
|
2547
|
+
await this.disposeAfterReplyBoundary(binding.sessionId, handle);
|
|
2548
|
+
}
|
|
2549
|
+
}
|
|
2550
|
+
async createSession(input) {
|
|
2551
|
+
const agents = this.ctx.get('agents');
|
|
2552
|
+
const sessions = this.ctx.get('sessions');
|
|
2553
|
+
if (agents === undefined || sessions === undefined)
|
|
2554
|
+
throw new Error('assistant-delivery: agents and sessions services are required');
|
|
2555
|
+
const id = sessionId(this.options.sessionNamespace, input.envelope.conversation, input.generation);
|
|
2556
|
+
const workspace = input.previous?.workspace ?? this.options.workspace;
|
|
2557
|
+
const requestedPreset = input.previous?.agentPreset ?? this.options.agentPreset;
|
|
2558
|
+
const agentPresets = this.options.getAgentPresets();
|
|
2559
|
+
const presetId = agentPresets === undefined
|
|
2560
|
+
? requestedPreset
|
|
2561
|
+
: (await agentPresets.resolve(requestedPreset)).id;
|
|
2562
|
+
await ensureWorkspace(workspace);
|
|
2563
|
+
const selected = agentSelection(toModelRoute(this.options.getModelSelection(input.envelope.conversation)
|
|
2564
|
+
?? { provider: this.options.provider, model: this.options.model }));
|
|
2565
|
+
const setup = async (agentCtx, preparedAgent) => {
|
|
2566
|
+
await this.setupAgent(agentCtx, preparedAgent, workspace, presetId, externalPrincipalId(input.envelope.principal), selected, agentPresets);
|
|
2567
|
+
};
|
|
2568
|
+
const lease = this.sessionLeases.open({ kind: 'construction', sessionId: String(id),
|
|
2569
|
+
conversation: input.envelope.conversation, principal: input.envelope.principal,
|
|
2570
|
+
workspace, agentPreset: presetId, generation: input.generation,
|
|
2571
|
+
...(input.previous === undefined ? {} : { previous: input.previous }) }, input.signal);
|
|
2572
|
+
let handle;
|
|
2573
|
+
let adopted = false;
|
|
2574
|
+
try {
|
|
2575
|
+
lease.dispatch();
|
|
2576
|
+
const agentOptions = {
|
|
2577
|
+
provider: selected.provider,
|
|
2578
|
+
model: selected.model,
|
|
2579
|
+
maxTokens: this.options.maxOutputTokens,
|
|
2580
|
+
};
|
|
2581
|
+
const persistence = this.ctx.get('sessionPersistence');
|
|
2582
|
+
const persisted = persistence === undefined
|
|
2583
|
+
? false
|
|
2584
|
+
: (await persistence.list({ signal: lease.signal })).some(snapshot => String(snapshot.header.id) === String(id));
|
|
2585
|
+
if (persisted) {
|
|
2586
|
+
handle = await this.resumeAgent({
|
|
2587
|
+
resumeSessionId: id,
|
|
2588
|
+
agentOptions,
|
|
2589
|
+
signal: lease.signal,
|
|
2590
|
+
setup,
|
|
2591
|
+
});
|
|
2592
|
+
adopted = true;
|
|
2593
|
+
}
|
|
2594
|
+
if (handle === undefined) {
|
|
2595
|
+
handle = await this.sessionLeases.create(this.ctx, {
|
|
2596
|
+
sessionId: id,
|
|
2597
|
+
meta: { cwd: workspace, agentPreset: presetId },
|
|
2598
|
+
agentOptions,
|
|
2599
|
+
signal: lease.signal,
|
|
2600
|
+
setup,
|
|
2601
|
+
});
|
|
2602
|
+
}
|
|
2603
|
+
const session = handle.agent.session;
|
|
2604
|
+
if (adopted)
|
|
2605
|
+
assertAdoptableUnstartedSession(session, workspace, presetId);
|
|
2606
|
+
await this.reconcileNativeFullPermissionReviewer(session);
|
|
2607
|
+
if (!await sessions.flush(session)) {
|
|
2608
|
+
throw new Error('assistant-delivery: newly created Agent session was not durable');
|
|
2609
|
+
}
|
|
2610
|
+
return { sessionId: String(id), workspace, agentPreset: presetId,
|
|
2611
|
+
policyRef: input.previous?.policyRef ?? this.options.policyRef };
|
|
2612
|
+
}
|
|
2613
|
+
finally {
|
|
2614
|
+
try {
|
|
2615
|
+
if (handle !== undefined)
|
|
2616
|
+
await handle.dispose();
|
|
2617
|
+
}
|
|
2618
|
+
finally {
|
|
2619
|
+
lease.close();
|
|
2620
|
+
}
|
|
2621
|
+
}
|
|
2622
|
+
}
|
|
2623
|
+
/**
|
|
2624
|
+
* Resume one previously owner-scheduled native Goal. This is deliberately
|
|
2625
|
+
* not an inbound-message path: it creates no delivery source and never
|
|
2626
|
+
* calls followup(). The native round driver remains the only producer of
|
|
2627
|
+
* `source.kind === 'goal'` work.
|
|
2628
|
+
*/
|
|
2629
|
+
async resumeScheduledGoal(binding, input) {
|
|
2630
|
+
const denied = () => ({ outcome: 'denied', dispatched: false, quiescent: false });
|
|
2631
|
+
const now = Date.now();
|
|
2632
|
+
if (!this.validGoalWakeInput(binding, input, now))
|
|
2633
|
+
return denied();
|
|
2634
|
+
const duration = input.deadlineAt - now;
|
|
2635
|
+
const deadline = new AbortController();
|
|
2636
|
+
const expire = setTimeout(() => deadline.abort(new Error('assistant-delivery: scheduled goal wake expired')), duration);
|
|
2637
|
+
expire.unref?.();
|
|
2638
|
+
const abort = () => deadline.abort(input.signal.reason);
|
|
2639
|
+
input.signal.addEventListener('abort', abort, { once: true });
|
|
2640
|
+
if (input.signal.aborted)
|
|
2641
|
+
abort();
|
|
2642
|
+
const signal = deadline.signal;
|
|
2643
|
+
let lease;
|
|
2644
|
+
let control;
|
|
2645
|
+
let handle;
|
|
2646
|
+
let releaseFences;
|
|
2647
|
+
let dispatched = false;
|
|
2648
|
+
let terminal = false;
|
|
2649
|
+
let disposed = false;
|
|
2650
|
+
let goalOutput;
|
|
2651
|
+
try {
|
|
2652
|
+
signal.throwIfAborted();
|
|
2653
|
+
const persisted = this.options.getModelSelection(binding.conversation);
|
|
2654
|
+
const requested = toModelRoute(persisted ?? { provider: this.options.provider, model: this.options.model });
|
|
2655
|
+
const resolved = await this.resolveExecutionRoute(binding.conversation, persisted, requested, signal);
|
|
2656
|
+
if ('retry' in resolved) {
|
|
2657
|
+
return denied();
|
|
2658
|
+
}
|
|
2659
|
+
const selected = agentSelection(resolved.route);
|
|
2660
|
+
const presets = this.options.getAgentPresets();
|
|
2661
|
+
const presetId = presets === undefined ? binding.agentPreset : (await presets.resolve(binding.agentPreset)).id;
|
|
2662
|
+
signal.throwIfAborted();
|
|
2663
|
+
await requireWorkspace(binding.workspace);
|
|
2664
|
+
signal.throwIfAborted();
|
|
2665
|
+
try {
|
|
2666
|
+
lease = this.sessionLeases.open({ kind: 'bound', binding }, signal);
|
|
2667
|
+
}
|
|
2668
|
+
catch (error) {
|
|
2669
|
+
if (error instanceof SessionLeaseUnavailable) {
|
|
2670
|
+
return { outcome: error.kind, dispatched: false, quiescent: false };
|
|
2671
|
+
}
|
|
2672
|
+
throw error;
|
|
2673
|
+
}
|
|
2674
|
+
control = this.beginSessionControl(binding.sessionId, lease.signal);
|
|
2675
|
+
lease.dispatch();
|
|
2676
|
+
handle = await this.resumeAgent({
|
|
2677
|
+
resumeSessionId: SessionId(binding.sessionId),
|
|
2678
|
+
signal: control.controller.signal,
|
|
2679
|
+
agentOptions: { provider: selected.provider, model: selected.model, maxTokens: this.options.maxOutputTokens },
|
|
2680
|
+
setup: async (agentCtx, preparedAgent) => {
|
|
2681
|
+
// Restored inbox entries may wake immediately on Session publication.
|
|
2682
|
+
// Install the background-only gate before that publication boundary.
|
|
2683
|
+
const agent = preparedAgent;
|
|
2684
|
+
if (agent === undefined)
|
|
2685
|
+
throw new Error('assistant-delivery: wake Agent missing');
|
|
2686
|
+
releaseFences = this.installScheduledGoalFences(agent, input);
|
|
2687
|
+
await this.setupAgent(agentCtx, agent, binding.workspace, presetId, input.attestation.principalId, selected, presets, 'background');
|
|
2688
|
+
const llm = this.ctx.get('llm');
|
|
2689
|
+
if (llm === undefined)
|
|
2690
|
+
throw new Error('assistant-delivery: llm service is required');
|
|
2691
|
+
requireAdapterToolCallProtocol(llm, selected.provider, selected.model, presetId, agentCtx.tools.schemas(preparedAgent).length);
|
|
2692
|
+
},
|
|
2693
|
+
});
|
|
2694
|
+
const agent = handle.agent;
|
|
2695
|
+
this.assertScheduledGoal(input, agent, 'before-resume');
|
|
2696
|
+
await this.reconcileNativeFullPermissionReviewer(agent.session);
|
|
2697
|
+
this.assertScheduledGoal(input, agent, 'before-resume');
|
|
2698
|
+
const goals = this.ctx.get('goals');
|
|
2699
|
+
const current = goals?.get(agent);
|
|
2700
|
+
if (goals === undefined || current === undefined || String(current.id) !== input.native.goalId
|
|
2701
|
+
|| current.revision !== input.native.revision || current.phase !== 'paused'
|
|
2702
|
+
|| current.activation !== 'disarmed' || current.roundsStarted >= current.maxGoalRounds) {
|
|
2703
|
+
return denied();
|
|
2704
|
+
}
|
|
2705
|
+
if (agent.status !== 'idle' || (agent.inbox.nextTurn.length > 0 || agent.inbox.nextStep.length > 0)) {
|
|
2706
|
+
return denied();
|
|
2707
|
+
}
|
|
2708
|
+
this.assertScheduledGoal(input, agent, 'before-resume');
|
|
2709
|
+
input.beforeResume(agent);
|
|
2710
|
+
// `beforeResume` is the durable goal-wake CAS. Once it returned, native
|
|
2711
|
+
// resume might have committed before throwing, so this invocation is no
|
|
2712
|
+
// longer retry-safe regardless of the result of `goals.resume()`.
|
|
2713
|
+
dispatched = true;
|
|
2714
|
+
this.assertScheduledGoal(input, agent, 'before-resume');
|
|
2715
|
+
const beforeSequence = agent.session.snapshotEvents().at(-1)?.seq ?? 0;
|
|
2716
|
+
goals.resume(agent, { id: current.id, revision: current.revision });
|
|
2717
|
+
terminal = await this.waitForScheduledGoalTerminal(agent, input, control.controller.signal);
|
|
2718
|
+
if (terminal && input.includeOutput === true) {
|
|
2719
|
+
this.assertScheduledGoal(input, agent, 'terminal');
|
|
2720
|
+
const events = agent.session.snapshotEvents().filter(event => event.seq > beforeSequence);
|
|
2721
|
+
const message = events.findLast(event => event.type === 'user/message'
|
|
2722
|
+
&& event.data.source.kind === 'goal' && String(event.data.source.goalId) === input.native.goalId
|
|
2723
|
+
&& event.data.source.revision === input.native.revision + 1);
|
|
2724
|
+
const start = message === undefined ? undefined : events.findLast(event => event.type === 'turn/start' && event.seq < message.seq);
|
|
2725
|
+
const turn = start?.type === 'turn/start' ? start.data.turn : undefined;
|
|
2726
|
+
const end = events.find(event => event.type === 'turn/end' && event.data.turn === turn);
|
|
2727
|
+
const inputs = start === undefined || end === undefined ? [] : events.filter(event => event.seq > start.seq && event.seq < end.seq
|
|
2728
|
+
&& event.type === 'user/message' && !isScheduledGoalRuntimeContext(event.data.source));
|
|
2729
|
+
const output = finalAssistant(events, 0, inputs.length === 1 && inputs[0]?.seq === message?.seq ? turn : undefined);
|
|
2730
|
+
if (output.completed && !output.truncated && !output.stopped && !output.hasUnpairedToolCall
|
|
2731
|
+
&& output.failureCode === undefined && output.text.trim() !== ''
|
|
2732
|
+
&& Buffer.byteLength(output.text, 'utf8') <= this.options.maxTextBytes)
|
|
2733
|
+
goalOutput = output.text;
|
|
2734
|
+
}
|
|
2735
|
+
}
|
|
2736
|
+
catch (error) {
|
|
2737
|
+
if (!(error instanceof SessionLeaseUnavailable) && !signal.aborted) {
|
|
2738
|
+
this.ctx.logger.warn(`assistant-delivery: scheduled goal wake failed: ${String(error)}`);
|
|
2739
|
+
}
|
|
2740
|
+
terminal = false;
|
|
2741
|
+
try {
|
|
2742
|
+
const agent = handle?.agent;
|
|
2743
|
+
const goals = this.ctx.get('goals');
|
|
2744
|
+
if (agent !== undefined) {
|
|
2745
|
+
try {
|
|
2746
|
+
goals?.disarm(agent);
|
|
2747
|
+
}
|
|
2748
|
+
catch { }
|
|
2749
|
+
agent.cancel({ kind: 'hook', reason: 'assistant-delivery-scheduled-goal-wake-cancelled' });
|
|
2750
|
+
}
|
|
2751
|
+
}
|
|
2752
|
+
catch { }
|
|
2753
|
+
}
|
|
2754
|
+
finally {
|
|
2755
|
+
input.signal.removeEventListener('abort', abort);
|
|
2756
|
+
clearTimeout(expire);
|
|
2757
|
+
try {
|
|
2758
|
+
const remaining = Math.max(0, input.deadlineAt - Date.now());
|
|
2759
|
+
disposed = await this.disposeAfterReplyBoundary(binding.sessionId, handle, releaseFences, !terminal, remaining);
|
|
2760
|
+
}
|
|
2761
|
+
finally {
|
|
2762
|
+
if (handle === undefined)
|
|
2763
|
+
releaseFences?.();
|
|
2764
|
+
if (control !== undefined)
|
|
2765
|
+
this.endSessionControl(binding.sessionId, control);
|
|
2766
|
+
lease?.close();
|
|
2767
|
+
}
|
|
2768
|
+
}
|
|
2769
|
+
const quiescent = terminal && disposed && !signal.aborted;
|
|
2770
|
+
return { outcome: quiescent ? 'succeeded' : 'unknown', dispatched, quiescent,
|
|
2771
|
+
...(quiescent && goalOutput !== undefined ? { output: goalOutput } : {}) };
|
|
2772
|
+
}
|
|
2773
|
+
validGoalWakeInput(binding, input, now) {
|
|
2774
|
+
if (input === null || typeof input !== 'object' || input.signal === undefined
|
|
2775
|
+
|| typeof input.signal.aborted !== 'boolean' || typeof input.signal.addEventListener !== 'function'
|
|
2776
|
+
|| typeof input.signal.removeEventListener !== 'function' || input.signal.aborted
|
|
2777
|
+
|| !isDeliveryGoalWakeDeadline(input.deadlineAt, now) || typeof input.assertCurrent !== 'function'
|
|
2778
|
+
|| typeof input.beforeResume !== 'function' || typeof input.settle !== 'function'
|
|
2779
|
+
|| typeof input.resolveOutcomeFeedbackTarget !== 'function'
|
|
2780
|
+
|| (input.includeOutput !== undefined && typeof input.includeOutput !== 'boolean') || typeof input.native?.goalId !== 'string'
|
|
2781
|
+
|| input.native.goalId.length === 0 || input.native.goalId.length > 512
|
|
2782
|
+
|| !Number.isSafeInteger(input.native.revision) || input.native.revision < 1)
|
|
2783
|
+
return false;
|
|
2784
|
+
const attestation = input.attestation;
|
|
2785
|
+
return attestation !== null && typeof attestation === 'object'
|
|
2786
|
+
&& attestation.bindingId === binding.id && attestation.bindingVersion === binding.version
|
|
2787
|
+
&& attestation.bindingGeneration === binding.generation && attestation.sessionId === binding.sessionId
|
|
2788
|
+
&& attestation.scope?.workspace === binding.workspace && attestation.scope.preset === binding.agentPreset
|
|
2789
|
+
&& attestation.principalId === externalPrincipalId(binding.principal)
|
|
2790
|
+
&& typeof attestation.principalLineage?.principalRecordId === 'string'
|
|
2791
|
+
&& attestation.principalLineage.principalRecordId.length > 0
|
|
2792
|
+
&& Number.isSafeInteger(attestation.principalLineage.principalVersion)
|
|
2793
|
+
&& attestation.principalLineage.principalVersion >= 1;
|
|
2794
|
+
}
|
|
2795
|
+
assertScheduledGoal(input, agent, phase) {
|
|
2796
|
+
this.sessionLeases.assert(String(agent.session.id));
|
|
2797
|
+
input.signal.throwIfAborted();
|
|
2798
|
+
if (Date.now() >= input.deadlineAt)
|
|
2799
|
+
throw new Error('assistant-delivery: scheduled goal wake expired');
|
|
2800
|
+
input.assertCurrent(agent, phase);
|
|
2801
|
+
}
|
|
2802
|
+
installScheduledGoalFences(agent, input) {
|
|
2803
|
+
let pendingGoalStep;
|
|
2804
|
+
const nativeGoalStep = (source) => {
|
|
2805
|
+
const native = this.ctx.get('goals')?.get(agent);
|
|
2806
|
+
const round = source.round;
|
|
2807
|
+
if (source.kind !== 'goal' || String(source.goalId) !== input.native.goalId
|
|
2808
|
+
|| source.revision !== input.native.revision + 1 || typeof round !== 'number' || !Number.isSafeInteger(round) || round < 1
|
|
2809
|
+
|| native === undefined || native.phase !== 'active' || String(native.id) !== input.native.goalId
|
|
2810
|
+
|| native.revision !== source.revision || round !== native.roundsStarted + 1)
|
|
2811
|
+
return undefined;
|
|
2812
|
+
return { turn: 0, step: 0, goalId: String(source.goalId), revision: source.revision, round };
|
|
2813
|
+
};
|
|
2814
|
+
const durableTurnMessages = (turn) => {
|
|
2815
|
+
const events = agent.session.snapshotEvents();
|
|
2816
|
+
const start = events.findLast(event => event.type === 'turn/start');
|
|
2817
|
+
if (start?.type !== 'turn/start' || start.data.turn !== turn
|
|
2818
|
+
|| events.some(event => event.seq > start.seq && event.type === 'turn/end')) {
|
|
2819
|
+
throw new Error('assistant-delivery: exact native goal turn required');
|
|
2820
|
+
}
|
|
2821
|
+
return events.filter(event => event.seq > start.seq && event.type === 'user/message'
|
|
2822
|
+
&& !isScheduledGoalRuntimeContext(event.data.source));
|
|
2823
|
+
};
|
|
2824
|
+
const pendingCurrent = (turn, step) => {
|
|
2825
|
+
const pending = pendingGoalStep;
|
|
2826
|
+
if (pending === undefined || pending.turn !== turn || pending.step !== step)
|
|
2827
|
+
return undefined;
|
|
2828
|
+
const native = this.ctx.get('goals')?.get(agent);
|
|
2829
|
+
// Only bridge the gap before the accepted goal input is durably folded.
|
|
2830
|
+
// Once any input appears, the ordinary snapshot fence must verify it.
|
|
2831
|
+
if (native === undefined || native.phase !== 'active' || String(native.id) !== pending.goalId
|
|
2832
|
+
|| native.revision !== pending.revision || native.roundsStarted !== pending.round - 1)
|
|
2833
|
+
return undefined;
|
|
2834
|
+
return pending;
|
|
2835
|
+
};
|
|
2836
|
+
const goalTurn = () => {
|
|
2837
|
+
const events = agent.session.snapshotEvents();
|
|
2838
|
+
const start = events.findLast(event => event.type === 'turn/start');
|
|
2839
|
+
// DSH persists runtime context snapshots as user/message too; they are
|
|
2840
|
+
// context for this turn, never a second input or a grant of authority.
|
|
2841
|
+
const messages = start === undefined ? [] : events.filter(event => event.seq > start.seq && event.type === 'user/message'
|
|
2842
|
+
&& !isScheduledGoalRuntimeContext(event.data.source));
|
|
2843
|
+
if (start === undefined || events.some(event => event.seq > start.seq && event.type === 'turn/end')
|
|
2844
|
+
|| messages.length !== 1 || messages[0]?.type !== 'user/message')
|
|
2845
|
+
throw new Error('assistant-delivery: exact native goal turn required');
|
|
2846
|
+
const source = messages[0].data.source;
|
|
2847
|
+
const native = this.ctx.get('goals')?.get(agent);
|
|
2848
|
+
if (source.kind !== 'goal' || String(source.goalId) !== input.native.goalId
|
|
2849
|
+
|| source.revision !== input.native.revision + 1 || source.round < 1
|
|
2850
|
+
|| native === undefined || native.phase !== 'active' || String(native.id) !== input.native.goalId
|
|
2851
|
+
|| native.revision !== source.revision || native.roundsStarted !== source.round)
|
|
2852
|
+
throw new Error('assistant-delivery: foreign wake input denied');
|
|
2853
|
+
};
|
|
2854
|
+
const reject = () => {
|
|
2855
|
+
try {
|
|
2856
|
+
agent.cancel({ kind: 'hook', reason: 'assistant-delivery-scheduled-goal-wake-revoked' });
|
|
2857
|
+
}
|
|
2858
|
+
catch { }
|
|
2859
|
+
throw new Error('assistant-delivery: scheduled goal wake authorization changed');
|
|
2860
|
+
};
|
|
2861
|
+
const clearPending = () => { pendingGoalStep = undefined; };
|
|
2862
|
+
input.signal.addEventListener('abort', clearPending, { once: true });
|
|
2863
|
+
const preStep = agent.ctx.on('agent/pre-step', async (payload, next) => {
|
|
2864
|
+
// A pre-step decision is the sole new-Host bridge between the claimed
|
|
2865
|
+
// inbox item and its later durable append. Never carry it into another
|
|
2866
|
+
// boundary, rejection, replacement, or retry.
|
|
2867
|
+
clearPending();
|
|
2868
|
+
const offered = payload.messages.filter(message => !isScheduledGoalRuntimeContext(message.source));
|
|
2869
|
+
const offeredMessage = offered.length === 1 ? structuredClone(offered[0]) : undefined;
|
|
2870
|
+
const decision = await next();
|
|
2871
|
+
if (payload.signal.aborted || input.signal.aborted || decision.kind !== 'enter')
|
|
2872
|
+
return decision;
|
|
2873
|
+
const entered = decision.messages.filter(message => !isScheduledGoalRuntimeContext(message.source));
|
|
2874
|
+
if (offeredMessage === undefined || entered.length !== 1
|
|
2875
|
+
|| typeof offeredMessage.id !== 'string' || offeredMessage.id.length === 0
|
|
2876
|
+
|| !isDeepStrictEqual(entered[0], offeredMessage))
|
|
2877
|
+
return decision;
|
|
2878
|
+
const candidate = nativeGoalStep(entered[0].source);
|
|
2879
|
+
if (candidate === undefined)
|
|
2880
|
+
return decision;
|
|
2881
|
+
pendingGoalStep = { ...candidate, turn: payload.turn, step: payload.step };
|
|
2882
|
+
return decision;
|
|
2883
|
+
}, { prepend: true });
|
|
2884
|
+
const request = agent.ctx.on('agent/request', async (payload, next) => {
|
|
2885
|
+
const assertRequest = () => {
|
|
2886
|
+
payload.signal.throwIfAborted();
|
|
2887
|
+
if (durableTurnMessages(payload.turn).length > 0)
|
|
2888
|
+
goalTurn();
|
|
2889
|
+
else if (pendingCurrent(payload.turn, payload.step) === undefined)
|
|
2890
|
+
throw new Error('assistant-delivery: native goal step not admitted');
|
|
2891
|
+
this.assertScheduledGoal(input, agent, 'running');
|
|
2892
|
+
};
|
|
2893
|
+
try {
|
|
2894
|
+
try {
|
|
2895
|
+
assertRequest();
|
|
2896
|
+
}
|
|
2897
|
+
catch {
|
|
2898
|
+
return reject();
|
|
2899
|
+
}
|
|
2900
|
+
const result = await next();
|
|
2901
|
+
try {
|
|
2902
|
+
assertRequest();
|
|
2903
|
+
}
|
|
2904
|
+
catch {
|
|
2905
|
+
return reject();
|
|
2906
|
+
}
|
|
2907
|
+
return result;
|
|
2908
|
+
}
|
|
2909
|
+
finally {
|
|
2910
|
+
clearPending();
|
|
2911
|
+
}
|
|
2912
|
+
}, { prepend: true });
|
|
2913
|
+
const preExecute = agent.ctx.on('tools/pre-execute', async (_payload, next) => {
|
|
2914
|
+
try {
|
|
2915
|
+
goalTurn();
|
|
2916
|
+
this.assertScheduledGoal(input, agent, 'running');
|
|
2917
|
+
}
|
|
2918
|
+
catch {
|
|
2919
|
+
return { kind: 'deny', reason: 'assistant-delivery: scheduled goal wake authorization changed' };
|
|
2920
|
+
}
|
|
2921
|
+
const result = await next();
|
|
2922
|
+
try {
|
|
2923
|
+
goalTurn();
|
|
2924
|
+
this.assertScheduledGoal(input, agent, 'running');
|
|
2925
|
+
}
|
|
2926
|
+
catch {
|
|
2927
|
+
return { kind: 'deny', reason: 'assistant-delivery: scheduled goal wake authorization changed' };
|
|
2928
|
+
}
|
|
2929
|
+
return result;
|
|
2930
|
+
}, { prepend: true });
|
|
2931
|
+
const guard = agent.ctx.tools.guard(() => {
|
|
2932
|
+
try {
|
|
2933
|
+
goalTurn();
|
|
2934
|
+
this.assertScheduledGoal(input, agent, 'running');
|
|
2935
|
+
return undefined;
|
|
2936
|
+
}
|
|
2937
|
+
catch {
|
|
2938
|
+
return 'assistant-delivery: scheduled goal wake authorization changed';
|
|
2939
|
+
}
|
|
2940
|
+
});
|
|
2941
|
+
return () => { input.signal.removeEventListener('abort', clearPending); clearPending(); preStep(); request(); preExecute(); guard(); };
|
|
2942
|
+
}
|
|
2943
|
+
waitForScheduledGoalTerminal(agent, input, signal) {
|
|
2944
|
+
return new Promise(resolve => {
|
|
2945
|
+
let settled = false;
|
|
2946
|
+
let verifying = false;
|
|
2947
|
+
const finish = (value) => {
|
|
2948
|
+
if (settled)
|
|
2949
|
+
return;
|
|
2950
|
+
settled = true;
|
|
2951
|
+
removeGoal();
|
|
2952
|
+
removeStatus();
|
|
2953
|
+
signal.removeEventListener('abort', aborted);
|
|
2954
|
+
resolve(value);
|
|
2955
|
+
};
|
|
2956
|
+
const check = () => {
|
|
2957
|
+
if (settled || verifying)
|
|
2958
|
+
return;
|
|
2959
|
+
try {
|
|
2960
|
+
this.sessionLeases.assert(String(agent.session.id));
|
|
2961
|
+
input.signal.throwIfAborted();
|
|
2962
|
+
if (Date.now() >= input.deadlineAt)
|
|
2963
|
+
throw new Error('assistant-delivery: scheduled goal wake expired');
|
|
2964
|
+
const goals = this.ctx.get('goals');
|
|
2965
|
+
const current = goals?.get(agent);
|
|
2966
|
+
if (current === undefined || String(current.id) !== input.native.goalId)
|
|
2967
|
+
return finish(false);
|
|
2968
|
+
if (current.phase === 'active') {
|
|
2969
|
+
input.assertCurrent(agent, 'running');
|
|
2970
|
+
return;
|
|
2971
|
+
}
|
|
2972
|
+
if (agent.status !== 'idle' || (agent.inbox.nextTurn.length > 0 || agent.inbox.nextStep.length > 0))
|
|
2973
|
+
return;
|
|
2974
|
+
input.assertCurrent(agent, 'terminal');
|
|
2975
|
+
// Native idle/round-limit can precede the asynchronous step and
|
|
2976
|
+
// whole-goal verifier. Keep the Agent and its lease alive until that
|
|
2977
|
+
// exact terminal round settles; cancellation still ends this wait.
|
|
2978
|
+
verifying = true;
|
|
2979
|
+
void Promise.resolve().then(() => input.settle(agent, signal)).then(() => {
|
|
2980
|
+
if (settled)
|
|
2981
|
+
return;
|
|
2982
|
+
signal.throwIfAborted();
|
|
2983
|
+
this.assertScheduledGoal(input, agent, 'terminal');
|
|
2984
|
+
if (agent.status !== 'idle' || (agent.inbox.nextTurn.length > 0 || agent.inbox.nextStep.length > 0))
|
|
2985
|
+
throw new Error('assistant-delivery: goal changed during terminal settlement');
|
|
2986
|
+
finish(true);
|
|
2987
|
+
}).catch(() => {
|
|
2988
|
+
if (settled)
|
|
2989
|
+
return;
|
|
2990
|
+
try {
|
|
2991
|
+
agent.cancel({ kind: 'hook', reason: 'assistant-delivery-scheduled-goal-settlement-failed' });
|
|
2992
|
+
}
|
|
2993
|
+
catch { }
|
|
2994
|
+
finish(false);
|
|
2995
|
+
});
|
|
2996
|
+
}
|
|
2997
|
+
catch {
|
|
2998
|
+
try {
|
|
2999
|
+
agent.cancel({ kind: 'hook', reason: 'assistant-delivery-scheduled-goal-wake-revoked' });
|
|
3000
|
+
}
|
|
3001
|
+
catch { }
|
|
3002
|
+
finish(false);
|
|
3003
|
+
}
|
|
3004
|
+
};
|
|
3005
|
+
const removeGoal = this.ctx.on('goal/changed', ({ agent: changed }) => { if (changed === agent)
|
|
3006
|
+
check(); });
|
|
3007
|
+
const removeStatus = this.ctx.on('agent/status', ({ agent: changed }) => { if (changed === agent)
|
|
3008
|
+
check(); });
|
|
3009
|
+
const aborted = () => finish(false);
|
|
3010
|
+
signal.addEventListener('abort', aborted, { once: true });
|
|
3011
|
+
if (signal.aborted)
|
|
3012
|
+
aborted();
|
|
3013
|
+
else
|
|
3014
|
+
check();
|
|
3015
|
+
});
|
|
3016
|
+
}
|
|
3017
|
+
async prepare(binding, envelope, signal, context) {
|
|
3018
|
+
const imageCount = (envelope.attachments ?? [])
|
|
3019
|
+
.filter(attachment => attachment.resourceType === 'image').length;
|
|
3020
|
+
if (envelope.kind === 'command') {
|
|
3021
|
+
return { outcome: 'prepared', message: {
|
|
3022
|
+
imageAttachments: [],
|
|
3023
|
+
...(context.permissionDispatchRecovery === undefined
|
|
3024
|
+
? {}
|
|
3025
|
+
: { permissionDispatchRecovery: context.permissionDispatchRecovery }),
|
|
3026
|
+
} };
|
|
3027
|
+
}
|
|
3028
|
+
const selected = toModelRoute(this.options.getModelSelection(envelope.conversation)
|
|
3029
|
+
?? { provider: this.options.provider, model: this.options.model });
|
|
3030
|
+
if (imageCount === 0) {
|
|
3031
|
+
return { outcome: 'prepared', message: { imageAttachments: [], modelRoute: selected } };
|
|
3032
|
+
}
|
|
3033
|
+
if (!this.options.isInboundAuthorized(binding, envelope)) {
|
|
3034
|
+
return { outcome: 'not-processed', failureCode: 'image-authorization-revoked', retryable: false };
|
|
3035
|
+
}
|
|
3036
|
+
const llm = this.ctx.get('llm');
|
|
3037
|
+
if (llm === undefined) {
|
|
3038
|
+
return { outcome: 'not-processed', failureCode: 'model-directory-unavailable', retryable: true };
|
|
3039
|
+
}
|
|
3040
|
+
try {
|
|
3041
|
+
await requireImageCapability(llm, selected.provider, selected.model, signal);
|
|
3042
|
+
}
|
|
3043
|
+
catch (error) {
|
|
3044
|
+
if (signal.aborted)
|
|
3045
|
+
throw error;
|
|
3046
|
+
if (!(error instanceof ImageCapabilityAdmissionError)) {
|
|
3047
|
+
return { outcome: 'not-processed', failureCode: 'image-model-unavailable', retryable: true };
|
|
3048
|
+
}
|
|
3049
|
+
try {
|
|
3050
|
+
this.options.replyCommand(binding, envelope.eventId, imageCapabilityReply(error));
|
|
3051
|
+
}
|
|
3052
|
+
catch {
|
|
3053
|
+
return { outcome: 'not-processed', failureCode: 'image-capability-notice-failed', retryable: true };
|
|
3054
|
+
}
|
|
3055
|
+
return { outcome: 'not-processed', failureCode: 'model-image-input-unsupported', retryable: false };
|
|
3056
|
+
}
|
|
3057
|
+
const result = await this.options.imageMaterializer.materialize({
|
|
3058
|
+
...context,
|
|
3059
|
+
binding,
|
|
3060
|
+
envelope,
|
|
3061
|
+
signal,
|
|
3062
|
+
});
|
|
3063
|
+
return result.outcome === 'ready'
|
|
3064
|
+
? { outcome: 'prepared', message: { imageAttachments: result.imageAttachments, modelRoute: selected } }
|
|
3065
|
+
: { outcome: 'not-processed', failureCode: result.failureCode, retryable: result.retryable,
|
|
3066
|
+
...(result.retryAfterMs === undefined ? {} : { retryAfterMs: result.retryAfterMs }) };
|
|
3067
|
+
}
|
|
3068
|
+
replySessionCommand(binding, envelope, reply, signal, markDispatching) {
|
|
3069
|
+
if (markDispatching === undefined) {
|
|
3070
|
+
return { outcome: 'not-processed', failureCode: 'dispatch-gate-unavailable', retryable: true };
|
|
3071
|
+
}
|
|
3072
|
+
signal.throwIfAborted();
|
|
3073
|
+
markDispatching();
|
|
3074
|
+
signal.throwIfAborted();
|
|
3075
|
+
this.options.replyCommand(binding, envelope.eventId, reply);
|
|
3076
|
+
return { outcome: 'processed' };
|
|
3077
|
+
}
|
|
3078
|
+
async runFeedbackCommand(command, binding, envelope, signal, markDispatching) {
|
|
3079
|
+
const parsed = parseFeedbackCommand(command.rawInput);
|
|
3080
|
+
if (parsed.kind === 'invalid') {
|
|
3081
|
+
return this.replySessionCommand(binding, envelope, {
|
|
3082
|
+
text: feedbackUsage,
|
|
3083
|
+
format: 'plain',
|
|
3084
|
+
}, signal, markDispatching);
|
|
3085
|
+
}
|
|
3086
|
+
if ((envelope.attachments?.length ?? 0) > 0) {
|
|
3087
|
+
return this.replySessionCommand(binding, envelope, {
|
|
3088
|
+
text: '反馈命令不接受文件、图片或其他附件;本次反馈未记录。请只发送 /feedback 文字命令。',
|
|
3089
|
+
format: 'plain',
|
|
3090
|
+
}, signal, markDispatching);
|
|
3091
|
+
}
|
|
3092
|
+
let authorized;
|
|
3093
|
+
try {
|
|
3094
|
+
authorized = this.options.isOwnerFeedbackController(binding, envelope);
|
|
3095
|
+
}
|
|
3096
|
+
catch {
|
|
3097
|
+
return {
|
|
3098
|
+
outcome: 'not-processed',
|
|
3099
|
+
failureCode: 'feedback-authorization-check-failed',
|
|
3100
|
+
retryable: true,
|
|
3101
|
+
};
|
|
3102
|
+
}
|
|
3103
|
+
if (!authorized) {
|
|
3104
|
+
return this.replySessionCommand(binding, envelope, {
|
|
3105
|
+
text: '当前身份不能提交反馈;本次反馈未记录。',
|
|
3106
|
+
format: 'plain',
|
|
3107
|
+
}, signal, markDispatching);
|
|
3108
|
+
}
|
|
3109
|
+
if (markDispatching === undefined) {
|
|
3110
|
+
return { outcome: 'not-processed', failureCode: 'dispatch-gate-unavailable', retryable: true };
|
|
3111
|
+
}
|
|
3112
|
+
signal.throwIfAborted();
|
|
3113
|
+
markDispatching();
|
|
3114
|
+
signal.throwIfAborted();
|
|
3115
|
+
if (parsed.kind === 'objective' || parsed.kind === 'objective-revision' || parsed.kind === 'objective-status') {
|
|
3116
|
+
const objective = await this.options.dispatchObjectiveFeedback(binding, envelope, parsed.kind === 'objective' ? parsed.objectiveStatus : parsed);
|
|
3117
|
+
signal.throwIfAborted();
|
|
3118
|
+
if (typeof objective === 'object') {
|
|
3119
|
+
this.options.replyCommand(binding, envelope.eventId, { text: (parsed.kind === 'objective-status' ? '' : `已把该次任务结果记录为 ${objective.objectiveStatus};同一次任务只计一票。\n`) + objectiveStateMessage(objective), format: 'plain' });
|
|
3120
|
+
return { outcome: 'processed' };
|
|
3121
|
+
}
|
|
3122
|
+
if (objective === 'unknown') {
|
|
3123
|
+
return {
|
|
3124
|
+
outcome: 'not-processed',
|
|
3125
|
+
failureCode: 'objective-feedback-state-unknown',
|
|
3126
|
+
retryable: true,
|
|
3127
|
+
};
|
|
3128
|
+
}
|
|
3129
|
+
if (objective === 'unavailable') {
|
|
3130
|
+
this.options.replyCommand(binding, envelope.eventId, {
|
|
3131
|
+
text: '评测服务尚未启用;本次任务结果未记录。请联系管理员启用成长组件。',
|
|
3132
|
+
format: 'plain',
|
|
3133
|
+
});
|
|
3134
|
+
return { outcome: 'processed' };
|
|
3135
|
+
}
|
|
3136
|
+
if (objective === 'invalid-target') {
|
|
3137
|
+
this.options.replyCommand(binding, envelope.eventId, {
|
|
3138
|
+
text: '任务结果未记录。请直接回复对应的自动化或普通 Agent 任务结果消息,并发送 /feedback achieved、partial 或 not-achieved。',
|
|
3139
|
+
format: 'plain',
|
|
3140
|
+
});
|
|
3141
|
+
return { outcome: 'processed' };
|
|
3142
|
+
}
|
|
3143
|
+
if (objective === 'conflict') {
|
|
3144
|
+
this.options.replyCommand(binding, envelope.eventId, {
|
|
3145
|
+
text: '该次任务已经记录了不同的任务结果或反馈版本已变化,本次未覆盖。请回复原任务结果发送 /feedback status,使用当前版本更正或撤回。',
|
|
3146
|
+
format: 'plain',
|
|
3147
|
+
});
|
|
3148
|
+
return { outcome: 'processed' };
|
|
3149
|
+
}
|
|
3150
|
+
this.options.replyCommand(binding, envelope.eventId, {
|
|
3151
|
+
text: parsed.kind === 'objective-status' ? '尚未记录任务反馈,请回复原任务结果发送 /feedback achieved、partial 或 not-achieved。' : `已把该次任务结果记录为 ${parsed.objectiveStatus};同一次任务只计一票。回复原结果发送 /feedback status 可更正或撤回。`,
|
|
3152
|
+
format: 'plain',
|
|
3153
|
+
});
|
|
3154
|
+
return { outcome: 'processed' };
|
|
3155
|
+
}
|
|
3156
|
+
// The dispatch fence proves the exact Inbox/binding snapshot. Recheck the
|
|
3157
|
+
// mutable owner and consume an audited preference-signal authorization
|
|
3158
|
+
// immediately before the authoritative sink receives the batch.
|
|
3159
|
+
let attestation;
|
|
3160
|
+
try {
|
|
3161
|
+
attestation = this.options.authorizeOwnerPreferenceFeedback(binding, envelope, parsed.selections);
|
|
3162
|
+
}
|
|
3163
|
+
catch {
|
|
3164
|
+
return {
|
|
3165
|
+
outcome: 'not-processed',
|
|
3166
|
+
failureCode: 'feedback-authorization-check-failed-after-dispatch',
|
|
3167
|
+
retryable: false,
|
|
3168
|
+
};
|
|
3169
|
+
}
|
|
3170
|
+
if (attestation === undefined) {
|
|
3171
|
+
return {
|
|
3172
|
+
outcome: 'not-processed',
|
|
3173
|
+
failureCode: 'feedback-authorization-revoked',
|
|
3174
|
+
retryable: false,
|
|
3175
|
+
};
|
|
3176
|
+
}
|
|
3177
|
+
const events = parsed.selections.map(selection => feedbackSignalInput(binding, envelope, selection, attestation));
|
|
3178
|
+
const result = await this.options.dispatchPreferenceFeedback(Object.freeze(events));
|
|
3179
|
+
signal.throwIfAborted();
|
|
3180
|
+
if (result === 'unknown') {
|
|
3181
|
+
// The Inbox remains the durable retry envelope. Both downstream ledgers
|
|
3182
|
+
// are idempotent, so a crash/ambiguous local call safely replays the exact
|
|
3183
|
+
// feedback event rather than acknowledging a signal that may be lost.
|
|
3184
|
+
return {
|
|
3185
|
+
outcome: 'not-processed',
|
|
3186
|
+
failureCode: 'preference-feedback-state-unknown',
|
|
3187
|
+
retryable: true,
|
|
3188
|
+
};
|
|
3189
|
+
}
|
|
3190
|
+
if (result === 'unavailable') {
|
|
3191
|
+
this.options.replyCommand(binding, envelope.eventId, {
|
|
3192
|
+
text: '偏好学习服务尚未启用;本次偏好反馈未记录。',
|
|
3193
|
+
format: 'plain',
|
|
3194
|
+
});
|
|
3195
|
+
return { outcome: 'processed' };
|
|
3196
|
+
}
|
|
3197
|
+
signal.throwIfAborted();
|
|
3198
|
+
this.options.replyCommand(binding, envelope.eventId, {
|
|
3199
|
+
text: parsed.selections.length === 1
|
|
3200
|
+
? '已记录偏好反馈;它不会被当成任务成败。只作用于当前工作区与 preset。'
|
|
3201
|
+
: '已记录偏好反馈及对应的回复长度偏好;它们不会被当成任务成败。只作用于当前工作区与 preset。',
|
|
3202
|
+
format: 'plain',
|
|
3203
|
+
});
|
|
3204
|
+
return { outcome: 'processed' };
|
|
3205
|
+
}
|
|
3206
|
+
async runWorkflowCommand(command, binding, envelope, signal, markDispatching) {
|
|
3207
|
+
const parsed = parseWorkflowCommand(command.rawInput);
|
|
3208
|
+
if (parsed.kind === 'help' || parsed.kind === 'invalid') {
|
|
3209
|
+
return this.replySessionCommand(binding, envelope, {
|
|
3210
|
+
text: workflowCommandUsage,
|
|
3211
|
+
format: 'plain',
|
|
3212
|
+
}, signal, markDispatching);
|
|
3213
|
+
}
|
|
3214
|
+
if ((envelope.attachments?.length ?? 0) > 0) {
|
|
3215
|
+
return this.replySessionCommand(binding, envelope, {
|
|
3216
|
+
text: '工作流学习命令不接受附件;本次未记录。请只回复一条无附件的已完成任务结果。',
|
|
3217
|
+
format: 'plain',
|
|
3218
|
+
}, signal, markDispatching);
|
|
3219
|
+
}
|
|
3220
|
+
let authorized;
|
|
3221
|
+
try {
|
|
3222
|
+
authorized = this.options.isOwnerFeedbackController(binding, envelope);
|
|
3223
|
+
}
|
|
3224
|
+
catch {
|
|
3225
|
+
return { outcome: 'not-processed', failureCode: 'workflow-authorization-check-failed', retryable: true };
|
|
3226
|
+
}
|
|
3227
|
+
if (!authorized) {
|
|
3228
|
+
return this.replySessionCommand(binding, envelope, {
|
|
3229
|
+
text: '当前身份不是此会话的 owner;本次工作流学习未记录。',
|
|
3230
|
+
format: 'plain',
|
|
3231
|
+
}, signal, markDispatching);
|
|
3232
|
+
}
|
|
3233
|
+
if (markDispatching === undefined) {
|
|
3234
|
+
return { outcome: 'not-processed', failureCode: 'dispatch-gate-unavailable', retryable: true };
|
|
3235
|
+
}
|
|
3236
|
+
signal.throwIfAborted();
|
|
3237
|
+
markDispatching();
|
|
3238
|
+
signal.throwIfAborted();
|
|
3239
|
+
const outcome = await this.options.dispatchWorkflowCommand(binding, envelope, parsed);
|
|
3240
|
+
signal.throwIfAborted();
|
|
3241
|
+
if (outcome === 'unknown') {
|
|
3242
|
+
return { outcome: 'not-processed', failureCode: 'workflow-dispatch-recovery', retryable: true };
|
|
3243
|
+
}
|
|
3244
|
+
const text = outcome === 'recorded'
|
|
3245
|
+
? parsed.kind === 'save'
|
|
3246
|
+
? '已记录 owner 明确授权的工作流证据;它只会生成候选与审批,当前没有自动化被启用。'
|
|
3247
|
+
: '已撤回这条任务对应的工作流证据;若已有实验,成长组件会按证据撤回流程回滚。'
|
|
3248
|
+
: outcome === 'invalid-target'
|
|
3249
|
+
? '工作流证据未记录。请直接回复同一会话中一条已完成、无附件的任务结果消息。'
|
|
3250
|
+
: outcome === 'conflict'
|
|
3251
|
+
? '该工作流命令与已持久化记录冲突;本次没有覆盖原记录。'
|
|
3252
|
+
: '成长组件尚未启用;本次工作流证据未记录。';
|
|
3253
|
+
this.options.replyCommand(binding, envelope.eventId, { text, format: 'plain' });
|
|
3254
|
+
return { outcome: 'processed' };
|
|
3255
|
+
}
|
|
3256
|
+
async runLearningCommand(command, binding, envelope, signal, markDispatching) {
|
|
3257
|
+
const parsed = parseLearningCommand(command.rawInput);
|
|
3258
|
+
if (parsed.kind === 'help' || parsed.kind === 'invalid') {
|
|
3259
|
+
return this.replySessionCommand(binding, envelope, {
|
|
3260
|
+
text: learningCommandUsage,
|
|
3261
|
+
format: 'plain',
|
|
3262
|
+
}, signal, markDispatching);
|
|
3263
|
+
}
|
|
3264
|
+
if (parsed.kind === 'forget-prompt') {
|
|
3265
|
+
return this.replySessionCommand(binding, envelope, {
|
|
3266
|
+
text: '尚未删除任何学习记录。若确定永久删除当前工作区与 preset 的记录,请发送 /learning forget confirm。',
|
|
3267
|
+
format: 'plain',
|
|
3268
|
+
}, signal, markDispatching);
|
|
3269
|
+
}
|
|
3270
|
+
if ((envelope.attachments?.length ?? 0) > 0) {
|
|
3271
|
+
return this.replySessionCommand(binding, envelope, {
|
|
3272
|
+
text: '学习控制命令不接受附件;本次未执行。请只发送 /learning 文字命令。',
|
|
3273
|
+
format: 'plain',
|
|
3274
|
+
}, signal, markDispatching);
|
|
3275
|
+
}
|
|
3276
|
+
let authorized;
|
|
3277
|
+
try {
|
|
3278
|
+
authorized = this.options.isOwnerFeedbackController(binding, envelope);
|
|
3279
|
+
}
|
|
3280
|
+
catch {
|
|
3281
|
+
return { outcome: 'not-processed', failureCode: 'learning-authorization-check-failed', retryable: true };
|
|
3282
|
+
}
|
|
3283
|
+
if (!authorized) {
|
|
3284
|
+
return this.replySessionCommand(binding, envelope, {
|
|
3285
|
+
text: '当前身份不是此会话的 owner;本次学习控制未执行。',
|
|
3286
|
+
format: 'plain',
|
|
3287
|
+
}, signal, markDispatching);
|
|
3288
|
+
}
|
|
3289
|
+
if (markDispatching === undefined) {
|
|
3290
|
+
return { outcome: 'not-processed', failureCode: 'dispatch-gate-unavailable', retryable: true };
|
|
3291
|
+
}
|
|
3292
|
+
signal.throwIfAborted();
|
|
3293
|
+
markDispatching();
|
|
3294
|
+
signal.throwIfAborted();
|
|
3295
|
+
const action = parsed.kind === 'forget-confirm'
|
|
3296
|
+
? 'forget'
|
|
3297
|
+
: parsed.kind === 'rollback-confirm' ? 'rollback' : parsed.kind;
|
|
3298
|
+
const result = await this.options.dispatchLearningCommand(binding, envelope, action, parsed.kind === 'rollback-confirm' ? parsed.preferenceKey : undefined);
|
|
3299
|
+
signal.throwIfAborted();
|
|
3300
|
+
if (result === 'unknown') {
|
|
3301
|
+
return { outcome: 'not-processed', failureCode: learningDispatchRecoveryCode, retryable: true };
|
|
3302
|
+
}
|
|
3303
|
+
if (result === 'unavailable') {
|
|
3304
|
+
this.options.replyCommand(binding, envelope.eventId, {
|
|
3305
|
+
text: '偏好学习服务尚未启用;本次学习控制未执行。',
|
|
3306
|
+
format: 'plain',
|
|
3307
|
+
});
|
|
3308
|
+
return { outcome: 'processed' };
|
|
3309
|
+
}
|
|
3310
|
+
if (result === 'forbidden' || result.outcome === 'stale') {
|
|
3311
|
+
this.options.replyCommand(binding, envelope.eventId, {
|
|
3312
|
+
text: result === 'forbidden'
|
|
3313
|
+
? 'owner 或会话绑定已变化;本次学习控制未执行。'
|
|
3314
|
+
: '已有更新的学习控制,或 owner/会话绑定已经变化;本次学习控制未执行,也未覆盖当前状态。',
|
|
3315
|
+
format: 'plain',
|
|
3316
|
+
});
|
|
3317
|
+
return { outcome: 'processed' };
|
|
3318
|
+
}
|
|
3319
|
+
const state = result.state;
|
|
3320
|
+
const statusLines = [
|
|
3321
|
+
`组件状态:${state.administrativelyEnabled ? '已启用' : '已禁用'}`,
|
|
3322
|
+
`管理员开关:${state.administrativelyEnabled ? '已开启' : '已关闭'}`,
|
|
3323
|
+
`收集状态:${state.collectionMode === 'paused' ? '已暂停' : '运行中'}`,
|
|
3324
|
+
`owner 控制:${state.collectionMode === 'paused' ? '已暂停' : '未暂停'}`,
|
|
3325
|
+
`- 已保存信号:${state.signals}`,
|
|
3326
|
+
`- 已保存假设:${state.hypotheses}`,
|
|
3327
|
+
`- 已保存有效偏好:${state.storedActiveOverlays}`,
|
|
3328
|
+
`- 当前生效偏好:${state.effectiveActiveOverlays}`,
|
|
3329
|
+
`- 待观察假设:${state.shadowHypotheses}`,
|
|
3330
|
+
];
|
|
3331
|
+
const text = result.action === 'status'
|
|
3332
|
+
? statusLines.join('\n')
|
|
3333
|
+
: result.action === 'export'
|
|
3334
|
+
? serializeLearningExport(result.exportDocument)
|
|
3335
|
+
: result.action === 'explain'
|
|
3336
|
+
? result.explanation?.length
|
|
3337
|
+
? [
|
|
3338
|
+
'当前 owner 与 lineage 的 T1 偏好摘要(不含原始内容):',
|
|
3339
|
+
...result.explanation.map(item => [
|
|
3340
|
+
`- key=${item.key}`,
|
|
3341
|
+
` value=${item.value}`,
|
|
3342
|
+
` state=${item.state}`,
|
|
3343
|
+
` version=${item.version}`,
|
|
3344
|
+
` supportingSignals=${item.supportingSignals}`,
|
|
3345
|
+
` contradictingSignals=${item.contradictingSignals}`,
|
|
3346
|
+
` evidenceMass=${item.evidenceMass}`,
|
|
3347
|
+
].join('\n')),
|
|
3348
|
+
].join('\n')
|
|
3349
|
+
: '当前 owner 与 lineage 没有 T1 偏好摘要。'
|
|
3350
|
+
: result.action === 'pause'
|
|
3351
|
+
? [state.administrativelyEnabled
|
|
3352
|
+
? '已暂停当前工作区与 preset 的偏好学习。暂停期间不收集、不激活、也不注入偏好;已有记录保留。'
|
|
3353
|
+
: '已记录暂停状态;偏好学习组件当前由管理员禁用,重新启用后仍会保持暂停。',
|
|
3354
|
+
'', ...statusLines].join('\n')
|
|
3355
|
+
: result.action === 'resume'
|
|
3356
|
+
? [state.administrativelyEnabled
|
|
3357
|
+
? '已恢复当前工作区与 preset 的偏好学习;已有的有效偏好会重新生效。'
|
|
3358
|
+
: '已记录恢复状态;偏好学习组件当前仍由管理员禁用,只有管理员重新启用后偏好才会生效。',
|
|
3359
|
+
'', ...statusLines].join('\n')
|
|
3360
|
+
: result.action === 'rollback'
|
|
3361
|
+
? [result.rolledBack
|
|
3362
|
+
? `已回滚 ${parsed.kind === 'rollback-confirm' ? parsed.preferenceKey : '指定键'} 当前激活的偏好。`
|
|
3363
|
+
: `${parsed.kind === 'rollback-confirm' ? parsed.preferenceKey : '指定键'} 当前没有激活偏好;未修改偏好记录。`,
|
|
3364
|
+
state.administrativelyEnabled
|
|
3365
|
+
? `owner 收集状态:${state.collectionMode === 'paused' ? '已暂停' : '运行中'}。`
|
|
3366
|
+
: '管理员开关:已禁用;即使 owner 处于运行状态,偏好仍不会收集或生效。',
|
|
3367
|
+
'',
|
|
3368
|
+
...statusLines,
|
|
3369
|
+
].join('\n')
|
|
3370
|
+
: [
|
|
3371
|
+
'已永久删除当前工作区与 preset 的偏好学习记录。',
|
|
3372
|
+
`- 删除信号:${result.deletedSignals ?? 0}`,
|
|
3373
|
+
`- 删除假设:${result.deletedHypotheses ?? 0}`,
|
|
3374
|
+
'',
|
|
3375
|
+
...statusLines,
|
|
3376
|
+
].join('\n');
|
|
3377
|
+
this.options.replyCommand(binding, envelope.eventId, { text, format: 'plain' });
|
|
3378
|
+
return { outcome: 'processed' };
|
|
3379
|
+
}
|
|
3380
|
+
async runOwnerSelfIterationCommand(command, binding, envelope, signal, markDispatching) {
|
|
3381
|
+
if ((envelope.attachments?.length ?? 0) > 0) {
|
|
3382
|
+
return this.replySessionCommand(binding, envelope, {
|
|
3383
|
+
text: '自迭代控制命令不接受文件、图片或其他附件;本次未执行。',
|
|
3384
|
+
format: 'plain',
|
|
3385
|
+
}, signal, markDispatching);
|
|
3386
|
+
}
|
|
3387
|
+
if (command === undefined) {
|
|
3388
|
+
return this.replySessionCommand(binding, envelope, {
|
|
3389
|
+
text: ownerSelfIterationUsage,
|
|
3390
|
+
format: 'plain',
|
|
3391
|
+
}, signal, markDispatching);
|
|
3392
|
+
}
|
|
3393
|
+
let authorized;
|
|
3394
|
+
try {
|
|
3395
|
+
authorized = this.options.isOwnerFeedbackController(binding, envelope);
|
|
3396
|
+
}
|
|
3397
|
+
catch {
|
|
3398
|
+
return { outcome: 'not-processed', failureCode: 'self-iteration-authorization-check-failed', retryable: true };
|
|
3399
|
+
}
|
|
3400
|
+
if (!authorized) {
|
|
3401
|
+
return this.replySessionCommand(binding, envelope, {
|
|
3402
|
+
text: '当前身份不是此会话的 owner;本次自迭代控制未执行。',
|
|
3403
|
+
format: 'plain',
|
|
3404
|
+
}, signal, markDispatching);
|
|
3405
|
+
}
|
|
3406
|
+
if (markDispatching === undefined) {
|
|
3407
|
+
return { outcome: 'not-processed', failureCode: 'dispatch-gate-unavailable', retryable: true };
|
|
3408
|
+
}
|
|
3409
|
+
signal.throwIfAborted();
|
|
3410
|
+
markDispatching();
|
|
3411
|
+
signal.throwIfAborted();
|
|
3412
|
+
const result = await this.options.dispatchOwnerSelfIterationCommand(binding, envelope, command);
|
|
3413
|
+
signal.throwIfAborted();
|
|
3414
|
+
if (result === 'forbidden') {
|
|
3415
|
+
this.options.replyCommand(binding, envelope.eventId, {
|
|
3416
|
+
text: 'owner 或会话绑定已变化;本次自迭代控制未执行。',
|
|
3417
|
+
format: 'plain',
|
|
3418
|
+
});
|
|
3419
|
+
return { outcome: 'processed' };
|
|
3420
|
+
}
|
|
3421
|
+
if (result === 'unavailable') {
|
|
3422
|
+
this.options.replyCommand(binding, envelope.eventId, {
|
|
3423
|
+
text: '自迭代控制服务尚未启用;本次控制未执行。',
|
|
3424
|
+
format: 'plain',
|
|
3425
|
+
});
|
|
3426
|
+
return { outcome: 'processed' };
|
|
3427
|
+
}
|
|
3428
|
+
this.options.replyCommand(binding, envelope.eventId, {
|
|
3429
|
+
text: formatOwnerSelfIterationResult(command.action, result),
|
|
3430
|
+
format: 'plain',
|
|
3431
|
+
});
|
|
3432
|
+
return { outcome: 'processed' };
|
|
3433
|
+
}
|
|
3434
|
+
async runVersionQuery(query, binding, envelope, signal, markDispatching) {
|
|
3435
|
+
if (query.kind !== 'natural-language' && (envelope.attachments?.length ?? 0) > 0) {
|
|
3436
|
+
return this.replySessionCommand(binding, envelope, {
|
|
3437
|
+
text: '版本查询命令不接受文件、图片或其他附件;本次未执行。',
|
|
3438
|
+
format: 'plain',
|
|
3439
|
+
}, signal, markDispatching);
|
|
3440
|
+
}
|
|
3441
|
+
const checkAuthorized = () => {
|
|
3442
|
+
try {
|
|
3443
|
+
return this.options.isInboundAuthorized(binding, envelope);
|
|
3444
|
+
}
|
|
3445
|
+
catch {
|
|
3446
|
+
return { outcome: 'not-processed', failureCode: 'inbound-authorization-check-failed', retryable: true };
|
|
3447
|
+
}
|
|
3448
|
+
};
|
|
3449
|
+
const preAuth = checkAuthorized();
|
|
3450
|
+
if (preAuth !== true) {
|
|
3451
|
+
return preAuth === false
|
|
3452
|
+
? { outcome: 'not-processed', failureCode: 'inbound-authorization-revoked', retryable: false }
|
|
3453
|
+
: preAuth;
|
|
3454
|
+
}
|
|
3455
|
+
if (markDispatching === undefined) {
|
|
3456
|
+
return { outcome: 'not-processed', failureCode: 'dispatch-gate-unavailable', retryable: true };
|
|
3457
|
+
}
|
|
3458
|
+
signal.throwIfAborted();
|
|
3459
|
+
markDispatching();
|
|
3460
|
+
signal.throwIfAborted();
|
|
3461
|
+
const report = this.options.dispatchVersionQuery !== undefined
|
|
3462
|
+
? await this.options.dispatchVersionQuery(binding, envelope, query)
|
|
3463
|
+
: await collectDeliveryVersionReport({ ctx: this.ctx });
|
|
3464
|
+
signal.throwIfAborted();
|
|
3465
|
+
const postAuth = checkAuthorized();
|
|
3466
|
+
if (postAuth !== true) {
|
|
3467
|
+
return postAuth === false
|
|
3468
|
+
? { outcome: 'not-processed', failureCode: 'inbound-authorization-revoked', retryable: false }
|
|
3469
|
+
: postAuth;
|
|
3470
|
+
}
|
|
3471
|
+
this.options.replyCommand(binding, envelope.eventId, {
|
|
3472
|
+
text: formatAssistantVersionSummary(report),
|
|
3473
|
+
format: 'plain',
|
|
3474
|
+
});
|
|
3475
|
+
return { outcome: 'processed' };
|
|
3476
|
+
}
|
|
3477
|
+
sessionHelp(native) {
|
|
3478
|
+
const lines = [
|
|
3479
|
+
'会话命令:',
|
|
3480
|
+
'- /new(/clear):开始空白新会话;旧会话保留。',
|
|
3481
|
+
'- /stop:停止当前任务;当前会话与已完成上下文保留。',
|
|
3482
|
+
'- /status(/session):查看当前 session、上下文与模型。',
|
|
3483
|
+
'- /model:查看或切换模型;上下文保留。',
|
|
3484
|
+
'- /permission:查看或切换运行权限。',
|
|
3485
|
+
'- /feedback:提交结构化偏好;回复自动化结果可记录 achieved/partial/not-achieved;不进入模型。',
|
|
3486
|
+
'- /learning:查看、导出、暂停、恢复或清除当前 scope 的偏好学习;不进入模型。',
|
|
3487
|
+
'- /autonomy:开启、关闭或升级整体助手自迭代能力;不进入模型。',
|
|
3488
|
+
'- /version:查看当前助手、Host、插件版本与自迭代演进统计;不进入模型。',
|
|
3489
|
+
'- /help:显示当前实际可用命令。',
|
|
3490
|
+
];
|
|
3491
|
+
const visible = native.filter(command => SAFE_NATIVE_COMMANDS.has(command.name));
|
|
3492
|
+
if (visible.length > 0) {
|
|
3493
|
+
lines.push('', 'DSH / 当前 preset 命令:');
|
|
3494
|
+
for (const command of visible)
|
|
3495
|
+
lines.push(`- /${command.name}:${command.description}`);
|
|
3496
|
+
}
|
|
3497
|
+
return lines.join('\n');
|
|
3498
|
+
}
|
|
3499
|
+
async runSessionCommand(command, binding, envelope, signal, markDispatching) {
|
|
3500
|
+
const args = command.rawInput.trim();
|
|
3501
|
+
const local = new Set(['clear', 'help', 'new', 'session', 'status', 'stop']);
|
|
3502
|
+
if (local.has(command.name) && args !== '') {
|
|
3503
|
+
return this.replySessionCommand(binding, envelope, {
|
|
3504
|
+
text: `/${command.name} 不接受参数。发送 /help 查看用法。`,
|
|
3505
|
+
format: 'plain',
|
|
3506
|
+
}, signal, markDispatching);
|
|
3507
|
+
}
|
|
3508
|
+
const agents = this.ctx.get('agents');
|
|
3509
|
+
const sessions = this.ctx.get('sessions');
|
|
3510
|
+
if (agents === undefined || sessions === undefined) {
|
|
3511
|
+
return { outcome: 'not-processed', failureCode: 'agent-runtime-unavailable', retryable: true };
|
|
3512
|
+
}
|
|
3513
|
+
const selectedRoute = toModelRoute(this.options.getModelSelection(envelope.conversation)
|
|
3514
|
+
?? { provider: this.options.provider, model: this.options.model });
|
|
3515
|
+
const selected = agentSelection(selectedRoute);
|
|
3516
|
+
let handle;
|
|
3517
|
+
let resumed = false;
|
|
3518
|
+
let nativeDispatchStarted = false;
|
|
3519
|
+
const authorizationFailure = () => {
|
|
3520
|
+
try {
|
|
3521
|
+
return this.options.isInboundAuthorized(binding, envelope)
|
|
3522
|
+
? undefined
|
|
3523
|
+
: { outcome: 'not-processed', failureCode: 'inbound-authorization-revoked', retryable: false };
|
|
3524
|
+
}
|
|
3525
|
+
catch {
|
|
3526
|
+
return { outcome: 'not-processed', failureCode: 'inbound-authorization-check-failed', retryable: true };
|
|
3527
|
+
}
|
|
3528
|
+
};
|
|
3529
|
+
try {
|
|
3530
|
+
const agentPresets = this.options.getAgentPresets();
|
|
3531
|
+
const presetId = agentPresets === undefined
|
|
3532
|
+
? binding.agentPreset
|
|
3533
|
+
: (await agentPresets.resolve(binding.agentPreset)).id;
|
|
3534
|
+
await requireWorkspace(binding.workspace);
|
|
3535
|
+
handle = await this.resumeAgent({
|
|
3536
|
+
resumeSessionId: SessionId(binding.sessionId),
|
|
3537
|
+
signal,
|
|
3538
|
+
agentOptions: {
|
|
3539
|
+
provider: selected.provider,
|
|
3540
|
+
model: selected.model,
|
|
3541
|
+
maxTokens: this.options.maxOutputTokens,
|
|
3542
|
+
},
|
|
3543
|
+
setup: async (agentCtx, preparedAgent) => {
|
|
3544
|
+
await this.setupAgent(agentCtx, preparedAgent, binding.workspace, presetId, externalPrincipalId(binding.principal), selected, agentPresets);
|
|
3545
|
+
},
|
|
3546
|
+
});
|
|
3547
|
+
resumed = true;
|
|
3548
|
+
signal.throwIfAborted();
|
|
3549
|
+
const agent = handle.agent;
|
|
3550
|
+
const commands = this.ctx.get('commands');
|
|
3551
|
+
const native = commands?.list(agent) ?? [];
|
|
3552
|
+
const revoked = authorizationFailure();
|
|
3553
|
+
if (revoked !== undefined)
|
|
3554
|
+
return revoked;
|
|
3555
|
+
if (command.name === 'help') {
|
|
3556
|
+
return this.replySessionCommand(binding, envelope, {
|
|
3557
|
+
text: this.sessionHelp(native),
|
|
3558
|
+
format: 'plain',
|
|
3559
|
+
}, signal, markDispatching);
|
|
3560
|
+
}
|
|
3561
|
+
if (command.name === 'status' || command.name === 'session') {
|
|
3562
|
+
const messages = agent.session.deriveMessages().length;
|
|
3563
|
+
const turns = agent.session.snapshotEvents().filter(event => event.type === 'turn/end').length;
|
|
3564
|
+
return this.replySessionCommand(binding, envelope, {
|
|
3565
|
+
text: [
|
|
3566
|
+
'当前会话',
|
|
3567
|
+
`- 第 ${binding.generation} 代(${sessionFingerprint(binding.sessionId)})`,
|
|
3568
|
+
`- 状态:${agent.status === 'idle' ? '空闲' : '运行中'}`,
|
|
3569
|
+
`- 上下文消息:${messages}`,
|
|
3570
|
+
`- 已记录轮次:${turns}`,
|
|
3571
|
+
`- 模型:${routeLabel(selectedRoute)}`,
|
|
3572
|
+
'',
|
|
3573
|
+
'/new 会开始空白新 session 并保留旧会话;/stop 只停止当前任务,不清空上下文。',
|
|
3574
|
+
].join('\n'),
|
|
3575
|
+
format: 'plain',
|
|
3576
|
+
}, signal, markDispatching);
|
|
3577
|
+
}
|
|
3578
|
+
const descriptor = SAFE_NATIVE_COMMANDS.has(command.name)
|
|
3579
|
+
? native.find(candidate => candidate.name === command.name)
|
|
3580
|
+
: undefined;
|
|
3581
|
+
if (commands === undefined || descriptor === undefined) {
|
|
3582
|
+
return this.replySessionCommand(binding, envelope, {
|
|
3583
|
+
text: `未知命令 /${command.name}。发送 /help 查看当前实际可用命令。`,
|
|
3584
|
+
format: 'plain',
|
|
3585
|
+
}, signal, markDispatching);
|
|
3586
|
+
}
|
|
3587
|
+
if ((envelope.attachments?.length ?? 0) > 0) {
|
|
3588
|
+
return this.replySessionCommand(binding, envelope, {
|
|
3589
|
+
text: `当前渠道暂不支持为 /${command.name} 附带文件或图片。`,
|
|
3590
|
+
format: 'plain',
|
|
3591
|
+
}, signal, markDispatching);
|
|
3592
|
+
}
|
|
3593
|
+
if (markDispatching === undefined) {
|
|
3594
|
+
return { outcome: 'not-processed', failureCode: 'dispatch-gate-unavailable', retryable: true };
|
|
3595
|
+
}
|
|
3596
|
+
signal.throwIfAborted();
|
|
3597
|
+
const preExecutionAuthorization = authorizationFailure();
|
|
3598
|
+
if (preExecutionAuthorization !== undefined)
|
|
3599
|
+
return preExecutionAuthorization;
|
|
3600
|
+
markDispatching();
|
|
3601
|
+
nativeDispatchStarted = true;
|
|
3602
|
+
const execution = await commands.execute(agent, envelope.text, [], signal);
|
|
3603
|
+
signal.throwIfAborted();
|
|
3604
|
+
if (execution === undefined) {
|
|
3605
|
+
return {
|
|
3606
|
+
outcome: 'not-processed',
|
|
3607
|
+
failureCode: 'native-command-unresolved-after-dispatch',
|
|
3608
|
+
retryable: false,
|
|
3609
|
+
};
|
|
3610
|
+
}
|
|
3611
|
+
if (!await sessions.flush(agent.session)) {
|
|
3612
|
+
return {
|
|
3613
|
+
outcome: 'not-processed',
|
|
3614
|
+
failureCode: 'command-session-flush-failed',
|
|
3615
|
+
retryable: false,
|
|
3616
|
+
};
|
|
3617
|
+
}
|
|
3618
|
+
signal.throwIfAborted();
|
|
3619
|
+
const finalAuthorization = authorizationFailure();
|
|
3620
|
+
if (finalAuthorization !== undefined)
|
|
3621
|
+
return { ...finalAuthorization, retryable: false };
|
|
3622
|
+
const result = execution.result;
|
|
3623
|
+
this.options.replyCommand(binding, envelope.eventId, {
|
|
3624
|
+
text: result?.text ?? (result?.kind === 'error'
|
|
3625
|
+
? `/${command.name} 未完成。`
|
|
3626
|
+
: `/${command.name} 已完成。`),
|
|
3627
|
+
format: 'plain',
|
|
3628
|
+
});
|
|
3629
|
+
return { outcome: 'processed' };
|
|
3630
|
+
}
|
|
3631
|
+
catch (error) {
|
|
3632
|
+
if (signal.aborted || causedByUserCancellation(error))
|
|
3633
|
+
throw error;
|
|
3634
|
+
if (nativeDispatchStarted) {
|
|
3635
|
+
this.ctx.logger.warn(`assistant-delivery: native command /${command.name} became ambiguous for session `
|
|
3636
|
+
+ sessionFingerprint(binding.sessionId));
|
|
3637
|
+
return {
|
|
3638
|
+
outcome: 'not-processed',
|
|
3639
|
+
failureCode: 'native-command-execution-ambiguous',
|
|
3640
|
+
retryable: false,
|
|
3641
|
+
};
|
|
3642
|
+
}
|
|
3643
|
+
if (resumed) {
|
|
3644
|
+
return {
|
|
3645
|
+
outcome: 'not-processed',
|
|
3646
|
+
failureCode: 'session-command-runtime-failed',
|
|
3647
|
+
retryable: true,
|
|
3648
|
+
};
|
|
3649
|
+
}
|
|
3650
|
+
const failureCode = sessionResumeFailureCode(error);
|
|
3651
|
+
this.ctx.logger.warn(`assistant-delivery: ${failureCode} for session ${sessionFingerprint(binding.sessionId)}`);
|
|
3652
|
+
try {
|
|
3653
|
+
return this.replySessionCommand(binding, envelope, {
|
|
3654
|
+
text: [
|
|
3655
|
+
'当前会话暂时无法恢复;原历史未删除。',
|
|
3656
|
+
`- 会话:第 ${binding.generation} 代(${sessionFingerprint(binding.sessionId)})`,
|
|
3657
|
+
`- 诊断:${failureCode}`,
|
|
3658
|
+
'',
|
|
3659
|
+
'请先修复或升级对应 DSH 插件后重试;也可发送 /new 开始空白新会话,旧会话仍会保留。',
|
|
3660
|
+
].join('\n'),
|
|
3661
|
+
format: 'plain',
|
|
3662
|
+
}, signal, markDispatching);
|
|
3663
|
+
}
|
|
3664
|
+
catch {
|
|
3665
|
+
return {
|
|
3666
|
+
outcome: 'not-processed',
|
|
3667
|
+
failureCode: 'session-diagnostic-reply-failed',
|
|
3668
|
+
retryable: failureCode !== 'agent-identity-mismatch' && failureCode !== 'session-persistence-corrupt',
|
|
3669
|
+
};
|
|
3670
|
+
}
|
|
3671
|
+
}
|
|
3672
|
+
finally {
|
|
3673
|
+
await this.disposeAfterReplyBoundary(binding.sessionId, handle);
|
|
3674
|
+
}
|
|
3675
|
+
}
|
|
3676
|
+
async process(binding, envelope, outerSignal, prepared, markDispatching, restartContinuation) {
|
|
3677
|
+
const sessionCommand = parseDeliveryCommand(envelope);
|
|
3678
|
+
const isAutonomyCommand = envelope.kind === 'command' && /^\/autonomy(?:[\t ]|$)/iu.test(envelope.text);
|
|
3679
|
+
if (envelope.kind === 'command' && sessionCommand === undefined && !isAutonomyCommand) {
|
|
3680
|
+
return this.replySessionCommand(binding, envelope, {
|
|
3681
|
+
text: '命令格式无效。命令必须以小写 /name 开头,并使用普通空格分隔参数;发送 /help 查看用法。',
|
|
3682
|
+
format: 'plain',
|
|
3683
|
+
}, outerSignal, markDispatching);
|
|
3684
|
+
}
|
|
3685
|
+
if (isExactDeliveryCommand(sessionCommand, 'new', 'clear')) {
|
|
3686
|
+
return this.replySessionCommand(binding, envelope, {
|
|
3687
|
+
text: `已开始新会话(第 ${binding.generation} 代,${sessionFingerprint(binding.sessionId)});`
|
|
3688
|
+
+ '旧会话已保留。新 session 的对话上下文为空。',
|
|
3689
|
+
format: 'plain',
|
|
3690
|
+
}, outerSignal, markDispatching);
|
|
3691
|
+
}
|
|
3692
|
+
if (isExactDeliveryCommand(sessionCommand, 'stop')) {
|
|
3693
|
+
return this.replySessionCommand(binding, envelope, {
|
|
3694
|
+
text: '已处理停止请求;当前 session 与已完成上下文保留。',
|
|
3695
|
+
format: 'plain',
|
|
3696
|
+
}, outerSignal, markDispatching);
|
|
3697
|
+
}
|
|
3698
|
+
let lease;
|
|
3699
|
+
try {
|
|
3700
|
+
lease = this.sessionLeases.open({ kind: 'bound', binding }, outerSignal);
|
|
3701
|
+
}
|
|
3702
|
+
catch (error) {
|
|
3703
|
+
if (error instanceof SessionLeaseUnavailable) {
|
|
3704
|
+
if (error.kind === 'unknown' && !outerSignal.aborted) {
|
|
3705
|
+
try {
|
|
3706
|
+
if (this.options.isInboundAuthorized(binding, envelope))
|
|
3707
|
+
this.options.replyCommand(binding, envelope.eventId, {
|
|
3708
|
+
text: '上一次执行是否已经停止还无法确认,因此暂时无法继续这个会话。请先核对外部操作;需要独立开始新任务可发送 /new,旧会话会保留。',
|
|
3709
|
+
format: 'plain',
|
|
3710
|
+
});
|
|
3711
|
+
}
|
|
3712
|
+
catch { /* Keep the exact unknown execution diagnostic even if its notice is unavailable. */ }
|
|
3713
|
+
}
|
|
3714
|
+
return {
|
|
3715
|
+
outcome: 'not-processed', failureCode: `session-lease-${error.kind}`,
|
|
3716
|
+
retryable: error.kind === 'busy', retryAfterMs: this.sessionLeases.leaseMs,
|
|
3717
|
+
};
|
|
3718
|
+
}
|
|
3719
|
+
throw error;
|
|
3720
|
+
}
|
|
3721
|
+
let control;
|
|
3722
|
+
let taskDeadline;
|
|
3723
|
+
try {
|
|
3724
|
+
control = this.beginSessionControl(binding.sessionId, lease.signal);
|
|
3725
|
+
taskDeadline = setTimeout(() => {
|
|
3726
|
+
// Cancel the durable lease as well as the local wait: late tools and
|
|
3727
|
+
// model requests must remain fenced until real teardown is observed.
|
|
3728
|
+
lease.cancel(new AgentTaskTimeoutError());
|
|
3729
|
+
}, this.options.taskTimeoutMs);
|
|
3730
|
+
taskDeadline.unref?.();
|
|
3731
|
+
lease.dispatch();
|
|
3732
|
+
return await this.processControlled(binding, envelope, control.controller.signal, sessionCommand, prepared, markDispatching === undefined ? undefined : () => {
|
|
3733
|
+
lease.assert();
|
|
3734
|
+
markDispatching();
|
|
3735
|
+
lease.assert();
|
|
3736
|
+
}, restartContinuation);
|
|
3737
|
+
}
|
|
3738
|
+
catch (error) {
|
|
3739
|
+
if (control?.command !== undefined && causedByUserCancellation(error)) {
|
|
3740
|
+
return permissionCommand(sessionCommand) === undefined
|
|
3741
|
+
? { outcome: 'processed' }
|
|
3742
|
+
: {
|
|
3743
|
+
outcome: 'not-processed',
|
|
3744
|
+
failureCode: permissionDispatchRecoveryCode('cancelled'),
|
|
3745
|
+
retryable: true,
|
|
3746
|
+
};
|
|
3747
|
+
}
|
|
3748
|
+
throw error;
|
|
3749
|
+
}
|
|
3750
|
+
finally {
|
|
3751
|
+
if (taskDeadline !== undefined)
|
|
3752
|
+
clearTimeout(taskDeadline);
|
|
3753
|
+
if (control !== undefined)
|
|
3754
|
+
this.endSessionControl(binding.sessionId, control);
|
|
3755
|
+
lease.close();
|
|
3756
|
+
}
|
|
3757
|
+
}
|
|
3758
|
+
async processControlled(binding, envelope, signal, sessionCommand, prepared, markDispatching, restartContinuation) {
|
|
3759
|
+
if (sessionCommand?.name === 'feedback') {
|
|
3760
|
+
return await this.runFeedbackCommand(sessionCommand, binding, envelope, signal, markDispatching);
|
|
3761
|
+
}
|
|
3762
|
+
if (sessionCommand?.name === 'workflow') {
|
|
3763
|
+
return await this.runWorkflowCommand(sessionCommand, binding, envelope, signal, markDispatching);
|
|
3764
|
+
}
|
|
3765
|
+
if (sessionCommand?.name === 'learning') {
|
|
3766
|
+
return await this.runLearningCommand(sessionCommand, binding, envelope, signal, markDispatching);
|
|
3767
|
+
}
|
|
3768
|
+
const versionQuery = parseOwnerVersionQuery(envelope.text);
|
|
3769
|
+
if (versionQuery !== undefined
|
|
3770
|
+
&& (versionQuery.kind !== 'natural-language' || (envelope.attachments?.length ?? 0) === 0)) {
|
|
3771
|
+
return await this.runVersionQuery(versionQuery, binding, envelope, signal, markDispatching);
|
|
3772
|
+
}
|
|
3773
|
+
if (sessionCommand?.name === 'version') {
|
|
3774
|
+
return this.replySessionCommand(binding, envelope, {
|
|
3775
|
+
text: '/version 不接受参数。发送 /help 查看用法。',
|
|
3776
|
+
format: 'plain',
|
|
3777
|
+
}, signal, markDispatching);
|
|
3778
|
+
}
|
|
3779
|
+
const rawSelfIterationCommand = parseOwnerSelfIterationCommand(envelope.text);
|
|
3780
|
+
const isAutonomyCommand = envelope.kind === 'command' && /^\/autonomy(?:[\t ]|$)/iu.test(envelope.text);
|
|
3781
|
+
if (sessionCommand?.name === 'autonomy' || isAutonomyCommand || rawSelfIterationCommand !== undefined) {
|
|
3782
|
+
return await this.runOwnerSelfIterationCommand(rawSelfIterationCommand, binding, envelope, signal, markDispatching);
|
|
3783
|
+
}
|
|
3784
|
+
const permissions = permissionCommand(sessionCommand);
|
|
3785
|
+
if (permissions !== undefined) {
|
|
3786
|
+
if (markDispatching === undefined) {
|
|
3787
|
+
return { outcome: 'not-processed', failureCode: 'dispatch-gate-unavailable', retryable: true };
|
|
3788
|
+
}
|
|
3789
|
+
return await this.runPermissionCommand(permissions, binding, envelope, signal, markDispatching, prepared?.permissionDispatchRecovery);
|
|
3790
|
+
}
|
|
3791
|
+
const command = modelCommand(sessionCommand);
|
|
3792
|
+
if (command !== undefined) {
|
|
3793
|
+
const llm = this.ctx.get('llm');
|
|
3794
|
+
if (llm === undefined) {
|
|
3795
|
+
return { outcome: 'not-processed', failureCode: 'model-directory-unavailable', retryable: true };
|
|
3796
|
+
}
|
|
3797
|
+
let reply;
|
|
3798
|
+
try {
|
|
3799
|
+
reply = await runModelCommand(command, llm, envelope.conversation, {
|
|
3800
|
+
provider: this.options.provider,
|
|
3801
|
+
model: this.options.model,
|
|
3802
|
+
}, this.options, signal, envelope.eventId);
|
|
3803
|
+
this.options.replyCommand(binding, envelope.eventId, reply);
|
|
3804
|
+
return { outcome: 'processed' };
|
|
3805
|
+
}
|
|
3806
|
+
catch (error) {
|
|
3807
|
+
if (signal.aborted || causedByUserCancellation(error))
|
|
3808
|
+
throw error;
|
|
3809
|
+
if (reply?.format === 'model-picker' && reply.fallbackText !== undefined
|
|
3810
|
+
&& error instanceof DeliveryStoreError
|
|
3811
|
+
&& (error.code === 'invalid-intent' || error.code === 'invalid-binding')) {
|
|
3812
|
+
try {
|
|
3813
|
+
this.options.replyCommand(binding, envelope.eventId, { text: reply.fallbackText, format: 'plain' });
|
|
3814
|
+
return { outcome: 'processed' };
|
|
3815
|
+
}
|
|
3816
|
+
catch (fallbackError) {
|
|
3817
|
+
return modelCommandFailure(fallbackError);
|
|
3818
|
+
}
|
|
3819
|
+
}
|
|
3820
|
+
return modelCommandFailure(error);
|
|
3821
|
+
}
|
|
3822
|
+
}
|
|
3823
|
+
if (sessionCommand !== undefined) {
|
|
3824
|
+
return await this.runSessionCommand(sessionCommand, binding, envelope, signal, markDispatching);
|
|
3825
|
+
}
|
|
3826
|
+
const imageDescriptorCount = (envelope.attachments ?? [])
|
|
3827
|
+
.filter(attachment => attachment.resourceType === 'image').length;
|
|
3828
|
+
const imageAttachments = prepared?.imageAttachments ?? [];
|
|
3829
|
+
const checkAuthorization = () => {
|
|
3830
|
+
try {
|
|
3831
|
+
return this.options.isInboundAuthorized(binding, envelope) ? 'authorized' : 'revoked';
|
|
3832
|
+
}
|
|
3833
|
+
catch {
|
|
3834
|
+
return 'check-failed';
|
|
3835
|
+
}
|
|
3836
|
+
};
|
|
3837
|
+
const preDispatchAuthorizationFailure = () => {
|
|
3838
|
+
const authorization = checkAuthorization();
|
|
3839
|
+
if (authorization === 'authorized')
|
|
3840
|
+
return undefined;
|
|
3841
|
+
return authorization === 'revoked'
|
|
3842
|
+
? { outcome: 'not-processed', failureCode: 'inbound-authorization-revoked', retryable: false }
|
|
3843
|
+
: { outcome: 'not-processed', failureCode: 'inbound-authorization-check-failed', retryable: true };
|
|
3844
|
+
};
|
|
3845
|
+
if (imageAttachments.length !== imageDescriptorCount
|
|
3846
|
+
|| (imageDescriptorCount > 0 && prepared?.modelRoute === undefined)) {
|
|
3847
|
+
return { outcome: 'not-processed', failureCode: 'image-preparation-missing', retryable: false };
|
|
3848
|
+
}
|
|
3849
|
+
if (imageDescriptorCount > 0) {
|
|
3850
|
+
const authorizationFailure = preDispatchAuthorizationFailure();
|
|
3851
|
+
if (authorizationFailure !== undefined)
|
|
3852
|
+
return authorizationFailure;
|
|
3853
|
+
}
|
|
3854
|
+
const content = [
|
|
3855
|
+
...(envelope.text === '' ? [] : [{ type: 'text', text: envelope.text }]),
|
|
3856
|
+
...imageAttachments.map(attachment => ({ type: 'image', attachment })),
|
|
3857
|
+
];
|
|
3858
|
+
if (content.length === 0) {
|
|
3859
|
+
return { outcome: 'not-processed', failureCode: 'inbound-content-empty', retryable: false };
|
|
3860
|
+
}
|
|
3861
|
+
if (markDispatching === undefined) {
|
|
3862
|
+
return { outcome: 'not-processed', failureCode: 'dispatch-gate-unavailable', retryable: true };
|
|
3863
|
+
}
|
|
3864
|
+
// Persist owner feedback before model/session preparation, which may be
|
|
3865
|
+
// unavailable independently. The ordinary Inbox still proceeds to Agent.
|
|
3866
|
+
try {
|
|
3867
|
+
await this.options.dispatchNaturalObjectiveFeedback(binding, envelope);
|
|
3868
|
+
}
|
|
3869
|
+
catch {
|
|
3870
|
+
this.ctx.logger.warn('assistant-delivery: natural objective intent could not be prepared; continuing ordinary Agent turn');
|
|
3871
|
+
}
|
|
3872
|
+
const agents = this.ctx.get('agents');
|
|
3873
|
+
const sessions = this.ctx.get('sessions');
|
|
3874
|
+
if (agents === undefined || sessions === undefined) {
|
|
3875
|
+
return { outcome: 'not-processed', failureCode: 'agent-runtime-unavailable', retryable: true };
|
|
3876
|
+
}
|
|
3877
|
+
const restart = this.options.restart;
|
|
3878
|
+
const continuationTask = restartContinuation === undefined ? undefined : restart?.store.getTask(restartContinuation.inboxId);
|
|
3879
|
+
if (restartContinuation !== undefined && continuationTask?.model === undefined)
|
|
3880
|
+
throw new Error('assistant-delivery: restart model is not frozen');
|
|
3881
|
+
const persistedSelection = restartContinuation === undefined ? this.options.getModelSelection(envelope.conversation) : undefined;
|
|
3882
|
+
const requestedRoute = toModelRoute(persistedSelection
|
|
3883
|
+
?? continuationTask?.model ?? prepared?.modelRoute
|
|
3884
|
+
?? { provider: this.options.provider, model: this.options.model });
|
|
3885
|
+
const resolvedRoute = await this.resolveExecutionRoute(envelope.conversation, persistedSelection, requestedRoute, signal);
|
|
3886
|
+
if ('retry' in resolvedRoute) {
|
|
3887
|
+
return { outcome: 'not-processed', failureCode: 'model-selection-changed-before-dispatch', retryable: true };
|
|
3888
|
+
}
|
|
3889
|
+
const selectedRoute = resolvedRoute.route;
|
|
3890
|
+
const selected = agentSelection(selectedRoute);
|
|
3891
|
+
let handle;
|
|
3892
|
+
let dispatched = false;
|
|
3893
|
+
let acceptance;
|
|
3894
|
+
let foregroundExecution;
|
|
3895
|
+
let foregroundTurn;
|
|
3896
|
+
let terminationCause;
|
|
3897
|
+
let removeAcceptanceRequest;
|
|
3898
|
+
let acceptanceSucceeded = false;
|
|
3899
|
+
let completionPending = false;
|
|
3900
|
+
let goalContinuation;
|
|
3901
|
+
let goalContinuationQuiescent = true;
|
|
3902
|
+
let removeAbort;
|
|
3903
|
+
let removeProgress;
|
|
3904
|
+
let progressOpen = true;
|
|
3905
|
+
let restartRun;
|
|
3906
|
+
let restartCheckpoint;
|
|
3907
|
+
let progressQueue = Promise.resolve();
|
|
3908
|
+
let progressTerminal = false;
|
|
3909
|
+
const drainProgress = async () => {
|
|
3910
|
+
const control = this.activeSessionControls.get(binding.sessionId);
|
|
3911
|
+
// `/new` and `/stop` abandon presentation follow-through so user-initiated
|
|
3912
|
+
// session resets do not stall on a wedged adapter progress stream.
|
|
3913
|
+
if (control?.command !== undefined)
|
|
3914
|
+
return;
|
|
3915
|
+
let timeout;
|
|
3916
|
+
try {
|
|
3917
|
+
await Promise.race([
|
|
3918
|
+
progressQueue,
|
|
3919
|
+
...(control === undefined ? [] : [control.cancelRequested]),
|
|
3920
|
+
new Promise(resolve => {
|
|
3921
|
+
timeout = setTimeout(resolve, 5_000);
|
|
3922
|
+
timeout.unref?.();
|
|
3923
|
+
}),
|
|
3924
|
+
]);
|
|
3925
|
+
}
|
|
3926
|
+
finally {
|
|
3927
|
+
if (timeout !== undefined)
|
|
3928
|
+
clearTimeout(timeout);
|
|
3929
|
+
}
|
|
3930
|
+
};
|
|
3931
|
+
// WP19 stage 2c: only turns that claimed this inbound message (or one of its
|
|
3932
|
+
// automatic completion notices) are foreground. Native Goal continuation
|
|
3933
|
+
// rounds keep this listener attached until the fence settles, and a turn
|
|
3934
|
+
// that was already running before the claim also reaches it; both are
|
|
3935
|
+
// background. Events without `data.turn` inherit the latest opened turn.
|
|
3936
|
+
const foregroundTurns = new Set();
|
|
3937
|
+
let currentSessionTurn;
|
|
3938
|
+
const claimForegroundTurn = (turn) => {
|
|
3939
|
+
foregroundTurn = turn;
|
|
3940
|
+
foregroundTurns.add(turn);
|
|
3941
|
+
};
|
|
3942
|
+
const publishProgress = (update, origin = 'foreground') => {
|
|
3943
|
+
const terminal = update.kind === 'completed' || update.kind === 'failed' || update.kind === 'paused';
|
|
3944
|
+
if ((!progressOpen && !terminal) || progressTerminal)
|
|
3945
|
+
return;
|
|
3946
|
+
if (terminal)
|
|
3947
|
+
progressTerminal = true;
|
|
3948
|
+
const publish = async () => {
|
|
3949
|
+
if ((!terminal && progressTerminal) || checkAuthorization() !== 'authorized')
|
|
3950
|
+
return;
|
|
3951
|
+
await this.options.progress(binding, envelope.eventId, update, origin);
|
|
3952
|
+
};
|
|
3953
|
+
// Terminal journaling must not wait behind a slow provider's step updates.
|
|
3954
|
+
// The adapter preserves provider ordering after staging the durable result.
|
|
3955
|
+
progressQueue = (terminal
|
|
3956
|
+
? Promise.all([progressQueue, publish()]).then(() => { })
|
|
3957
|
+
: progressQueue.then(publish))
|
|
3958
|
+
// Progress is presentation-only: its provider failure must never retry an Agent turn.
|
|
3959
|
+
.catch(() => { });
|
|
3960
|
+
};
|
|
3961
|
+
try {
|
|
3962
|
+
const agentPresets = this.options.getAgentPresets();
|
|
3963
|
+
const presetId = agentPresets === undefined
|
|
3964
|
+
? binding.agentPreset
|
|
3965
|
+
: (await agentPresets.resolve(binding.agentPreset)).id;
|
|
3966
|
+
await requireWorkspace(binding.workspace);
|
|
3967
|
+
handle = await this.resumeAgent({ resumeSessionId: SessionId(binding.sessionId), signal,
|
|
3968
|
+
agentOptions: { provider: selected.provider, model: selected.model,
|
|
3969
|
+
maxTokens: this.options.maxOutputTokens },
|
|
3970
|
+
setup: async (agentCtx, preparedAgent) => {
|
|
3971
|
+
await this.setupAgent(agentCtx, preparedAgent, binding.workspace, presetId, externalPrincipalId(binding.principal), selected, agentPresets);
|
|
3972
|
+
const llm = this.ctx.get('llm');
|
|
3973
|
+
if (llm === undefined)
|
|
3974
|
+
throw new Error('assistant-delivery: llm service is required');
|
|
3975
|
+
requireAdapterToolCallProtocol(llm, selected.provider, selected.model, presetId, agentCtx.tools.schemas(preparedAgent).length);
|
|
3976
|
+
} });
|
|
3977
|
+
const agent = handle.agent;
|
|
3978
|
+
await this.reconcileNativeFullPermissionReviewer(agent.session);
|
|
3979
|
+
signal.throwIfAborted();
|
|
3980
|
+
const llm = this.ctx.get('llm');
|
|
3981
|
+
if (llm === undefined)
|
|
3982
|
+
throw new Error('assistant-delivery: llm service is required');
|
|
3983
|
+
if (agent.session.deriveMessages().some(message => contentHasImage(message.content))
|
|
3984
|
+
|| imageAttachments.length > 0) {
|
|
3985
|
+
await requireImageCapability(llm, selected.provider, selected.model, signal);
|
|
3986
|
+
}
|
|
3987
|
+
if (imageDescriptorCount > 0) {
|
|
3988
|
+
const authorizationFailure = preDispatchAuthorizationFailure();
|
|
3989
|
+
if (authorizationFailure !== undefined)
|
|
3990
|
+
return authorizationFailure;
|
|
3991
|
+
}
|
|
3992
|
+
let turnFrom = agent.session.snapshotEvents().length;
|
|
3993
|
+
const automaticCompletionTurns = new Map();
|
|
3994
|
+
const automaticCompletionToolViolations = new Set();
|
|
3995
|
+
const abort = () => {
|
|
3996
|
+
const command = this.activeSessionControls.get(binding.sessionId)?.command;
|
|
3997
|
+
agent.cancel(command === undefined
|
|
3998
|
+
? { kind: 'hook', reason: 'assistant-delivery-signal' }
|
|
3999
|
+
: { kind: 'user' });
|
|
4000
|
+
};
|
|
4001
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
4002
|
+
removeAbort = () => signal.removeEventListener('abort', abort);
|
|
4003
|
+
signal.throwIfAborted();
|
|
4004
|
+
const authorizationFailure = preDispatchAuthorizationFailure();
|
|
4005
|
+
if (authorizationFailure !== undefined)
|
|
4006
|
+
return authorizationFailure;
|
|
4007
|
+
// Mount the native-goal fences before the foreground message is queued:
|
|
4008
|
+
// an owner tool can create/resume a goal in that very first turn and the
|
|
4009
|
+
// host driver is otherwise free to claim its first round at idle.
|
|
4010
|
+
goalContinuation = this.waitForNativeGoalContinuation(binding, envelope, agent, signal);
|
|
4011
|
+
acceptance = restartContinuation === undefined ? this.options.prepareForegroundTaskAcceptance(binding, envelope) : undefined;
|
|
4012
|
+
foregroundExecution = restartContinuation?.inboxId ?? this.options.beginForegroundTaskExecution(binding, envelope);
|
|
4013
|
+
if (restart !== undefined && foregroundExecution !== undefined && restart.store.getTask(foregroundExecution) !== undefined) {
|
|
4014
|
+
if (restartContinuation !== undefined) {
|
|
4015
|
+
const checkpoint = restartContinuation.checkpoint;
|
|
4016
|
+
if (checkpoint === undefined || restartDigest(agent.session.snapshotEvents().slice(0, checkpoint.sessionEventCount)) !== checkpoint.sessionDigest
|
|
4017
|
+
|| checkpoint.continuationTextDigest !== restartDigest(restartContinuationText)
|
|
4018
|
+
|| createRestartContinuation({ continuationId: restartContinuation.id, text: restartContinuationText }).id !== checkpoint.continuationMessageId) {
|
|
4019
|
+
throw new Error('assistant-delivery: restart checkpoint does not match the persisted Session');
|
|
4020
|
+
}
|
|
4021
|
+
}
|
|
4022
|
+
restartRun = attachRestartRun({ agent, inboxId: foregroundExecution, binding, envelope,
|
|
4023
|
+
store: restart.store, config: restart.config,
|
|
4024
|
+
isRestartSafeTool: restart.isRestartSafeTool,
|
|
4025
|
+
...(restartContinuation === undefined ? {} : { continuation: restartContinuation }),
|
|
4026
|
+
authorize: () => checkAuthorization() === 'authorized' && restart.authorizeTask(foregroundExecution),
|
|
4027
|
+
authorizeRestart: () => acceptance === undefined && !goalContinuation?.pinActiveArmedGoal()
|
|
4028
|
+
&& restart.authorizeTask(foregroundExecution),
|
|
4029
|
+
});
|
|
4030
|
+
this.restartRuns.set(agent, restartRun);
|
|
4031
|
+
}
|
|
4032
|
+
if (acceptance !== undefined || foregroundExecution !== undefined)
|
|
4033
|
+
removeAcceptanceRequest = this.ctx.on('session/event', (session, event) => {
|
|
4034
|
+
if (session !== agent.session || event.type !== 'request/header')
|
|
4035
|
+
return;
|
|
4036
|
+
// `agent/request` exposes the candidate route. The native loop writes
|
|
4037
|
+
// this header only after `llm.prepareCall()` has applied adapter
|
|
4038
|
+
// defaults such as reasoning effort, which is the route actually sent
|
|
4039
|
+
// to the provider.
|
|
4040
|
+
if (foregroundExecution !== undefined)
|
|
4041
|
+
this.options.recordForegroundExecutionModelSelection(foregroundExecution, event.data.header.config);
|
|
4042
|
+
if (acceptance !== undefined)
|
|
4043
|
+
this.options.recordForegroundTaskModelSelection(acceptance, event.data.header.config);
|
|
4044
|
+
});
|
|
4045
|
+
markDispatching();
|
|
4046
|
+
// Once the durable marker exists, even a synchronous followup failure is ambiguous:
|
|
4047
|
+
// implementations may enqueue before throwing, so no retry is safe.
|
|
4048
|
+
dispatched = true;
|
|
4049
|
+
removeProgress = this.ctx.on('session/event', (session, event) => {
|
|
4050
|
+
if (session !== agent.session)
|
|
4051
|
+
return;
|
|
4052
|
+
const eventTurn = 'turn' in event.data && typeof event.data.turn === 'number' ? event.data.turn : undefined;
|
|
4053
|
+
if (event.type === 'turn/start' || event.type === 'step/start')
|
|
4054
|
+
currentSessionTurn = eventTurn;
|
|
4055
|
+
const progressTurn = eventTurn ?? currentSessionTurn;
|
|
4056
|
+
const progressOrigin = progressTurn !== undefined && foregroundTurns.has(progressTurn)
|
|
4057
|
+
? 'foreground' : 'background';
|
|
4058
|
+
if (event.type === 'step/start') {
|
|
4059
|
+
const automaticKind = automaticCompletionTurns.get(event.data.turn);
|
|
4060
|
+
if (automaticKind !== undefined) {
|
|
4061
|
+
publishProgress({
|
|
4062
|
+
kind: 'step',
|
|
4063
|
+
text: automaticKind === 'compact' ? '正在压缩并补全回答…' : '正在自动补全回答…',
|
|
4064
|
+
});
|
|
4065
|
+
return;
|
|
4066
|
+
}
|
|
4067
|
+
}
|
|
4068
|
+
if (event.type === 'tool/call' && automaticCompletionTurns.has(event.data.turn)) {
|
|
4069
|
+
if (!automaticCompletionToolViolations.has(event.data.turn)) {
|
|
4070
|
+
automaticCompletionToolViolations.add(event.data.turn);
|
|
4071
|
+
agent.cancel({ kind: 'hook', reason: 'assistant-delivery-automatic-completion-tool-call' }, { keepInbox: true });
|
|
4072
|
+
}
|
|
4073
|
+
return;
|
|
4074
|
+
}
|
|
4075
|
+
if (event.type === 'tool/result' && automaticCompletionTurns.has(event.data.turn))
|
|
4076
|
+
return;
|
|
4077
|
+
const update = deliveryProgressFromSessionEvent(event);
|
|
4078
|
+
if (update !== undefined)
|
|
4079
|
+
publishProgress(update, progressOrigin);
|
|
4080
|
+
});
|
|
4081
|
+
publishProgress({ kind: 'started' });
|
|
4082
|
+
const message = restartContinuation === undefined ? createUserMessage({ content, source: {
|
|
4083
|
+
kind: 'delivery', channel: envelope.channel, account: envelope.account, eventId: envelope.eventId,
|
|
4084
|
+
trust: 'untrusted',
|
|
4085
|
+
} }) : createRestartContinuation({ continuationId: restartContinuation.id, text: restartContinuationText });
|
|
4086
|
+
let deliveryTurn = await this.followupTurn(agent, message, claimForegroundTurn, undefined, restartContinuation === undefined ? undefined
|
|
4087
|
+
: () => admitRestartContinuation(agent, message, { signal,
|
|
4088
|
+
authorize: () => {
|
|
4089
|
+
this.sessionLeases.assert(String(agent.session.id));
|
|
4090
|
+
if (!restart.authorize(restartContinuation))
|
|
4091
|
+
throw new Error('restart authority changed');
|
|
4092
|
+
},
|
|
4093
|
+
flush: () => sessions.flush(agent.session),
|
|
4094
|
+
onAdmitted: () => {
|
|
4095
|
+
this.sessionLeases.assert(String(agent.session.id));
|
|
4096
|
+
restart.onContinuationAdmitted(restartContinuation, String(agent.session.id));
|
|
4097
|
+
},
|
|
4098
|
+
}), signal);
|
|
4099
|
+
if (deliveryTurn !== undefined)
|
|
4100
|
+
claimForegroundTurn(deliveryTurn);
|
|
4101
|
+
else
|
|
4102
|
+
foregroundTurn = deliveryTurn;
|
|
4103
|
+
if (restartRun?.requested() !== undefined) {
|
|
4104
|
+
await this.waitForAgentIdle(agent, signal);
|
|
4105
|
+
restartCheckpoint = await restartRun.checkpoint();
|
|
4106
|
+
this.options.replyCommand(binding, envelope.eventId, {
|
|
4107
|
+
text: '已保存当前任务,准备进行维护重启;服务就绪后会自动继续,无需重新发送请求。', format: 'plain',
|
|
4108
|
+
}, `inbound:${foregroundExecution}:maintenance`);
|
|
4109
|
+
// Publish the maintenance handoff only after teardown and ready commit.
|
|
4110
|
+
return { outcome: 'processed' };
|
|
4111
|
+
}
|
|
4112
|
+
let completionKind;
|
|
4113
|
+
let automaticTurns = 0;
|
|
4114
|
+
let assembledText = '';
|
|
4115
|
+
let bestEffortText = '';
|
|
4116
|
+
while (true) {
|
|
4117
|
+
const output = finalAssistant(agent.session.snapshotEvents(), turnFrom, deliveryTurn);
|
|
4118
|
+
let addedText = false;
|
|
4119
|
+
if (output.text.trim() !== '') {
|
|
4120
|
+
if (completionKind === 'compact' || completionKind === 'regenerate') {
|
|
4121
|
+
const previousText = assembledText;
|
|
4122
|
+
addedText = output.text.trim() !== previousText.trim();
|
|
4123
|
+
if (addedText)
|
|
4124
|
+
assembledText = output.text;
|
|
4125
|
+
}
|
|
4126
|
+
else {
|
|
4127
|
+
const merged = mergeContinuationText(assembledText, output.text);
|
|
4128
|
+
assembledText = merged.text;
|
|
4129
|
+
addedText = merged.added;
|
|
4130
|
+
}
|
|
4131
|
+
bestEffortText = assembledText;
|
|
4132
|
+
}
|
|
4133
|
+
// Every exact segment crosses the persistence barrier before another paid model turn can start.
|
|
4134
|
+
if (!await sessions.flush(agent.session)) {
|
|
4135
|
+
publishProgress({ kind: 'failed', code: 'session-persistence-unavailable' });
|
|
4136
|
+
return { outcome: 'not-processed', failureCode: 'session-flush-failed', retryable: false };
|
|
4137
|
+
}
|
|
4138
|
+
signal.throwIfAborted();
|
|
4139
|
+
const cancelled = this.activeSessionControls.get(binding.sessionId)?.command;
|
|
4140
|
+
const automaticToolViolation = deliveryTurn !== undefined
|
|
4141
|
+
&& automaticCompletionToolViolations.has(deliveryTurn);
|
|
4142
|
+
if (cancelled !== undefined || (output.stopped && !automaticToolViolation)) {
|
|
4143
|
+
terminationCause = cancelled === 'new' ? 'owner-new-session' : 'owner-stop';
|
|
4144
|
+
publishProgress({ kind: 'failed', code: cancelled === 'new' ? 'new-session' : 'user-stopped' });
|
|
4145
|
+
return { outcome: 'processed' };
|
|
4146
|
+
}
|
|
4147
|
+
const finalAuthorization = checkAuthorization();
|
|
4148
|
+
if (finalAuthorization !== 'authorized') {
|
|
4149
|
+
return finalAuthorization === 'revoked'
|
|
4150
|
+
? { outcome: 'not-processed', failureCode: 'inbound-authorization-revoked', retryable: false }
|
|
4151
|
+
: { outcome: 'not-processed', failureCode: 'inbound-authorization-check-failed', retryable: false };
|
|
4152
|
+
}
|
|
4153
|
+
const currentEmpty = output.text.trim() === '';
|
|
4154
|
+
const oversized = Buffer.byteLength(assembledText, 'utf8') > this.options.maxTextBytes;
|
|
4155
|
+
const stalledRecovery = completionKind !== undefined && output.completed && !currentEmpty && !addedText;
|
|
4156
|
+
const recoverable = automaticToolViolation || output.truncated
|
|
4157
|
+
|| (output.completed && (currentEmpty || oversized || stalledRecovery));
|
|
4158
|
+
if (recoverable && deliveryTurn !== undefined && !output.hasUnpairedToolCall
|
|
4159
|
+
&& automaticTurns < this.options.maxAutoContinuationTurns) {
|
|
4160
|
+
const isLastAutomaticTurn = automaticTurns + 1 >= this.options.maxAutoContinuationTurns;
|
|
4161
|
+
const nextKind = oversized
|
|
4162
|
+
? 'compact'
|
|
4163
|
+
: assembledText.trim() === ''
|
|
4164
|
+
? 'regenerate'
|
|
4165
|
+
: isLastAutomaticTurn
|
|
4166
|
+
? 'compact'
|
|
4167
|
+
: 'continue';
|
|
4168
|
+
automaticTurns += 1;
|
|
4169
|
+
turnFrom = agent.session.snapshotEvents().length;
|
|
4170
|
+
const completionMessage = createUserMessage({
|
|
4171
|
+
content: [{
|
|
4172
|
+
type: 'text',
|
|
4173
|
+
text: automaticCompletionPrompt(nextKind, this.options.maxTextBytes, this.options.maxOutputTokens),
|
|
4174
|
+
}],
|
|
4175
|
+
source: {
|
|
4176
|
+
kind: 'assistant-delivery',
|
|
4177
|
+
form: 'notice',
|
|
4178
|
+
summary: `Automatic answer completion attempt ${automaticTurns}`,
|
|
4179
|
+
},
|
|
4180
|
+
});
|
|
4181
|
+
completionKind = nextKind;
|
|
4182
|
+
try {
|
|
4183
|
+
deliveryTurn = await this.automaticCompletionTurn(agent, completionMessage, signal, deliveryTurn, checkAuthorization, turn => { claimForegroundTurn(turn); automaticCompletionTurns.set(turn, nextKind); });
|
|
4184
|
+
}
|
|
4185
|
+
catch (error) {
|
|
4186
|
+
if (error instanceof AutomaticCompletionAuthorizationError) {
|
|
4187
|
+
return error.state === 'revoked'
|
|
4188
|
+
? { outcome: 'not-processed', failureCode: 'inbound-authorization-revoked', retryable: false }
|
|
4189
|
+
: { outcome: 'not-processed', failureCode: 'inbound-authorization-check-failed', retryable: false };
|
|
4190
|
+
}
|
|
4191
|
+
if (!(error instanceof AutomaticCompletionUnavailableError))
|
|
4192
|
+
throw error;
|
|
4193
|
+
signal.throwIfAborted();
|
|
4194
|
+
const cancellation = this.activeSessionControls.get(binding.sessionId)?.command;
|
|
4195
|
+
if (cancellation !== undefined) {
|
|
4196
|
+
terminationCause = cancellation === 'new' ? 'owner-new-session' : 'owner-stop';
|
|
4197
|
+
publishProgress({ kind: 'failed', code: cancellation === 'new' ? 'new-session' : 'user-stopped' });
|
|
4198
|
+
return { outcome: 'processed' };
|
|
4199
|
+
}
|
|
4200
|
+
const fallbackAuthorization = checkAuthorization();
|
|
4201
|
+
if (fallbackAuthorization !== 'authorized') {
|
|
4202
|
+
return fallbackAuthorization === 'revoked'
|
|
4203
|
+
? { outcome: 'not-processed', failureCode: 'inbound-authorization-revoked', retryable: false }
|
|
4204
|
+
: { outcome: 'not-processed', failureCode: 'inbound-authorization-check-failed', retryable: false };
|
|
4205
|
+
}
|
|
4206
|
+
const hasPartial = bestEffortText.trim() !== '';
|
|
4207
|
+
this.options.replyCommand(binding, envelope.eventId, {
|
|
4208
|
+
text: hasPartial
|
|
4209
|
+
? truncatedAgentReply(bestEffortText, this.options.maxTextBytes)
|
|
4210
|
+
: emptyAgentReply(this.options.maxTextBytes),
|
|
4211
|
+
format: 'markdown',
|
|
4212
|
+
});
|
|
4213
|
+
publishProgress({
|
|
4214
|
+
kind: 'failed',
|
|
4215
|
+
code: hasPartial ? AGENT_OUTPUT_TRUNCATED_CODE : AGENT_EMPTY_RESPONSE_CODE,
|
|
4216
|
+
});
|
|
4217
|
+
return { outcome: 'processed' };
|
|
4218
|
+
}
|
|
4219
|
+
continue;
|
|
4220
|
+
}
|
|
4221
|
+
if (automaticToolViolation) {
|
|
4222
|
+
const hasPartial = bestEffortText.trim() !== '';
|
|
4223
|
+
this.options.replyCommand(binding, envelope.eventId, {
|
|
4224
|
+
text: hasPartial
|
|
4225
|
+
? truncatedAgentReply(bestEffortText, this.options.maxTextBytes)
|
|
4226
|
+
: emptyAgentReply(this.options.maxTextBytes),
|
|
4227
|
+
format: 'markdown',
|
|
4228
|
+
});
|
|
4229
|
+
publishProgress({
|
|
4230
|
+
kind: 'failed',
|
|
4231
|
+
code: hasPartial ? AGENT_OUTPUT_TRUNCATED_CODE : AGENT_EMPTY_RESPONSE_CODE,
|
|
4232
|
+
});
|
|
4233
|
+
return { outcome: 'processed' };
|
|
4234
|
+
}
|
|
4235
|
+
if (output.truncated || oversized) {
|
|
4236
|
+
this.options.replyCommand(binding, envelope.eventId, {
|
|
4237
|
+
text: truncatedAgentReply(bestEffortText, this.options.maxTextBytes),
|
|
4238
|
+
format: 'markdown',
|
|
4239
|
+
});
|
|
4240
|
+
publishProgress({ kind: 'failed', code: AGENT_OUTPUT_TRUNCATED_CODE });
|
|
4241
|
+
return { outcome: 'processed' };
|
|
4242
|
+
}
|
|
4243
|
+
if (stalledRecovery) {
|
|
4244
|
+
this.options.replyCommand(binding, envelope.eventId, {
|
|
4245
|
+
text: truncatedAgentReply(bestEffortText, this.options.maxTextBytes),
|
|
4246
|
+
format: 'markdown',
|
|
4247
|
+
});
|
|
4248
|
+
publishProgress({ kind: 'failed', code: AGENT_OUTPUT_TRUNCATED_CODE });
|
|
4249
|
+
return { outcome: 'processed' };
|
|
4250
|
+
}
|
|
4251
|
+
if (!output.completed) {
|
|
4252
|
+
if (automaticTurns > 0 && bestEffortText.trim() !== '') {
|
|
4253
|
+
this.options.replyCommand(binding, envelope.eventId, {
|
|
4254
|
+
text: truncatedAgentReply(bestEffortText, this.options.maxTextBytes),
|
|
4255
|
+
format: 'markdown',
|
|
4256
|
+
});
|
|
4257
|
+
publishProgress({
|
|
4258
|
+
kind: 'failed',
|
|
4259
|
+
code: output.failureCode ?? AGENT_OUTPUT_TRUNCATED_CODE,
|
|
4260
|
+
});
|
|
4261
|
+
return { outcome: 'processed' };
|
|
4262
|
+
}
|
|
4263
|
+
publishProgress({ kind: 'failed', ...(output.failureCode === undefined ? {} : { code: output.failureCode }) });
|
|
4264
|
+
return { outcome: 'not-processed', failureCode: 'agent-turn-incomplete', retryable: false };
|
|
4265
|
+
}
|
|
4266
|
+
if (currentEmpty || assembledText.trim() === '') {
|
|
4267
|
+
// A tool-only foreground turn can arm a native goal (typically
|
|
4268
|
+
// `goal_create`); the host round driver then continues with its own
|
|
4269
|
+
// rounds and this turn has no user-facing reply text. It must not be
|
|
4270
|
+
// classified as an empty response, which would dispose the armed
|
|
4271
|
+
// continuation fence and cancel the in-flight goal round.
|
|
4272
|
+
if (output.hadToolCall && goalContinuation?.pinActiveArmedGoal()) {
|
|
4273
|
+
// Fall through to the continuation fence below instead of replying.
|
|
4274
|
+
}
|
|
4275
|
+
else {
|
|
4276
|
+
const hasPartial = bestEffortText.trim() !== '';
|
|
4277
|
+
this.options.replyCommand(binding, envelope.eventId, {
|
|
4278
|
+
text: hasPartial
|
|
4279
|
+
? truncatedAgentReply(bestEffortText, this.options.maxTextBytes)
|
|
4280
|
+
: emptyAgentReply(this.options.maxTextBytes),
|
|
4281
|
+
format: 'markdown',
|
|
4282
|
+
});
|
|
4283
|
+
publishProgress({
|
|
4284
|
+
kind: 'failed',
|
|
4285
|
+
code: hasPartial ? AGENT_OUTPUT_TRUNCATED_CODE : AGENT_EMPTY_RESPONSE_CODE,
|
|
4286
|
+
});
|
|
4287
|
+
return { outcome: 'processed' };
|
|
4288
|
+
}
|
|
4289
|
+
}
|
|
4290
|
+
break;
|
|
4291
|
+
}
|
|
4292
|
+
signal.throwIfAborted();
|
|
4293
|
+
// The foreground reply has already crossed its durable reply path.
|
|
4294
|
+
// Retain the same Agent afterwards only for the native goal driver; its
|
|
4295
|
+
// unknown result must never turn the original reply into a claim that
|
|
4296
|
+
// the business goal was achieved. A tool-only turn has no reply text.
|
|
4297
|
+
if (assembledText.trim() !== '') {
|
|
4298
|
+
const learning = await this.options.replyCompletedPreferenceTurn(agent, binding, envelope, { text: assembledText, format: 'markdown' });
|
|
4299
|
+
if (learning === 'unknown') {
|
|
4300
|
+
this.ctx.logger.warn('assistant-delivery: completed-turn preference projection is ambiguous');
|
|
4301
|
+
}
|
|
4302
|
+
}
|
|
4303
|
+
if (goalContinuation !== undefined) {
|
|
4304
|
+
goalContinuationQuiescent = await goalContinuation.settle();
|
|
4305
|
+
}
|
|
4306
|
+
signal.throwIfAborted();
|
|
4307
|
+
completionPending = true;
|
|
4308
|
+
acceptanceSucceeded = goalContinuationQuiescent;
|
|
4309
|
+
return { outcome: 'processed' };
|
|
4310
|
+
}
|
|
4311
|
+
catch (error) {
|
|
4312
|
+
if (causedByUserCancellation(error)) {
|
|
4313
|
+
terminationCause = this.activeSessionControls.get(binding.sessionId)?.command === 'new' ? 'owner-new-session' : 'owner-stop';
|
|
4314
|
+
if (handle !== undefined && !await sessions.flush(handle.agent.session)) {
|
|
4315
|
+
return { outcome: 'not-processed', failureCode: 'session-flush-failed', retryable: false };
|
|
4316
|
+
}
|
|
4317
|
+
const command = this.activeSessionControls.get(binding.sessionId)?.command;
|
|
4318
|
+
publishProgress({ kind: 'failed', code: command === 'new' ? 'new-session' : 'user-stopped' });
|
|
4319
|
+
return { outcome: 'processed' };
|
|
4320
|
+
}
|
|
4321
|
+
if (dispatched) {
|
|
4322
|
+
const timedOut = signal.reason instanceof AgentTaskTimeoutError;
|
|
4323
|
+
terminationCause = timedOut ? 'execution-timeout' : 'runtime-error';
|
|
4324
|
+
publishProgress({ kind: 'failed', ...(timedOut
|
|
4325
|
+
? { code: 'agent-task-timeout' } : {}) });
|
|
4326
|
+
// Preserve an exact durable diagnosis so the existing interruption
|
|
4327
|
+
// Outbox can notify the owner even when progress presentation failed.
|
|
4328
|
+
if (timedOut)
|
|
4329
|
+
return { outcome: 'not-processed', failureCode: 'agent-task-timeout', retryable: false };
|
|
4330
|
+
throw new Error(`assistant-delivery: Agent turn became ambiguous: ${String(error)}`, { cause: error });
|
|
4331
|
+
}
|
|
4332
|
+
if (causedByDurableIdentity(error)) {
|
|
4333
|
+
return { outcome: 'not-processed', failureCode: 'agent-identity-mismatch', retryable: false };
|
|
4334
|
+
}
|
|
4335
|
+
if (errorChainHasName(error, 'SessionFormatUnsupportedError')) {
|
|
4336
|
+
this.ctx.logger.warn(`assistant-delivery: session-format-unsupported for session ${sessionFingerprint(binding.sessionId)}`);
|
|
4337
|
+
try {
|
|
4338
|
+
this.options.replyCommand(binding, envelope.eventId, sessionFormatUnsupportedReply());
|
|
4339
|
+
// The durable reply is the only user effect. Dead-letter the original
|
|
4340
|
+
// inbound event so a legacy format cannot consume the normal retry
|
|
4341
|
+
// budget or produce a second notification.
|
|
4342
|
+
return { outcome: 'not-processed', failureCode: 'session-format-unsupported', retryable: false };
|
|
4343
|
+
}
|
|
4344
|
+
catch {
|
|
4345
|
+
// Do not mark a terminal diagnosis without its owner-authorized,
|
|
4346
|
+
// durable reply; Coordinator may retry this pre-dispatch failure.
|
|
4347
|
+
return { outcome: 'not-processed', failureCode: 'session-format-unsupported-notice-failed', retryable: true };
|
|
4348
|
+
}
|
|
4349
|
+
}
|
|
4350
|
+
if (error instanceof ImageCapabilityAdmissionError) {
|
|
4351
|
+
try {
|
|
4352
|
+
this.options.replyCommand(binding, envelope.eventId, imageCapabilityReply(error));
|
|
4353
|
+
return { outcome: 'processed' };
|
|
4354
|
+
}
|
|
4355
|
+
catch {
|
|
4356
|
+
return { outcome: 'not-processed', failureCode: 'image-capability-notice-failed', retryable: true };
|
|
4357
|
+
}
|
|
4358
|
+
}
|
|
4359
|
+
if (error instanceof AdapterToolCallProtocolError) {
|
|
4360
|
+
try {
|
|
4361
|
+
this.options.replyCommand(binding, envelope.eventId, adapterToolCallProtocolReply(error));
|
|
4362
|
+
return { outcome: 'processed' };
|
|
4363
|
+
}
|
|
4364
|
+
catch {
|
|
4365
|
+
return { outcome: 'not-processed', failureCode: 'adapter-tool-protocol-notice-failed', retryable: true };
|
|
4366
|
+
}
|
|
4367
|
+
}
|
|
4368
|
+
if (isAcceptanceConfigurationError(error)) {
|
|
4369
|
+
this.ctx.logger.warn(`assistant-delivery: acceptance-profile-missing for session ${sessionFingerprint(binding.sessionId)}: ${error instanceof Error ? error.message : String(error)}`);
|
|
4370
|
+
return { outcome: 'not-processed', failureCode: 'acceptance-profile-missing', retryable: false };
|
|
4371
|
+
}
|
|
4372
|
+
this.ctx.logger.warn(`assistant-delivery: ${sessionResumeFailureCode(error)} for session ${sessionFingerprint(binding.sessionId)}`);
|
|
4373
|
+
return { outcome: 'not-processed', failureCode: 'agent-resume-failed', retryable: true };
|
|
4374
|
+
}
|
|
4375
|
+
finally {
|
|
4376
|
+
removeAbort?.();
|
|
4377
|
+
removeAcceptanceRequest?.();
|
|
4378
|
+
removeProgress?.();
|
|
4379
|
+
progressOpen = false;
|
|
4380
|
+
let disposed = false;
|
|
4381
|
+
let maintenanceReady = false;
|
|
4382
|
+
try {
|
|
4383
|
+
disposed = await this.disposeAfterReplyBoundary(binding.sessionId, handle, () => goalContinuation?.dispose(), !goalContinuationQuiescent, restartCheckpoint === undefined && restartContinuation === undefined
|
|
4384
|
+
? goalContinuation?.teardownTimeoutMs() ?? 10_000 : 10_000);
|
|
4385
|
+
}
|
|
4386
|
+
finally {
|
|
4387
|
+
acceptanceSucceeded = acceptanceSucceeded && disposed && !signal.aborted
|
|
4388
|
+
&& (goalContinuation?.isQuiescent() ?? true);
|
|
4389
|
+
if (foregroundExecution !== undefined && restartCheckpoint === undefined) {
|
|
4390
|
+
try {
|
|
4391
|
+
const command = this.activeSessionControls.get(binding.sessionId)?.command;
|
|
4392
|
+
if (command !== undefined)
|
|
4393
|
+
terminationCause = command === 'new' ? 'owner-new-session' : 'owner-stop';
|
|
4394
|
+
else if (signal.reason instanceof AgentTaskTimeoutError)
|
|
4395
|
+
terminationCause = 'execution-timeout';
|
|
4396
|
+
else if (signal.aborted)
|
|
4397
|
+
terminationCause = 'execution-aborted';
|
|
4398
|
+
const terminal = foregroundTurn === undefined ? undefined : handle?.agent.session.snapshotEvents().findLast(event => event.type === 'turn/end' && event.data.turn === foregroundTurn);
|
|
4399
|
+
this.options.completeForegroundTaskExecution(foregroundExecution, {
|
|
4400
|
+
status: acceptanceSucceeded ? 'succeeded' : 'unknown', quiescent: acceptanceSucceeded,
|
|
4401
|
+
termination: observeNativeTermination({ producer: 'delivery-agent',
|
|
4402
|
+
reason: terminal?.type === 'turn/end' ? terminal.data.reason : undefined,
|
|
4403
|
+
cause: terminationCause, handleDisposed: disposed, completed: acceptanceSucceeded }),
|
|
4404
|
+
});
|
|
4405
|
+
}
|
|
4406
|
+
catch (error) {
|
|
4407
|
+
acceptanceSucceeded = false;
|
|
4408
|
+
this.ctx.logger.warn(`assistant-delivery: foreground execution completion failed: ${String(error)}`);
|
|
4409
|
+
}
|
|
4410
|
+
}
|
|
4411
|
+
if (restart !== undefined && restartContinuation === undefined && restartCheckpoint === undefined) {
|
|
4412
|
+
const unfinished = restartRun?.requested();
|
|
4413
|
+
if (unfinished !== undefined)
|
|
4414
|
+
restart.store.fail(unfinished.id, 'restart-checkpoint-failed');
|
|
4415
|
+
}
|
|
4416
|
+
if (restart !== undefined && restartCheckpoint !== undefined) {
|
|
4417
|
+
if (disposed && !signal.aborted && restart.authorize(restartCheckpoint)) {
|
|
4418
|
+
restart.store.ready(restartCheckpoint.id);
|
|
4419
|
+
maintenanceReady = true;
|
|
4420
|
+
}
|
|
4421
|
+
else
|
|
4422
|
+
restart.store.fail(restartCheckpoint.id, 'restart-teardown-not-quiescent');
|
|
4423
|
+
}
|
|
4424
|
+
if (restart !== undefined && restartContinuation !== undefined) {
|
|
4425
|
+
const current = restart.store.getRequest(restartContinuation.id);
|
|
4426
|
+
if (current?.status === 'resuming') {
|
|
4427
|
+
if (acceptanceSucceeded)
|
|
4428
|
+
restart.store.complete(restartContinuation.id);
|
|
4429
|
+
else
|
|
4430
|
+
restart.store.fail(restartContinuation.id, 'restart-continuation-outcome-unknown');
|
|
4431
|
+
}
|
|
4432
|
+
}
|
|
4433
|
+
restartRun?.dispose();
|
|
4434
|
+
if (acceptance !== undefined && restartCheckpoint === undefined) {
|
|
4435
|
+
try {
|
|
4436
|
+
await this.options.completeForegroundTaskAcceptance(acceptance, {
|
|
4437
|
+
status: acceptanceSucceeded ? 'succeeded' : 'unknown', quiescent: acceptanceSucceeded,
|
|
4438
|
+
});
|
|
4439
|
+
}
|
|
4440
|
+
catch (error) {
|
|
4441
|
+
this.ctx.logger.warn(`assistant-delivery: acceptance completion failed: ${String(error)}`);
|
|
4442
|
+
}
|
|
4443
|
+
}
|
|
4444
|
+
// A provider-confirmed success cannot precede the durable execution
|
|
4445
|
+
// result: teardown can still fail after the final reply was queued.
|
|
4446
|
+
if (restartCheckpoint !== undefined)
|
|
4447
|
+
publishProgress(maintenanceReady
|
|
4448
|
+
? { kind: 'paused' } : { kind: 'failed', code: 'INTERRUPTED_RESULT_UNKNOWN' });
|
|
4449
|
+
else if (completionPending)
|
|
4450
|
+
publishProgress(acceptanceSucceeded
|
|
4451
|
+
? { kind: 'completed' } : { kind: 'failed', code: 'INTERRUPTED_RESULT_UNKNOWN' });
|
|
4452
|
+
// Terminal journal admission precedes the bounded provider drain.
|
|
4453
|
+
await drainProgress();
|
|
4454
|
+
}
|
|
4455
|
+
}
|
|
4456
|
+
}
|
|
4457
|
+
}
|
|
4458
|
+
//# sourceMappingURL=agent-runtime.js.map
|