agent-bridge-service 0.2.3 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +104 -140
- package/README.md +508 -35
- package/README.zh-CN.md +443 -33
- package/assets/agent-icons/agy.svg +27 -0
- package/dist/adapters/acp-auth.js +51 -0
- package/dist/adapters/acp-codebuddy.js +507 -0
- package/dist/adapters/agent-adapters.js +466 -46
- package/dist/adapters/claude-stream.js +159 -0
- package/dist/adapters/codex-app-server.js +310 -0
- package/dist/adapters/host-env.js +48 -0
- package/dist/adapters/mcp-elicitation.js +148 -0
- package/dist/adapters/mcp-host.js +70 -0
- package/dist/adapters/step-parsers.js +583 -0
- package/dist/app/bootstrap.js +163 -74
- package/dist/app/claude-resident.js +204 -0
- package/dist/app/conversation.js +639 -0
- package/dist/app/service-gate.js +1 -1
- package/dist/app/session.js +425 -14
- package/dist/app/task-dispatch.js +883 -7
- package/dist/app/task-registry.js +168 -0
- package/dist/cli/dispatch.js +4 -0
- package/dist/cli/flags.js +11 -0
- package/dist/cli/help.js +25 -7
- package/dist/cli/panel.js +334 -0
- package/dist/cli/render.js +2 -0
- package/dist/commands/approvals.js +80 -0
- package/dist/commands/connect.js +122 -4
- package/dist/commands/daemon-service.js +81 -0
- package/dist/commands/daemon.js +269 -6
- package/dist/commands/logout.js +13 -10
- package/dist/commands/serve.js +98 -12
- package/dist/commands/sessions.js +106 -0
- package/dist/core/ansi.js +5 -0
- package/dist/core/artifact-extract.js +158 -0
- package/dist/core/artifact-transfer.js +583 -0
- package/dist/core/device-identity.js +22 -0
- package/dist/core/emitter.js +50 -8
- package/dist/core/errors.js +43 -0
- package/dist/core/form-schema.js +72 -0
- package/dist/core/interaction-broker.js +440 -0
- package/dist/core/interaction-url.js +63 -0
- package/dist/core/partial-messages.js +99 -0
- package/dist/core/permission-ledger.js +146 -0
- package/dist/core/permission-policy.js +88 -0
- package/dist/core/port-fallback.js +22 -0
- package/dist/core/redact.js +13 -0
- package/dist/core/scan.js +12 -7
- package/dist/core/session-store.js +1632 -0
- package/dist/core/task-supervisor.js +955 -30
- package/dist/infra/atomic-file.js +111 -0
- package/dist/infra/audit.js +7 -0
- package/dist/infra/auth.js +143 -40
- package/dist/infra/config.js +511 -72
- package/dist/infra/device-identity-store.js +87 -0
- package/dist/infra/jwt.js +149 -0
- package/dist/infra/profile-lock.js +295 -0
- package/dist/infra/proxy-env.js +60 -0
- package/dist/infra/service-token.js +25 -4
- package/dist/protocol.js +298 -2
- package/dist/transport/a2a-mapping.js +206 -0
- package/dist/transport/acp-gateway-mapping.js +186 -0
- package/dist/transport/bridge-client.js +31 -22
- package/dist/transport/control-plane-page.js +820 -0
- package/dist/transport/control-plane-sessions-page.js +90 -0
- package/dist/transport/control-plane.js +923 -71
- package/dist/transport/gateway.js +1005 -0
- package/dist/transport/office-preview.js +154 -0
- package/package.json +6 -3
- package/assets/agent-icons/gemini.svg +0 -1
package/dist/app/session.js
CHANGED
|
@@ -8,26 +8,125 @@
|
|
|
8
8
|
*/
|
|
9
9
|
import { Emitter } from '../core/emitter.js';
|
|
10
10
|
import { scanAgents } from '../core/scan.js';
|
|
11
|
-
import {
|
|
11
|
+
import { defaultSupervisor } from '../core/task-supervisor.js';
|
|
12
|
+
import { assertServerMessage, ProtocolError, } from '../protocol.js';
|
|
12
13
|
import { createBridgeClient } from '../transport/bridge-client.js';
|
|
13
|
-
import { dispatchCancelTask, dispatchRunTask } from './task-dispatch.js';
|
|
14
|
+
import { dispatchCancelTask, dispatchCancelTurn, dispatchCloseSession, dispatchGetArtifact, dispatchGetTask, dispatchInteractionResponse, dispatchRunTask, resolveApproval, } from './task-dispatch.js';
|
|
15
|
+
import { dispatchConversationMessage, dispatchConversationRun, recoverConversationTurn } from './conversation.js';
|
|
16
|
+
import { authorizeService } from './service-gate.js';
|
|
17
|
+
import { DEFAULT_TENANT } from '../core/session-store.js';
|
|
18
|
+
import { DEFAULT_APPROVAL_TTL_MS } from '../core/permission-ledger.js';
|
|
19
|
+
import { ArtifactTransferManager } from '../core/artifact-transfer.js';
|
|
20
|
+
import { InteractionUrlVault } from '../core/interaction-url.js';
|
|
21
|
+
import { DEFAULT_INTERACTION_TIMEOUT_MS, DEFAULT_MAX_INTERACTIONS_PER_TASK } from '../infra/config.js';
|
|
14
22
|
export function createSession(opts) {
|
|
15
23
|
const tasks = new Map();
|
|
24
|
+
/**
|
|
25
|
+
* 常驻会话与空闲计时器必须挂在**会话级**,不能写在每条报文的 dispatchOpts 字面量里:
|
|
26
|
+
* 那样每个回合都会拿到一张新 Map,`residentSessions.get()` 永远 miss ——
|
|
27
|
+
* Claude 的常驻进程复用形同虚设,每回合都重新拉起一个进程。
|
|
28
|
+
*/
|
|
29
|
+
const residentSessions = new Map();
|
|
30
|
+
const idleTimers = new Map();
|
|
31
|
+
/**
|
|
32
|
+
* 任务调度的公共依赖。抽成函数是为了**两条通道共用同一份规则**:
|
|
33
|
+
* WS 的 `task_interaction_response` 与 HTTP 的 `POST /v1/interactions/{id}:respond`
|
|
34
|
+
* 如果各拼一份选项,鉴权/账本/审计迟早会漂。
|
|
35
|
+
*/
|
|
36
|
+
const dispatchOptions = (em) => ({
|
|
37
|
+
emitter: em,
|
|
38
|
+
tasks,
|
|
39
|
+
registry: opts.registry,
|
|
40
|
+
allowedCwd: opts.allowedCwd,
|
|
41
|
+
maxConcurrent: opts.maxConcurrent,
|
|
42
|
+
maxQueued: opts.maxQueued,
|
|
43
|
+
diffMaxBytes: opts.diffMaxBytes,
|
|
44
|
+
captureDiffByDefault: opts.captureDiffByDefault,
|
|
45
|
+
requireServiceToken: opts.requireServiceToken,
|
|
46
|
+
permissionPolicy: opts.permissionPolicy,
|
|
47
|
+
externalSandbox: opts.externalSandbox,
|
|
48
|
+
interactionEnabled: opts.interactionEnabled === true,
|
|
49
|
+
interactionTimeoutMs: opts.interactionTimeoutMs,
|
|
50
|
+
maxInteractionsPerTask: opts.maxInteractionsPerTask,
|
|
51
|
+
// 持久授权账本(1.0):默认关闭时 enabled=false,dispatch 侧既不查也不写
|
|
52
|
+
approvalLedger: {
|
|
53
|
+
enabled: opts.approvalLedgerEnabled === true,
|
|
54
|
+
tenantId: DEFAULT_TENANT,
|
|
55
|
+
ttlMs: opts.approvalTtlMs ?? DEFAULT_APPROVAL_TTL_MS,
|
|
56
|
+
},
|
|
57
|
+
artifactRootDir: opts.artifactRootDir,
|
|
58
|
+
store: opts.store,
|
|
59
|
+
interactions: defaultSupervisor.interactions,
|
|
60
|
+
approvalLookup: (input, taskId) => resolveApproval(dispatchOptions(emitter), input, taskId),
|
|
61
|
+
log: opts.log,
|
|
62
|
+
residentSessions,
|
|
63
|
+
idleTimeoutMs: opts.sessionIdleMs,
|
|
64
|
+
idleTimers,
|
|
65
|
+
// 半截消息的唯一真源是 supervisor 实例(三条流式通道都汇到那儿),这里只做读取转发
|
|
66
|
+
partialMessages: (taskId) => defaultSupervisor.listPartialMessages(taskId),
|
|
67
|
+
});
|
|
16
68
|
// client 的 onOpen/onMessage 里要用到 emitter,而 emitter 又要用到 client.send ——
|
|
17
69
|
// 互相依赖只能在"连接建立后才会回调"这个前提下用后赋值解决(与实现顺序无关,回调天然晚于同步构造)
|
|
18
70
|
let emitter;
|
|
71
|
+
const artifacts = new ArtifactTransferManager({
|
|
72
|
+
store: opts.store,
|
|
73
|
+
emit: (msg) => emitter?.emit(msg),
|
|
74
|
+
rootDir: opts.artifactRootDir,
|
|
75
|
+
});
|
|
76
|
+
const artifactsByTenant = new Map();
|
|
77
|
+
const artifactsForTenant = (tenantId) => {
|
|
78
|
+
if (tenantId === 'default')
|
|
79
|
+
return artifacts;
|
|
80
|
+
const cached = artifactsByTenant.get(tenantId);
|
|
81
|
+
if (cached)
|
|
82
|
+
return cached;
|
|
83
|
+
const manager = new ArtifactTransferManager({
|
|
84
|
+
store: opts.store,
|
|
85
|
+
emit: (msg) => emitter?.emit(msg),
|
|
86
|
+
rootDir: opts.artifactRootDir,
|
|
87
|
+
tenantId,
|
|
88
|
+
});
|
|
89
|
+
artifactsByTenant.set(tenantId, manager);
|
|
90
|
+
return manager;
|
|
91
|
+
};
|
|
92
|
+
const urls = new InteractionUrlVault();
|
|
93
|
+
try {
|
|
94
|
+
const stale = artifacts.cleanupStaleTransfers();
|
|
95
|
+
if (stale > 0)
|
|
96
|
+
opts.log('info', `[agent-bridge] 已回收 ${stale} 个超时未完成的附件上传`);
|
|
97
|
+
}
|
|
98
|
+
catch (error) {
|
|
99
|
+
opts.log('error', `[agent-bridge] 附件上传 GC 失败:${error.message}`);
|
|
100
|
+
}
|
|
19
101
|
const now = () => new Date().toISOString();
|
|
20
102
|
const client = createBridgeClient({
|
|
21
103
|
platformUrl: opts.platformUrl,
|
|
22
104
|
deviceToken: opts.deviceToken,
|
|
23
105
|
deviceId: opts.deviceId,
|
|
106
|
+
refresh: opts.refresh,
|
|
107
|
+
onTokenRefreshed: opts.onTokenRefreshed,
|
|
24
108
|
cliVersion: opts.cliVersion,
|
|
25
109
|
hostname: opts.hostname,
|
|
110
|
+
capacity: { maxTasks: opts.maxConcurrent, maxQueued: opts.maxQueued },
|
|
111
|
+
// 执行侧策略如实上报:平台据此决定能不能请求 full、要不要等交互
|
|
112
|
+
execution: {
|
|
113
|
+
permissionPolicy: opts.permissionPolicy ?? 'default',
|
|
114
|
+
externalSandbox: opts.externalSandbox === true,
|
|
115
|
+
interactionEnabled: opts.interactionEnabled === true,
|
|
116
|
+
interactionTimeoutMs: opts.interactionTimeoutMs ?? DEFAULT_INTERACTION_TIMEOUT_MS,
|
|
117
|
+
maxInteractionsPerTask: opts.maxInteractionsPerTask ?? DEFAULT_MAX_INTERACTIONS_PER_TASK,
|
|
118
|
+
approvalLedgerEnabled: opts.approvalLedgerEnabled === true,
|
|
119
|
+
},
|
|
26
120
|
log: (line) => opts.log('info', line),
|
|
27
121
|
onOpen: async () => {
|
|
122
|
+
// Outbox 已在 transport 层先 drain;这里再从 SQLite 补最新交互快照,覆盖控制消息溢出。
|
|
123
|
+
if (defaultSupervisor.interactions.isBound)
|
|
124
|
+
defaultSupervisor.interactions.replayRecoverable();
|
|
28
125
|
// 流式上报:每完成一个工具就推一条 scan_progress,平台可以边收边亮卡片
|
|
29
126
|
const items = await scanAgents({
|
|
30
127
|
fresh: true,
|
|
128
|
+
// sandbox 影响 CodeBuddy 的 executionModes:不传会让平台以为它也不能 full
|
|
129
|
+
externalSandbox: opts.externalSandbox === true,
|
|
31
130
|
onItem: (item) => emitter?.emit({ type: 'scan_progress', items: [item], scannedAt: now(), done: false }),
|
|
32
131
|
});
|
|
33
132
|
emitter?.emit({ type: 'scan_progress', items: [], scannedAt: now(), done: true });
|
|
@@ -48,14 +147,199 @@ export function createSession(opts) {
|
|
|
48
147
|
}
|
|
49
148
|
if (!emitter)
|
|
50
149
|
return;
|
|
150
|
+
const dispatchOpts = dispatchOptions(emitter);
|
|
51
151
|
if (msg.type === 'ping') {
|
|
52
152
|
emitter.emit({ type: 'pong', at: Date.now() });
|
|
53
153
|
return;
|
|
54
154
|
}
|
|
155
|
+
if (msg.type === 'get_task') {
|
|
156
|
+
dispatchGetTask(msg, dispatchOpts);
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
if (msg.type === 'get_artifact') {
|
|
160
|
+
dispatchGetArtifact(msg, dispatchOpts);
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
if (msg.type === 'close_session') {
|
|
164
|
+
dispatchCloseSession(msg, dispatchOpts);
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
if (msg.type === 'cancel_turn') {
|
|
168
|
+
dispatchCancelTurn(msg, dispatchOpts);
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
if (msg.type === 'send_message') {
|
|
172
|
+
void dispatchConversationMessage(msg, dispatchOpts).catch((error) => {
|
|
173
|
+
opts.log('error', `[agent-bridge] send_message 处理失败:${error.message}`);
|
|
174
|
+
});
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
if (msg.type === 'get_interaction_url') {
|
|
178
|
+
const gate = authorizeService(msg, 'get_interaction_url', msg.taskId, 'task:respond', opts.requireServiceToken);
|
|
179
|
+
if (!gate.ok) {
|
|
180
|
+
emitter.emit({
|
|
181
|
+
type: 'interaction_url',
|
|
182
|
+
taskId: msg.taskId,
|
|
183
|
+
requestId: msg.requestId,
|
|
184
|
+
ok: false,
|
|
185
|
+
errorCode: gate.code,
|
|
186
|
+
});
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
const lookup = urls.lookup(msg.taskId, msg.requestId);
|
|
190
|
+
const entry = lookup.entry;
|
|
191
|
+
emitter.emit({
|
|
192
|
+
type: 'interaction_url',
|
|
193
|
+
taskId: msg.taskId,
|
|
194
|
+
requestId: msg.requestId,
|
|
195
|
+
ok: Boolean(entry),
|
|
196
|
+
url: entry?.url,
|
|
197
|
+
expiresAt: entry?.expiresAt,
|
|
198
|
+
errorCode: entry
|
|
199
|
+
? undefined
|
|
200
|
+
: lookup.expired
|
|
201
|
+
? 'interaction_url_expired'
|
|
202
|
+
: 'interaction_url_not_found',
|
|
203
|
+
});
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
if (msg.type === 'task_interaction_response') {
|
|
207
|
+
void dispatchInteractionResponse(msg, dispatchOpts).catch((error) => {
|
|
208
|
+
opts.log('error', `[agent-bridge] 交互响应处理失败 ${msg.requestId}:${error.message}`);
|
|
209
|
+
});
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
if (msg.type === 'artifact_upload_start') {
|
|
213
|
+
const gate = authorizeService(msg, 'run_task', msg.taskId, 'task:create', opts.requireServiceToken);
|
|
214
|
+
if (!gate.ok) {
|
|
215
|
+
opts.log('error', `[agent-bridge] 拒绝附件上传 ${msg.taskId}:${gate.message}`);
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
try {
|
|
219
|
+
const ready = artifacts.startUpload({
|
|
220
|
+
sessionId: msg.taskId,
|
|
221
|
+
operationId: msg.operationId,
|
|
222
|
+
name: msg.name,
|
|
223
|
+
mimeType: msg.mimeType,
|
|
224
|
+
size: msg.size,
|
|
225
|
+
sha256: msg.sha256,
|
|
226
|
+
chunkSize: msg.chunkSize,
|
|
227
|
+
});
|
|
228
|
+
emitter.emit({ type: 'artifact_upload_ready', ...ready });
|
|
229
|
+
}
|
|
230
|
+
catch (error) {
|
|
231
|
+
opts.log('error', `[agent-bridge] 附件上传启动失败:${error.message}`);
|
|
232
|
+
}
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
if (msg.type === 'artifact_upload_chunk') {
|
|
236
|
+
try {
|
|
237
|
+
const ack = artifacts.writeChunk(msg);
|
|
238
|
+
emitter.emit({ type: 'artifact_upload_chunk_ack', transferId: msg.transferId, ...ack });
|
|
239
|
+
}
|
|
240
|
+
catch (error) {
|
|
241
|
+
emitter.emit({
|
|
242
|
+
type: 'artifact_upload_result',
|
|
243
|
+
transferId: msg.transferId,
|
|
244
|
+
status: 'failed',
|
|
245
|
+
errorCode: error.code ?? 'artifact_upload_failed',
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
if (msg.type === 'artifact_download_start') {
|
|
251
|
+
const gate = authorizeService(msg, 'get_task', msg.taskId, 'task:read', opts.requireServiceToken);
|
|
252
|
+
if (!gate.ok) {
|
|
253
|
+
opts.log('error', `[agent-bridge] 拒绝附件下载 ${msg.taskId}:${gate.message}`);
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
try {
|
|
257
|
+
artifacts.startDownload({
|
|
258
|
+
sessionId: msg.taskId,
|
|
259
|
+
artifactId: msg.artifactId,
|
|
260
|
+
operationId: msg.operationId,
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
catch (error) {
|
|
264
|
+
emitter.emit({
|
|
265
|
+
type: 'artifact_download_result',
|
|
266
|
+
transferId: msg.operationId,
|
|
267
|
+
status: 'failed',
|
|
268
|
+
errorCode: error.code ?? 'artifact_download_failed',
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
if (msg.type === 'artifact_download_chunk_ack') {
|
|
274
|
+
try {
|
|
275
|
+
artifacts.ackDownload(msg);
|
|
276
|
+
}
|
|
277
|
+
catch (error) {
|
|
278
|
+
emitter.emit({
|
|
279
|
+
type: 'artifact_download_result',
|
|
280
|
+
transferId: msg.transferId,
|
|
281
|
+
status: 'failed',
|
|
282
|
+
errorCode: error.code ?? 'artifact_download_failed',
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
if (msg.type === 'artifact_upload_complete') {
|
|
288
|
+
try {
|
|
289
|
+
const result = artifacts.completeUpload(msg);
|
|
290
|
+
emitter.emit({
|
|
291
|
+
type: 'artifact_upload_result',
|
|
292
|
+
transferId: msg.transferId,
|
|
293
|
+
status: 'committed',
|
|
294
|
+
artifactId: result.artifactId,
|
|
295
|
+
sha256: result.sha256 ?? msg.sha256,
|
|
296
|
+
eventSeq: result.eventSeq,
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
catch (error) {
|
|
300
|
+
emitter.emit({
|
|
301
|
+
type: 'artifact_upload_result',
|
|
302
|
+
transferId: msg.transferId,
|
|
303
|
+
status: 'failed',
|
|
304
|
+
errorCode: error.code ?? 'artifact_upload_failed',
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
if (msg.type === 'artifact_transfer_status' || msg.type === 'artifact_transfer_abort') {
|
|
310
|
+
const gate = authorizeService(msg, msg.type === 'artifact_transfer_abort' ? 'cancel_task' : 'get_task', msg.transferId, msg.type === 'artifact_transfer_abort' ? 'task:cancel' : 'task:read', opts.requireServiceToken);
|
|
311
|
+
if (!gate.ok) {
|
|
312
|
+
emitter.emit({
|
|
313
|
+
type: 'artifact_transfer_status',
|
|
314
|
+
transferId: msg.transferId,
|
|
315
|
+
state: 'failed',
|
|
316
|
+
errorCode: gate.code,
|
|
317
|
+
});
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
try {
|
|
321
|
+
if (msg.type === 'artifact_transfer_abort') {
|
|
322
|
+
artifacts.abortTransfer(msg.transferId, msg.reason);
|
|
323
|
+
}
|
|
324
|
+
else {
|
|
325
|
+
emitter.emit({ type: 'artifact_transfer_status', ...artifacts.transferStatus(msg.transferId) });
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
catch (error) {
|
|
329
|
+
emitter.emit({
|
|
330
|
+
type: 'artifact_transfer_status',
|
|
331
|
+
transferId: msg.transferId,
|
|
332
|
+
state: 'failed',
|
|
333
|
+
errorCode: error.code ?? 'internal',
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
55
338
|
if (msg.type === 'scan') {
|
|
56
339
|
const requestId = msg.requestId;
|
|
57
340
|
void scanAgents({
|
|
58
341
|
fresh: true,
|
|
342
|
+
externalSandbox: opts.externalSandbox === true,
|
|
59
343
|
onItem: (item) => emitter?.emit({
|
|
60
344
|
type: 'scan_progress',
|
|
61
345
|
requestId,
|
|
@@ -70,17 +354,6 @@ export function createSession(opts) {
|
|
|
70
354
|
});
|
|
71
355
|
return;
|
|
72
356
|
}
|
|
73
|
-
const dispatchOpts = {
|
|
74
|
-
emitter,
|
|
75
|
-
tasks,
|
|
76
|
-
allowedCwd: opts.allowedCwd,
|
|
77
|
-
maxConcurrent: opts.maxConcurrent,
|
|
78
|
-
maxQueued: opts.maxQueued,
|
|
79
|
-
diffMaxBytes: opts.diffMaxBytes,
|
|
80
|
-
captureDiffByDefault: opts.captureDiffByDefault,
|
|
81
|
-
requireServiceToken: opts.requireServiceToken,
|
|
82
|
-
log: opts.log,
|
|
83
|
-
};
|
|
84
357
|
if (msg.type === 'cancel_task')
|
|
85
358
|
return dispatchCancelTask(msg, dispatchOpts);
|
|
86
359
|
dispatchRunTask(msg, dispatchOpts);
|
|
@@ -90,12 +363,141 @@ export function createSession(opts) {
|
|
|
90
363
|
// 信封暂不由本地单方开启:平台在 hello 协商到 cloud-events 后再启用,默认保持 v1 扁平报文
|
|
91
364
|
sink: (msg) => client.send(msg),
|
|
92
365
|
});
|
|
366
|
+
if (!defaultSupervisor.interactions.isBound) {
|
|
367
|
+
defaultSupervisor.interactions.bind({
|
|
368
|
+
store: opts.store,
|
|
369
|
+
emit: (msg) => emitter?.emit(msg),
|
|
370
|
+
deliver: async (taskId, requestId, answer) => {
|
|
371
|
+
const handle = tasks.get(taskId);
|
|
372
|
+
return handle?.respondInteraction ? handle.respondInteraction(requestId, answer) : false;
|
|
373
|
+
},
|
|
374
|
+
defaultTimeoutMs: opts.interactionTimeoutMs,
|
|
375
|
+
onResolved: (taskId, requestId) => defaultSupervisor.completeInteraction(taskId, requestId),
|
|
376
|
+
onFailed: (taskId, requestId) => defaultSupervisor.failInteraction(taskId, requestId),
|
|
377
|
+
// 无 reject_once 可选的等待超时:cancelled outcome 已交付,这里取消回合并以 interaction_timeout 结算
|
|
378
|
+
onExpired: (taskId, requestId) => defaultSupervisor.expireInteraction(taskId, requestId),
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
// 容量水位(A2):每次调度状态变化广播一条 capacity_update。
|
|
382
|
+
// 平台与控制面任务共用 defaultSupervisor(都经 runner.startTask),一处订阅覆盖双通道。
|
|
383
|
+
defaultSupervisor.subscribeCapacity((s) => {
|
|
384
|
+
emitter?.emit({ type: 'capacity_update', ...s });
|
|
385
|
+
});
|
|
386
|
+
let recoveryActive = false;
|
|
387
|
+
let recoveryPumping = false;
|
|
388
|
+
const recoverySubmitted = new Set();
|
|
389
|
+
const pumpQueuedRecovery = () => {
|
|
390
|
+
if (!recoveryActive || recoveryPumping || !emitter)
|
|
391
|
+
return 0;
|
|
392
|
+
recoveryPumping = true;
|
|
393
|
+
let started = 0;
|
|
394
|
+
try {
|
|
395
|
+
for (;;) {
|
|
396
|
+
const queued = opts.store.listQueuedTurns();
|
|
397
|
+
const next = queued.find((turn) => !recoverySubmitted.has(`${turn.tenantId}\0${turn.turnId}`));
|
|
398
|
+
if (!next) {
|
|
399
|
+
if (queued.length === 0)
|
|
400
|
+
recoveryActive = false;
|
|
401
|
+
return started;
|
|
402
|
+
}
|
|
403
|
+
const capacity = defaultSupervisor.capacitySnapshot();
|
|
404
|
+
if (capacity.running >= capacity.maxTasks && capacity.queued >= capacity.maxQueued)
|
|
405
|
+
return started;
|
|
406
|
+
const session = opts.store.getSession(next.sessionId, next.tenantId);
|
|
407
|
+
const execution = next.execution;
|
|
408
|
+
if (!session || session.status !== 'running' || !execution) {
|
|
409
|
+
// 无快照不可猜参数重放;同时收口 Session,不能留下没有 active Turn 的假 queued。
|
|
410
|
+
opts.store.updateTurn(next.sessionId, next.turnId, {
|
|
411
|
+
status: 'failed',
|
|
412
|
+
stopReason: 'session_interrupted',
|
|
413
|
+
finishedAt: new Date().toISOString(),
|
|
414
|
+
}, next.tenantId);
|
|
415
|
+
if (session) {
|
|
416
|
+
const terminal = session.mode === 'task';
|
|
417
|
+
const status = terminal ? 'failed' : 'running';
|
|
418
|
+
const phase = terminal ? undefined : 'waiting_user';
|
|
419
|
+
const event = opts.store.appendEvent({
|
|
420
|
+
sessionId: next.sessionId,
|
|
421
|
+
tenantId: next.tenantId,
|
|
422
|
+
type: 'task_status',
|
|
423
|
+
payload: { status, phase, errorCode: 'internal', error: 'Turn 缺少恢复快照', turnId: next.turnId },
|
|
424
|
+
});
|
|
425
|
+
if (terminal)
|
|
426
|
+
opts.store.closeSession(next.sessionId, 'failed', 'session_interrupted', next.tenantId);
|
|
427
|
+
else
|
|
428
|
+
opts.store.updateSession(next.sessionId, { phase: 'waiting_user' }, next.tenantId);
|
|
429
|
+
emitter.emit({
|
|
430
|
+
type: 'task_status',
|
|
431
|
+
taskId: next.sessionId,
|
|
432
|
+
status,
|
|
433
|
+
phase,
|
|
434
|
+
errorCode: 'internal',
|
|
435
|
+
error: 'Turn 缺少恢复快照',
|
|
436
|
+
turnId: next.turnId,
|
|
437
|
+
eventSeq: event.eventSeq,
|
|
438
|
+
});
|
|
439
|
+
}
|
|
440
|
+
opts.log('warn', `[agent-bridge] queued Turn 缺少可恢复执行快照:${next.turnId}`);
|
|
441
|
+
continue;
|
|
442
|
+
}
|
|
443
|
+
recoverySubmitted.add(`${next.tenantId}\0${next.turnId}`);
|
|
444
|
+
if (session.mode === 'conversation') {
|
|
445
|
+
recoverConversationTurn(dispatchOptions(emitter), next);
|
|
446
|
+
}
|
|
447
|
+
else {
|
|
448
|
+
dispatchRunTask({
|
|
449
|
+
type: 'run_task',
|
|
450
|
+
taskId: next.sessionId,
|
|
451
|
+
agentType: session.agentType,
|
|
452
|
+
cwd: session.cwd,
|
|
453
|
+
args: [...execution.args],
|
|
454
|
+
prompt: execution.prompt,
|
|
455
|
+
timeoutMs: execution.timeoutMs,
|
|
456
|
+
allowInteractive: execution.allowInteractive,
|
|
457
|
+
captureDiff: execution.captureDiff,
|
|
458
|
+
permissionMode: execution.permissionMode,
|
|
459
|
+
requestedBy: execution.requestedBy,
|
|
460
|
+
purpose: execution.purpose,
|
|
461
|
+
sessionMode: session.mode,
|
|
462
|
+
}, dispatchOptions(emitter), next.turnId, next.tenantId);
|
|
463
|
+
}
|
|
464
|
+
started += 1;
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
finally {
|
|
468
|
+
recoveryPumping = false;
|
|
469
|
+
}
|
|
470
|
+
};
|
|
471
|
+
defaultSupervisor.subscribeCapacity(() => {
|
|
472
|
+
if (recoveryActive)
|
|
473
|
+
pumpQueuedRecovery();
|
|
474
|
+
});
|
|
93
475
|
return {
|
|
94
476
|
// 循环依赖的解法:client 的回调只在连接建立后触发,此时 emitter 必然已赋值
|
|
95
477
|
emitter,
|
|
96
|
-
|
|
478
|
+
registry: opts.registry,
|
|
479
|
+
store: opts.store,
|
|
480
|
+
artifacts,
|
|
481
|
+
artifactsForTenant,
|
|
482
|
+
urls,
|
|
483
|
+
close: () => {
|
|
484
|
+
// 常驻进程(Claude)不属于 supervisor,关闭会话时必须自己收干净,
|
|
485
|
+
// 否则每开一次会话就在后台留一批子进程。
|
|
486
|
+
for (const timer of idleTimers.values())
|
|
487
|
+
clearTimeout(timer);
|
|
488
|
+
idleTimers.clear();
|
|
489
|
+
for (const resident of residentSessions.values())
|
|
490
|
+
resident.close();
|
|
491
|
+
residentSessions.clear();
|
|
492
|
+
client.close();
|
|
493
|
+
opts.store.close();
|
|
494
|
+
},
|
|
97
495
|
isConnected: () => client.isOpen(),
|
|
98
496
|
activeTasks: () => tasks.size,
|
|
497
|
+
recoverQueuedTasks: () => {
|
|
498
|
+
recoveryActive = true;
|
|
499
|
+
return pumpQueuedRecovery();
|
|
500
|
+
},
|
|
99
501
|
cancelTask: (taskId) => {
|
|
100
502
|
const h = tasks.get(taskId);
|
|
101
503
|
if (!h)
|
|
@@ -103,5 +505,14 @@ export function createSession(opts) {
|
|
|
103
505
|
h.cancel();
|
|
104
506
|
return true;
|
|
105
507
|
},
|
|
508
|
+
respondInteraction: (msg) => dispatchInteractionResponse(msg, dispatchOptions(emitter)),
|
|
509
|
+
partialMessages: (taskId) => defaultSupervisor.listPartialMessages(taskId),
|
|
510
|
+
// conversation 编排(add-acp-session-memory):与 WS 通道同一份 dispatchOptions。
|
|
511
|
+
// emitter 在回调期求值(调用方发起请求时连接必然已建立),与 respondInteraction 同一前提。
|
|
512
|
+
conversation: {
|
|
513
|
+
run: (msg) => dispatchConversationRun(msg, dispatchOptions(emitter)),
|
|
514
|
+
message: (msg) => dispatchConversationMessage(msg, dispatchOptions(emitter)),
|
|
515
|
+
cancelTurn: (msg) => dispatchCancelTurn(msg, dispatchOptions(emitter)),
|
|
516
|
+
},
|
|
106
517
|
};
|
|
107
518
|
}
|