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/core/emitter.js
CHANGED
|
@@ -28,8 +28,15 @@ export class Emitter {
|
|
|
28
28
|
envelope;
|
|
29
29
|
onAudit;
|
|
30
30
|
maxSettled;
|
|
31
|
-
/**
|
|
32
|
-
|
|
31
|
+
/**
|
|
32
|
+
* 已终态 taskId → 规范化终态指纹;仅完全相同的终态允许幂等重放。
|
|
33
|
+
*
|
|
34
|
+
* 与 supervisor 的协调(3.4):supervisor 侧「拒绝终态后 log/step/running」的
|
|
35
|
+
* 第一道闸门在调度器回调入口(entry.state 守卫),本表是纵深防御 —— 淘汰
|
|
36
|
+
* (maxSettled 有界)不改变外部可见行为:迟到输出已在源头断绝,终态重放
|
|
37
|
+
* 由调度入口的 SQLite 前置回放负责、不依赖本表命中。
|
|
38
|
+
*/
|
|
39
|
+
settled = new Map();
|
|
33
40
|
seq = 0;
|
|
34
41
|
observers = new Set();
|
|
35
42
|
ring = [];
|
|
@@ -63,17 +70,42 @@ export class Emitter {
|
|
|
63
70
|
}
|
|
64
71
|
emit(msg) {
|
|
65
72
|
// —— 1. 幂等 ——
|
|
66
|
-
|
|
73
|
+
// task_snapshot/session_ack 是补取/控制回执,终态后仍必须可发。
|
|
74
|
+
// 相同终态也必须能回放(断线重发/同步拒绝重试);不同终态及后续日志仍然拒绝。
|
|
75
|
+
const identicalTerminalReplay = msg.type === 'task_status' &&
|
|
76
|
+
isTerminal(msg.status) &&
|
|
77
|
+
this.settled.get(msg.taskId) === terminalFingerprint(msg);
|
|
78
|
+
if ('taskId' in msg &&
|
|
79
|
+
this.settled.has(msg.taskId) &&
|
|
80
|
+
!identicalTerminalReplay &&
|
|
81
|
+
msg.type !== 'task_snapshot' &&
|
|
82
|
+
msg.type !== 'session_ack' &&
|
|
83
|
+
msg.type !== 'message_ack' &&
|
|
84
|
+
msg.type !== 'task_interaction_result' &&
|
|
85
|
+
msg.type !== 'interaction_url') {
|
|
67
86
|
return;
|
|
87
|
+
}
|
|
68
88
|
let out = msg;
|
|
69
89
|
if (msg.type === 'task_log') {
|
|
70
90
|
// —— 2. 脱敏(只动日志正文,不动 diff 这类产物)——
|
|
71
91
|
if (this.redactLogs)
|
|
72
92
|
out = { ...msg, data: redact(msg.data, { home: this.home }) };
|
|
73
93
|
}
|
|
94
|
+
if (out.type === 'task_message') {
|
|
95
|
+
out = {
|
|
96
|
+
...out,
|
|
97
|
+
text: this.redactLogs ? redact(out.text, { home: this.home }) : out.text,
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
if (out.type === 'task_step' && typeof out.label === 'string') {
|
|
101
|
+
// 步骤摘要同口径脱敏,并按协议上限截断(160 字符)
|
|
102
|
+
const redacted = this.redactLogs ? redact(out.label, { home: this.home }) : out.label;
|
|
103
|
+
out = { ...out, label: redacted.length > 160 ? `${redacted.slice(0, 157)}...` : redacted };
|
|
104
|
+
}
|
|
74
105
|
// 终态登记放在**发送之后**的必要之前:先记住,再发,避免重入导致重复终态
|
|
75
|
-
if (out.type === 'task_status' && isTerminal(out.status))
|
|
76
|
-
this.remember(out.taskId);
|
|
106
|
+
if (out.type === 'task_status' && isTerminal(out.status)) {
|
|
107
|
+
this.remember(out.taskId, terminalFingerprint(out));
|
|
108
|
+
}
|
|
77
109
|
// —— 4. 信封 ——
|
|
78
110
|
const payload = this.envelope
|
|
79
111
|
? toCloudEvent(out, this.envelope.source, (this.seq += 1))
|
|
@@ -105,15 +137,25 @@ export class Emitter {
|
|
|
105
137
|
}
|
|
106
138
|
this.sink(payload);
|
|
107
139
|
}
|
|
108
|
-
remember(taskId) {
|
|
140
|
+
remember(taskId, fingerprint) {
|
|
109
141
|
if (this.settled.has(taskId))
|
|
110
142
|
return;
|
|
111
|
-
this.settled.
|
|
143
|
+
this.settled.set(taskId, fingerprint);
|
|
112
144
|
while (this.settled.size > this.maxSettled) {
|
|
113
|
-
const oldest = this.settled.
|
|
145
|
+
const oldest = this.settled.keys().next().value;
|
|
114
146
|
if (oldest === undefined)
|
|
115
147
|
break;
|
|
116
148
|
this.settled.delete(oldest);
|
|
117
149
|
}
|
|
118
150
|
}
|
|
119
151
|
}
|
|
152
|
+
/** task_status 字段均为扁平值;顶层键排序避免 SQLite 重建对象时的键顺序影响“完全相同”判定。 */
|
|
153
|
+
function terminalFingerprint(msg) {
|
|
154
|
+
const normalized = {};
|
|
155
|
+
for (const key of Object.keys(msg).sort()) {
|
|
156
|
+
const value = msg[key];
|
|
157
|
+
if (value !== undefined)
|
|
158
|
+
normalized[key] = value;
|
|
159
|
+
}
|
|
160
|
+
return JSON.stringify(normalized);
|
|
161
|
+
}
|
package/dist/core/errors.js
CHANGED
|
@@ -25,6 +25,33 @@ export const BRIDGE_ERROR_CODES = [
|
|
|
25
25
|
'invalid_token', // 令牌格式非法 / 未登记 / 不匹配
|
|
26
26
|
'token_expired', // 令牌过期或已吊销
|
|
27
27
|
'insufficient_scope', // 令牌有效但 scope 不足
|
|
28
|
+
'tenant_not_supported', // 带了租户声明,但当前控制面尚未按租户分区读取
|
|
29
|
+
// —— 权限策略(1.0 Phase 2)——
|
|
30
|
+
'permission_mode_unsupported', // 本机/该工具不满足 full 运行条件(无映射、缺 external_sandbox)
|
|
31
|
+
'permission_policy_denied', // 本机策略不允许该权限组合(default 策略下请求 full、受管参数模式带自定义 args)
|
|
32
|
+
// 已尝试向 adapter 写入交互响应,但结果无法确认;必须结束回合并禁止重试,避免重复授权/重复表单提交。
|
|
33
|
+
'interaction_delivery_unknown',
|
|
34
|
+
'interaction_invalid_response',
|
|
35
|
+
'interaction_response_conflict',
|
|
36
|
+
// 单次交互等待到期且当前 options 不提供 reject_once:以 cancelled outcome 完成请求并结束回合
|
|
37
|
+
//(spec「等待状态、超时与取消」;有 reject_once 时按其原 optionId 拒绝、回合继续,不用此码)。
|
|
38
|
+
'interaction_timeout',
|
|
39
|
+
// full 模式的残余权限请求且 options 不提供 reject_once:fail closed 取消回合并结束
|
|
40
|
+
//(spec「权限与问题的组合语义」:不转交人工、不伪造 reject 选项)。
|
|
41
|
+
'interaction_denied',
|
|
42
|
+
'agent_protocol_error',
|
|
43
|
+
'idempotency_conflict',
|
|
44
|
+
// —— 会话历史(1.0)——
|
|
45
|
+
// 两者都是 410 Gone:任务曾经存在,但内容已不可完整取得,重试同一个 taskId 也不会变好。
|
|
46
|
+
'session_deleted', // taskId 命中 tombstone(内容已随 retention 删除,且永不复用)
|
|
47
|
+
'session_history_pruned', // 请求的游标落在已被 retention 裁剪的历史里,无法完整 replay
|
|
48
|
+
// 这两个早就在 task_snapshot / artifact_content 上以字符串形式发出去了,
|
|
49
|
+
// 进受控表只是把它们钉住:自由串会随文案漂,平台没法稳定分支。
|
|
50
|
+
'task_not_found', // taskId 从未存在,或不属于该租户
|
|
51
|
+
'artifact_not_found', // artifactId 未知或已淘汰
|
|
52
|
+
// conversation 创建前就拒:该工具没有任何可续接回合的通道(continuation=single-turn)。
|
|
53
|
+
// 在 message_ack 上早就用它了,这里钉住,让 run_task 的拒绝也能被程序化分支。
|
|
54
|
+
'session_not_continuable',
|
|
28
55
|
];
|
|
29
56
|
export function isBridgeErrorCode(v) {
|
|
30
57
|
return typeof v === 'string' && BRIDGE_ERROR_CODES.includes(v);
|
|
@@ -63,6 +90,22 @@ export const ERROR_HTTP_STATUS = {
|
|
|
63
90
|
invalid_token: 401,
|
|
64
91
|
token_expired: 401,
|
|
65
92
|
insufficient_scope: 403,
|
|
93
|
+
tenant_not_supported: 403,
|
|
94
|
+
permission_mode_unsupported: 400,
|
|
95
|
+
permission_policy_denied: 403,
|
|
96
|
+
interaction_delivery_unknown: 500,
|
|
97
|
+
interaction_invalid_response: 400,
|
|
98
|
+
interaction_response_conflict: 409,
|
|
99
|
+
interaction_timeout: 504,
|
|
100
|
+
interaction_denied: 403,
|
|
101
|
+
agent_protocol_error: 502,
|
|
102
|
+
idempotency_conflict: 409,
|
|
103
|
+
session_deleted: 410,
|
|
104
|
+
session_history_pruned: 410,
|
|
105
|
+
task_not_found: 404,
|
|
106
|
+
artifact_not_found: 404,
|
|
107
|
+
// 会话形态与请求不符(工具不支持多轮),换个参数就能成功 ⇒ 409 而不是 400
|
|
108
|
+
session_not_continuable: 409,
|
|
66
109
|
};
|
|
67
110
|
export function toProblem(code, opts = {}) {
|
|
68
111
|
return {
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ACP/MCP Form 的最小 schema 校验与 secret 拒绝。
|
|
3
|
+
*
|
|
4
|
+
* 只支持设计约定的扁平对象子集(type/properties/required),
|
|
5
|
+
* 不实现完整 JSON Schema;未知字段允许,但 secret 字段一律拒绝。
|
|
6
|
+
*/
|
|
7
|
+
const SECRET_KEY = /(token|secret|password|passwd|authorization|api[_-]?key|credential|private[_-]?key)/i;
|
|
8
|
+
export function findSecretKey(value, path = '') {
|
|
9
|
+
if (Array.isArray(value)) {
|
|
10
|
+
for (let i = 0; i < value.length; i += 1) {
|
|
11
|
+
const found = findSecretKey(value[i], `${path}[${i}]`);
|
|
12
|
+
if (found)
|
|
13
|
+
return found;
|
|
14
|
+
}
|
|
15
|
+
return undefined;
|
|
16
|
+
}
|
|
17
|
+
if (typeof value !== 'object' || value === null)
|
|
18
|
+
return undefined;
|
|
19
|
+
for (const [key, child] of Object.entries(value)) {
|
|
20
|
+
const next = path ? `${path}.${key}` : key;
|
|
21
|
+
if (SECRET_KEY.test(key))
|
|
22
|
+
return next;
|
|
23
|
+
const found = findSecretKey(child, next);
|
|
24
|
+
if (found)
|
|
25
|
+
return found;
|
|
26
|
+
}
|
|
27
|
+
return undefined;
|
|
28
|
+
}
|
|
29
|
+
function typeOf(value) {
|
|
30
|
+
if (value === null)
|
|
31
|
+
return 'null';
|
|
32
|
+
if (Array.isArray(value))
|
|
33
|
+
return 'array';
|
|
34
|
+
return typeof value;
|
|
35
|
+
}
|
|
36
|
+
function typeMatches(expected, value) {
|
|
37
|
+
if (Array.isArray(expected))
|
|
38
|
+
return expected.some((item) => typeMatches(item, value));
|
|
39
|
+
if (typeof expected !== 'string')
|
|
40
|
+
return true;
|
|
41
|
+
if (expected === 'integer')
|
|
42
|
+
return Number.isInteger(value);
|
|
43
|
+
if (expected === 'number')
|
|
44
|
+
return typeof value === 'number' && Number.isFinite(value);
|
|
45
|
+
return typeOf(value) === expected;
|
|
46
|
+
}
|
|
47
|
+
/** 返回错误文案;通过返回 undefined */
|
|
48
|
+
export function validateFormContent(schema, content) {
|
|
49
|
+
const secret = findSecretKey(content);
|
|
50
|
+
if (secret)
|
|
51
|
+
return `Form 不允许 secret 字段:${secret}`;
|
|
52
|
+
const required = Array.isArray(schema['required'])
|
|
53
|
+
? schema['required'].filter((key) => typeof key === 'string')
|
|
54
|
+
: [];
|
|
55
|
+
for (const key of required) {
|
|
56
|
+
if (!(key in content))
|
|
57
|
+
return `缺少必填字段:${key}`;
|
|
58
|
+
}
|
|
59
|
+
const properties = typeof schema['properties'] === 'object' && schema['properties'] !== null
|
|
60
|
+
? schema['properties']
|
|
61
|
+
: {};
|
|
62
|
+
for (const [key, value] of Object.entries(content)) {
|
|
63
|
+
const def = properties[key];
|
|
64
|
+
if (typeof def !== 'object' || def === null)
|
|
65
|
+
continue;
|
|
66
|
+
const expected = def['type'];
|
|
67
|
+
if (expected !== undefined && !typeMatches(expected, value)) {
|
|
68
|
+
return `字段类型不匹配:${key}`;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return undefined;
|
|
72
|
+
}
|
|
@@ -0,0 +1,440 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { validateFormContent } from './form-schema.js';
|
|
3
|
+
import { fullResidualPermissionOutcome } from './permission-policy.js';
|
|
4
|
+
/** interaction.payload 里的 options 数组(结构宽松解析;无则空) */
|
|
5
|
+
export function interactionPayloadOptions(payload) {
|
|
6
|
+
if (!payload || typeof payload !== 'object')
|
|
7
|
+
return undefined;
|
|
8
|
+
const raw = payload['options'];
|
|
9
|
+
if (!Array.isArray(raw))
|
|
10
|
+
return undefined;
|
|
11
|
+
return raw.filter((option) => typeof option === 'object' && option !== null);
|
|
12
|
+
}
|
|
13
|
+
function canonical(value) {
|
|
14
|
+
if (Array.isArray(value))
|
|
15
|
+
return value.map(canonical);
|
|
16
|
+
if (value && typeof value === 'object') {
|
|
17
|
+
return Object.fromEntries(Object.entries(value)
|
|
18
|
+
.filter(([, child]) => child !== undefined)
|
|
19
|
+
.sort(([a], [b]) => a.localeCompare(b))
|
|
20
|
+
.map(([key, child]) => [key, canonical(child)]));
|
|
21
|
+
}
|
|
22
|
+
return value;
|
|
23
|
+
}
|
|
24
|
+
export function fingerprintInteractionResponse(value) {
|
|
25
|
+
return createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');
|
|
26
|
+
}
|
|
27
|
+
function asRequestState(record) {
|
|
28
|
+
return record.state === 'accepted' || record.state === 'declined' ? 'resolved' : record.state;
|
|
29
|
+
}
|
|
30
|
+
/** 每个 TaskSupervisor 持有一个实例;SQLite 管状态,内存只管当前进程的交付 Promise。 */
|
|
31
|
+
export class InteractionBroker {
|
|
32
|
+
binding;
|
|
33
|
+
flights = new Map();
|
|
34
|
+
timers = new Map();
|
|
35
|
+
get isBound() {
|
|
36
|
+
return this.binding !== undefined;
|
|
37
|
+
}
|
|
38
|
+
bind(binding) {
|
|
39
|
+
if (this.binding)
|
|
40
|
+
throw new Error('InteractionBroker 已绑定');
|
|
41
|
+
this.binding = binding;
|
|
42
|
+
}
|
|
43
|
+
deps() {
|
|
44
|
+
if (!this.binding)
|
|
45
|
+
throw new Error('InteractionBroker 尚未绑定 SessionStore/Emitter');
|
|
46
|
+
return this.binding;
|
|
47
|
+
}
|
|
48
|
+
open(input) {
|
|
49
|
+
const { store, emit } = this.deps();
|
|
50
|
+
const existing = store
|
|
51
|
+
.listInteractions(input.sessionId, input.tenantId)
|
|
52
|
+
.find((item) => item.state === 'pending' || item.state === 'submitting');
|
|
53
|
+
if (existing)
|
|
54
|
+
throw new Error(`每会话只能有一个开放交互:${existing.requestId}`);
|
|
55
|
+
const expiresAt = input.expiresAt ??
|
|
56
|
+
(this.deps().defaultTimeoutMs
|
|
57
|
+
? new Date(Date.now() + this.deps().defaultTimeoutMs).toISOString()
|
|
58
|
+
: undefined);
|
|
59
|
+
const { interaction, event } = store.openInteraction({ ...input, expiresAt });
|
|
60
|
+
emit({
|
|
61
|
+
type: 'task_interaction_request',
|
|
62
|
+
taskId: input.sessionId,
|
|
63
|
+
requestId: input.requestId,
|
|
64
|
+
turnId: input.turnId,
|
|
65
|
+
kind: input.kind,
|
|
66
|
+
payload: input.payload,
|
|
67
|
+
expiresAt,
|
|
68
|
+
eventSeq: event.eventSeq,
|
|
69
|
+
});
|
|
70
|
+
if (expiresAt) {
|
|
71
|
+
const key = `${interaction.tenantId}\0${interaction.sessionId}\0${interaction.requestId}`;
|
|
72
|
+
const timer = setTimeout(() => {
|
|
73
|
+
this.timers.delete(key);
|
|
74
|
+
void this.expire(interaction);
|
|
75
|
+
}, Math.max(0, Date.parse(expiresAt) - Date.now()));
|
|
76
|
+
this.timers.set(key, timer);
|
|
77
|
+
}
|
|
78
|
+
return interaction;
|
|
79
|
+
}
|
|
80
|
+
normalize(record, msg) {
|
|
81
|
+
const payload = msg.payload ?? {};
|
|
82
|
+
if (record.kind === 'permission') {
|
|
83
|
+
const explicitOption = typeof payload['optionId'] === 'string'
|
|
84
|
+
? payload['optionId']
|
|
85
|
+
: typeof payload['option_id'] === 'string'
|
|
86
|
+
? payload['option_id']
|
|
87
|
+
: undefined;
|
|
88
|
+
const rawOptions = record.payload && typeof record.payload === 'object'
|
|
89
|
+
? record.payload['options']
|
|
90
|
+
: undefined;
|
|
91
|
+
const options = Array.isArray(rawOptions)
|
|
92
|
+
? rawOptions.filter((option) => typeof option === 'object' && option !== null)
|
|
93
|
+
: [];
|
|
94
|
+
const accepted = msg.state === 'accepted';
|
|
95
|
+
const invalid = accepted && (!explicitOption || !options.some((option) => option['optionId'] === explicitOption));
|
|
96
|
+
const outcome = accepted
|
|
97
|
+
? { outcome: 'selected', optionId: explicitOption }
|
|
98
|
+
: { outcome: 'cancelled' };
|
|
99
|
+
return {
|
|
100
|
+
fingerprint: fingerprintInteractionResponse({ kind: record.kind, outcome }),
|
|
101
|
+
answer: { optionId: accepted ? explicitOption : undefined, action: accepted ? 'accept' : msg.state === 'declined' ? 'decline' : 'cancel' },
|
|
102
|
+
resolution: accepted ? { state: msg.state, optionId: explicitOption } : { state: msg.state },
|
|
103
|
+
invalid,
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
const content = typeof payload['content'] === 'object' && payload['content'] !== null
|
|
107
|
+
? payload['content']
|
|
108
|
+
: undefined;
|
|
109
|
+
const action = msg.state === 'accepted' ? 'accept' : msg.state === 'declined' ? 'decline' : 'cancel';
|
|
110
|
+
const schema = record.payload && typeof record.payload === 'object'
|
|
111
|
+
? record.payload['requestedSchema']
|
|
112
|
+
: undefined;
|
|
113
|
+
const invalid = action === 'accept' && Boolean(validateFormContent(schema && typeof schema === 'object' ? schema : {}, content ?? {}));
|
|
114
|
+
return {
|
|
115
|
+
fingerprint: fingerprintInteractionResponse({ kind: record.kind, action, ...(action === 'accept' ? { content: content ?? {} } : {}) }),
|
|
116
|
+
answer: { action, ...(action === 'accept' ? { content: content ?? {} } : {}) },
|
|
117
|
+
resolution: {
|
|
118
|
+
action,
|
|
119
|
+
...(action === 'accept' ? { fieldNames: Object.keys(content ?? {}).sort() } : {}),
|
|
120
|
+
},
|
|
121
|
+
invalid,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
toMessage(record) {
|
|
125
|
+
return {
|
|
126
|
+
type: 'task_interaction_result',
|
|
127
|
+
taskId: record.sessionId,
|
|
128
|
+
requestId: record.requestId,
|
|
129
|
+
state: record.state,
|
|
130
|
+
requestState: record.requestState,
|
|
131
|
+
responseStatus: record.responseStatus,
|
|
132
|
+
responseId: record.responseId,
|
|
133
|
+
resultSeq: record.resultSeq,
|
|
134
|
+
resolution: record.resolution,
|
|
135
|
+
resultPayload: record.resolution,
|
|
136
|
+
errorCode: record.errorCode,
|
|
137
|
+
at: record.at,
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
emit(record) {
|
|
141
|
+
const result = this.toMessage(record);
|
|
142
|
+
this.deps().emit(result);
|
|
143
|
+
const ok = record.responseStatus === 'accepted' || record.responseStatus === 'duplicate';
|
|
144
|
+
return {
|
|
145
|
+
ok,
|
|
146
|
+
...(record.state !== 'failed' ? { state: record.state } : {}),
|
|
147
|
+
responseId: record.responseId,
|
|
148
|
+
resultSeq: record.resultSeq,
|
|
149
|
+
errorCode: record.errorCode,
|
|
150
|
+
result,
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
record(interaction, input) {
|
|
154
|
+
const result = this.deps().store.recordInteractionResult({
|
|
155
|
+
sessionId: interaction.sessionId,
|
|
156
|
+
requestId: interaction.requestId,
|
|
157
|
+
tenantId: interaction.tenantId,
|
|
158
|
+
responseId: input.responseId,
|
|
159
|
+
responseFingerprint: input.responseFingerprint,
|
|
160
|
+
responseAnchor: input.responseAnchor,
|
|
161
|
+
requestState: input.requestState ?? asRequestState(interaction),
|
|
162
|
+
responseStatus: input.responseStatus,
|
|
163
|
+
state: input.state,
|
|
164
|
+
resolution: input.resolution,
|
|
165
|
+
errorCode: input.errorCode,
|
|
166
|
+
transition: input.transition,
|
|
167
|
+
});
|
|
168
|
+
if (['resolved', 'failed', 'expired', 'cancelled'].includes(result.requestState)) {
|
|
169
|
+
const key = `${result.tenantId}\0${result.sessionId}\0${result.requestId}`;
|
|
170
|
+
const timer = this.timers.get(key);
|
|
171
|
+
if (timer)
|
|
172
|
+
clearTimeout(timer);
|
|
173
|
+
this.timers.delete(key);
|
|
174
|
+
}
|
|
175
|
+
const outcome = this.emit(result);
|
|
176
|
+
if (result.requestState === 'resolved' && result.responseStatus === 'accepted') {
|
|
177
|
+
this.deps().onResolved?.(result.sessionId, result.requestId);
|
|
178
|
+
}
|
|
179
|
+
if (result.requestState === 'failed' && result.errorCode === 'interaction_delivery_unknown') {
|
|
180
|
+
this.deps().onFailed?.(result.sessionId, result.requestId);
|
|
181
|
+
}
|
|
182
|
+
return outcome;
|
|
183
|
+
}
|
|
184
|
+
conflict(interaction, msg, fingerprint, anchor) {
|
|
185
|
+
return this.record(interaction, {
|
|
186
|
+
responseId: msg.responseId,
|
|
187
|
+
responseFingerprint: fingerprint,
|
|
188
|
+
responseAnchor: anchor,
|
|
189
|
+
responseStatus: 'invalid',
|
|
190
|
+
state: 'failed',
|
|
191
|
+
resolution: interaction.resolution,
|
|
192
|
+
errorCode: 'interaction_response_conflict',
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
respond(msg) {
|
|
196
|
+
const { store } = this.deps();
|
|
197
|
+
const interaction = store.getInteraction(msg.taskId, msg.requestId, msg.tenantId ?? 'default');
|
|
198
|
+
if (!interaction) {
|
|
199
|
+
return Promise.resolve({ ok: false, errorCode: 'interaction_not_found' });
|
|
200
|
+
}
|
|
201
|
+
const normalized = this.normalize(interaction, msg);
|
|
202
|
+
const receipt = store.getInteractionResponseReceipt(msg.taskId, msg.requestId, msg.responseId, normalized.fingerprint, interaction.tenantId);
|
|
203
|
+
if (receipt)
|
|
204
|
+
return Promise.resolve(this.emit(receipt));
|
|
205
|
+
const anchor = store.getInteractionResponseAnchor(msg.taskId, msg.requestId, msg.responseId, interaction.tenantId);
|
|
206
|
+
if (anchor) {
|
|
207
|
+
if (anchor.responseFingerprint === normalized.fingerprint)
|
|
208
|
+
return Promise.resolve(this.emit(anchor));
|
|
209
|
+
return Promise.resolve(this.conflict(interaction, msg, normalized.fingerprint, false));
|
|
210
|
+
}
|
|
211
|
+
const flightKey = `${interaction.tenantId}\0${interaction.sessionId}\0${interaction.requestId}\0${msg.responseId}`;
|
|
212
|
+
const inFlight = this.flights.get(flightKey);
|
|
213
|
+
if (inFlight) {
|
|
214
|
+
if (interaction.responseFingerprint !== normalized.fingerprint) {
|
|
215
|
+
return Promise.resolve(this.conflict(interaction, msg, normalized.fingerprint, false));
|
|
216
|
+
}
|
|
217
|
+
return inFlight.then((outcome) => ({ ...outcome, deliveredNow: false }));
|
|
218
|
+
}
|
|
219
|
+
const state = asRequestState(interaction);
|
|
220
|
+
if (state === 'pending') {
|
|
221
|
+
if (normalized.invalid) {
|
|
222
|
+
return Promise.resolve(this.record(interaction, {
|
|
223
|
+
responseId: msg.responseId,
|
|
224
|
+
responseFingerprint: normalized.fingerprint,
|
|
225
|
+
responseAnchor: true,
|
|
226
|
+
responseStatus: 'invalid',
|
|
227
|
+
state: 'failed',
|
|
228
|
+
requestState: 'pending',
|
|
229
|
+
errorCode: 'interaction_invalid_response',
|
|
230
|
+
}));
|
|
231
|
+
}
|
|
232
|
+
store.beginInteractionResponse({
|
|
233
|
+
sessionId: interaction.sessionId,
|
|
234
|
+
requestId: interaction.requestId,
|
|
235
|
+
tenantId: interaction.tenantId,
|
|
236
|
+
responseId: msg.responseId,
|
|
237
|
+
responseFingerprint: normalized.fingerprint,
|
|
238
|
+
});
|
|
239
|
+
const flight = this.deliver(interaction, msg, normalized).finally(() => this.flights.delete(flightKey));
|
|
240
|
+
this.flights.set(flightKey, flight);
|
|
241
|
+
return flight;
|
|
242
|
+
}
|
|
243
|
+
const same = (state === 'submitting' ? interaction.responseFingerprint : interaction.resolvedFingerprint) === normalized.fingerprint;
|
|
244
|
+
if (state === 'submitting' || state === 'resolved') {
|
|
245
|
+
return Promise.resolve(this.record(interaction, {
|
|
246
|
+
responseId: msg.responseId,
|
|
247
|
+
responseFingerprint: normalized.fingerprint,
|
|
248
|
+
responseAnchor: true,
|
|
249
|
+
responseStatus: same ? 'duplicate' : 'invalid',
|
|
250
|
+
state: same ? msg.state : 'failed',
|
|
251
|
+
requestState: state,
|
|
252
|
+
resolution: same ? normalized.resolution : interaction.resolution,
|
|
253
|
+
errorCode: same ? undefined : 'interaction_response_conflict',
|
|
254
|
+
}));
|
|
255
|
+
}
|
|
256
|
+
if (state === 'failed') {
|
|
257
|
+
return Promise.resolve(this.record(interaction, {
|
|
258
|
+
responseId: msg.responseId,
|
|
259
|
+
responseFingerprint: normalized.fingerprint,
|
|
260
|
+
responseAnchor: true,
|
|
261
|
+
responseStatus: 'invalid',
|
|
262
|
+
state: 'failed',
|
|
263
|
+
requestState: 'failed',
|
|
264
|
+
resolution: interaction.resolution,
|
|
265
|
+
errorCode: 'interaction_delivery_unknown',
|
|
266
|
+
}));
|
|
267
|
+
}
|
|
268
|
+
return Promise.resolve(this.record(interaction, {
|
|
269
|
+
responseId: msg.responseId,
|
|
270
|
+
responseFingerprint: normalized.fingerprint,
|
|
271
|
+
responseAnchor: true,
|
|
272
|
+
responseStatus: 'late',
|
|
273
|
+
state: state === 'expired' ? 'expired' : 'cancelled',
|
|
274
|
+
requestState: state,
|
|
275
|
+
resolution: interaction.resolution,
|
|
276
|
+
errorCode: state === 'expired' ? 'interaction_expired' : 'interaction_already_resolved',
|
|
277
|
+
}));
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* 单次等待到期(spec「等待状态、超时与取消」):
|
|
281
|
+
* - permission 且 options 真实提供 reject_once → 以**原 optionId** 拒绝这一次(deliver accept+optionId),
|
|
282
|
+
* 回合继续,走 onResolved 恢复 supervisor Entry;
|
|
283
|
+
* - 否则(含 Form 超时映射 cancel)→ 以 cancelled outcome 完成原请求并结束回合(onExpired,
|
|
284
|
+
* 调用方按 interaction_timeout 结算);不得伪造 reject_once 或 optionId;
|
|
285
|
+
* - 交付失败 → interaction_delivery_unknown(onFailed),与响应交付失败同一条路径。
|
|
286
|
+
*/
|
|
287
|
+
async expire(interaction) {
|
|
288
|
+
const current = this.deps().store.getInteraction(interaction.sessionId, interaction.requestId, interaction.tenantId);
|
|
289
|
+
if (!current || current.state !== 'pending')
|
|
290
|
+
return;
|
|
291
|
+
const answer = this.expiryAnswer(interaction);
|
|
292
|
+
const delivered = await this.deps()
|
|
293
|
+
.deliver(interaction.sessionId, interaction.requestId, answer)
|
|
294
|
+
.catch(() => false);
|
|
295
|
+
if (!delivered) {
|
|
296
|
+
this.record(current, {
|
|
297
|
+
responseStatus: 'invalid',
|
|
298
|
+
state: 'failed',
|
|
299
|
+
requestState: 'failed',
|
|
300
|
+
errorCode: 'interaction_delivery_unknown',
|
|
301
|
+
transition: { state: 'failed', resultPayload: { errorCode: 'interaction_delivery_unknown' } },
|
|
302
|
+
});
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
const rejectOutcome = 'optionId' in answer ? answer : undefined;
|
|
306
|
+
this.record(current, {
|
|
307
|
+
state: 'expired',
|
|
308
|
+
requestState: 'expired',
|
|
309
|
+
resolution: rejectOutcome
|
|
310
|
+
? { reason: 'interaction_timeout', optionId: rejectOutcome.optionId }
|
|
311
|
+
: { reason: 'interaction_timeout' },
|
|
312
|
+
errorCode: 'interaction_expired',
|
|
313
|
+
transition: {
|
|
314
|
+
state: 'expired',
|
|
315
|
+
resolution: rejectOutcome
|
|
316
|
+
? { reason: 'interaction_timeout', optionId: rejectOutcome.optionId }
|
|
317
|
+
: { reason: 'interaction_timeout' },
|
|
318
|
+
resultPayload: rejectOutcome
|
|
319
|
+
? { reason: 'interaction_timeout', optionId: rejectOutcome.optionId }
|
|
320
|
+
: { reason: 'interaction_timeout' },
|
|
321
|
+
},
|
|
322
|
+
});
|
|
323
|
+
if (rejectOutcome)
|
|
324
|
+
this.deps().onResolved?.(current.sessionId, current.requestId);
|
|
325
|
+
else
|
|
326
|
+
this.deps().onExpired?.(current.sessionId, current.requestId);
|
|
327
|
+
}
|
|
328
|
+
/** 到期时应交付给 adapter 的答复:有 reject_once 选原 optionId,否则 cancel(不伪造选项)。 */
|
|
329
|
+
expiryAnswer(interaction) {
|
|
330
|
+
if (interaction.kind === 'permission') {
|
|
331
|
+
const outcome = fullResidualPermissionOutcome(interactionPayloadOptions(interaction.payload));
|
|
332
|
+
if ('optionId' in outcome)
|
|
333
|
+
return { action: 'accept', optionId: outcome.optionId };
|
|
334
|
+
}
|
|
335
|
+
return { action: 'cancel' };
|
|
336
|
+
}
|
|
337
|
+
async deliver(interaction, msg, normalized) {
|
|
338
|
+
let delivered = false;
|
|
339
|
+
try {
|
|
340
|
+
delivered = await this.deps().deliver(msg.taskId, msg.requestId, normalized.answer);
|
|
341
|
+
}
|
|
342
|
+
catch {
|
|
343
|
+
delivered = false;
|
|
344
|
+
}
|
|
345
|
+
if (!delivered) {
|
|
346
|
+
const outcome = this.record(interaction, {
|
|
347
|
+
responseId: msg.responseId,
|
|
348
|
+
responseFingerprint: normalized.fingerprint,
|
|
349
|
+
responseAnchor: true,
|
|
350
|
+
responseStatus: 'invalid',
|
|
351
|
+
state: 'failed',
|
|
352
|
+
requestState: 'failed',
|
|
353
|
+
errorCode: 'interaction_delivery_unknown',
|
|
354
|
+
transition: {
|
|
355
|
+
state: 'failed',
|
|
356
|
+
responseId: msg.responseId,
|
|
357
|
+
responseFingerprint: normalized.fingerprint,
|
|
358
|
+
resultPayload: { errorCode: 'interaction_delivery_unknown' },
|
|
359
|
+
},
|
|
360
|
+
});
|
|
361
|
+
return { ...outcome, deliveryFailed: true };
|
|
362
|
+
}
|
|
363
|
+
const outcome = this.record(interaction, {
|
|
364
|
+
responseId: msg.responseId,
|
|
365
|
+
responseFingerprint: normalized.fingerprint,
|
|
366
|
+
responseAnchor: true,
|
|
367
|
+
responseStatus: 'accepted',
|
|
368
|
+
state: msg.state,
|
|
369
|
+
requestState: 'resolved',
|
|
370
|
+
resolution: normalized.resolution,
|
|
371
|
+
transition: {
|
|
372
|
+
state: 'resolved',
|
|
373
|
+
responseId: msg.responseId,
|
|
374
|
+
responseFingerprint: normalized.fingerprint,
|
|
375
|
+
resolvedFingerprint: normalized.fingerprint,
|
|
376
|
+
resolution: normalized.resolution,
|
|
377
|
+
resultPayload: normalized.resolution,
|
|
378
|
+
},
|
|
379
|
+
});
|
|
380
|
+
return { ...outcome, deliveredNow: true };
|
|
381
|
+
}
|
|
382
|
+
/** 回合终态同步关闭开放交互,不再次调用 adapter,也不留假 pending。 */
|
|
383
|
+
cancelRequest(taskId, tenantId, requestId) {
|
|
384
|
+
if (!this.isBound)
|
|
385
|
+
return;
|
|
386
|
+
const interaction = this.deps().store.getInteraction(taskId, requestId, tenantId);
|
|
387
|
+
if (!interaction)
|
|
388
|
+
return;
|
|
389
|
+
if (interaction.state === 'pending') {
|
|
390
|
+
const resolution = { reason: 'turn_cancelled' };
|
|
391
|
+
this.record(interaction, {
|
|
392
|
+
state: 'cancelled',
|
|
393
|
+
requestState: 'cancelled',
|
|
394
|
+
resolution,
|
|
395
|
+
errorCode: 'cancelled',
|
|
396
|
+
transition: { state: 'cancelled', resolution, resultPayload: resolution },
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
else if (interaction.state === 'submitting') {
|
|
400
|
+
this.record(interaction, {
|
|
401
|
+
responseId: interaction.responseId,
|
|
402
|
+
responseFingerprint: interaction.responseFingerprint,
|
|
403
|
+
responseAnchor: true,
|
|
404
|
+
responseStatus: 'invalid',
|
|
405
|
+
state: 'failed',
|
|
406
|
+
requestState: 'failed',
|
|
407
|
+
errorCode: 'interaction_delivery_unknown',
|
|
408
|
+
transition: {
|
|
409
|
+
state: 'failed',
|
|
410
|
+
responseId: interaction.responseId,
|
|
411
|
+
responseFingerprint: interaction.responseFingerprint,
|
|
412
|
+
resultPayload: { errorCode: 'interaction_delivery_unknown' },
|
|
413
|
+
},
|
|
414
|
+
});
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
/** Outbox 溢出/重连后的兜底:只重放持久快照,不产生新 occurrence。 */
|
|
418
|
+
replayRecoverable() {
|
|
419
|
+
const { store } = this.deps();
|
|
420
|
+
for (const session of store.listAllSessions()) {
|
|
421
|
+
for (const interaction of store.listInteractions(session.sessionId, session.tenantId)) {
|
|
422
|
+
if (interaction.state === 'pending' || interaction.state === 'submitting') {
|
|
423
|
+
this.deps().emit({
|
|
424
|
+
type: 'task_interaction_request',
|
|
425
|
+
taskId: interaction.sessionId,
|
|
426
|
+
requestId: interaction.requestId,
|
|
427
|
+
turnId: interaction.turnId,
|
|
428
|
+
kind: interaction.kind,
|
|
429
|
+
payload: interaction.payload,
|
|
430
|
+
expiresAt: interaction.expiresAt,
|
|
431
|
+
eventSeq: interaction.requestEventSeq,
|
|
432
|
+
});
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
for (const result of store.listLatestInteractionResults(session.sessionId, session.tenantId)) {
|
|
436
|
+
this.deps().emit(this.toMessage(result));
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
}
|