evolcore 0.0.47 → 0.0.49
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 +90 -1
- package/bin/ec-build.mjs +86 -0
- package/dist/agent-template/jobs.js +12 -4
- package/dist/agent-template/runtime.js +143 -40
- package/dist/agent-template/service.js +66 -13
- package/dist/agents/baseagent.js +60 -20
- package/dist/agents/claude-runner.js +34 -17
- package/dist/agents/codex-runner.js +36 -17
- package/dist/agents/ecagent-runner.js +7 -4
- package/dist/agents/gemini-runner.js +5 -2
- package/dist/agents/runner-types.js +5 -21
- package/dist/aun/aid/agentmd.js +5 -1
- package/dist/aun/msg/p2p.js +2 -1
- package/dist/aun/service-proxy.js +4 -2
- package/dist/build-identity.json +1 -0
- package/dist/channels/aun.js +722 -295
- package/dist/channels/daemon.js +9 -25
- package/dist/cli/aun-commands.js +86 -51
- package/dist/cli/code-stats.js +19 -8
- package/dist/cli/command-log.js +1 -1
- package/dist/cli/daemon-commands.js +44 -43
- package/dist/cli/directory.js +13 -2
- package/dist/cli/ecmsg-gateway.js +5 -2
- package/dist/cli/index.js +9 -9
- package/dist/cli/init-channel.js +4 -6
- package/dist/cli/init.js +72 -50
- package/dist/cli/invoke-command.js +1 -1
- package/dist/cli/managed-command-guard.js +2 -0
- package/dist/cli/model.js +20 -5
- package/dist/cli/provider-command.js +74 -13
- package/dist/cli/quota.js +89 -0
- package/dist/cli/role.js +62 -17
- package/dist/cli/services-command.js +1 -0
- package/dist/cli/stats.js +3 -3
- package/dist/cli/team-workspace-command.js +56 -2
- package/dist/cli/thread-command.js +16 -51
- package/dist/config/boot-log.js +3 -9
- package/dist/config/builtin-roles.js +5 -7
- package/dist/config/config-field-policy.js +71 -1
- package/dist/config/config-manager.js +13 -7
- package/dist/config/daemon-services.js +30 -3
- package/dist/config/gateway-config.js +2 -2
- package/dist/config/invoke-ipc-service.js +6 -4
- package/dist/config/peer-bind-code.js +3 -4
- package/dist/config/peer-book-store.js +62 -229
- package/dist/config/peer-book.js +26 -27
- package/dist/config/peer-role-resolver.js +16 -1
- package/dist/config/provider-identity-migration.js +4 -1
- package/dist/config/provider-ipc-service.js +56 -11
- package/dist/config/provider-menu-request.js +24 -5
- package/dist/config/provider-templates.js +127 -0
- package/dist/config/providers-config.js +67 -12
- package/dist/config/providers-management.js +477 -51
- package/dist/config/resolved-config-op.js +3 -2
- package/dist/config/role-command-service.js +248 -1
- package/dist/config/schema-migration.js +105 -4
- package/dist/core/agent-application-service.js +6 -1
- package/dist/core/agent-runtime.js +4 -0
- package/dist/core/auth/agent-delegation.js +2 -1
- package/dist/core/auth/auth-gateway.js +2 -1
- package/dist/core/auth/delegation-authorization.js +36 -26
- package/dist/core/auth/operation-authorizer.js +25 -0
- package/dist/core/auth/operation-catalog.js +37 -64
- package/dist/core/capability/providers/codex-capability-provider.js +7 -8
- package/dist/core/channel-loader.js +18 -0
- package/dist/core/command/agent-control.js +32 -0
- package/dist/core/command/cli-intent-parser.js +13 -0
- package/dist/core/command/command-handler.js +126 -87
- package/dist/core/command/menu-catalog.js +1 -0
- package/dist/core/command/menu-handler.js +67 -150
- package/dist/core/command/menu-protocol.js +31 -1
- package/dist/core/command/provider-menu.js +13 -3
- package/dist/core/command/remote-shell.js +565 -0
- package/dist/core/command/role-menu.js +47 -23
- package/dist/core/command/slash-handler.js +26 -43
- package/dist/core/command/team-workspace-items.js +81 -12
- package/dist/core/command/team-workspace-team.js +9 -71
- package/dist/core/command/topic-slash.js +9 -30
- package/dist/core/daemon-bootstrap.js +8 -1
- package/dist/core/daemon-control.js +64 -8
- package/dist/core/daemon-lifecycle.js +16 -2
- package/dist/core/evolagent-registry.js +20 -3
- package/dist/core/file-integrity/store.js +2 -0
- package/dist/core/handoff/runtime.js +37 -1
- package/dist/core/inference/text-inference.js +3 -1
- package/dist/core/initialization/service.js +11 -6
- package/dist/core/interaction-router.js +3 -0
- package/dist/core/invoke/executors/text.js +72 -19
- package/dist/core/ipc-registration.js +3 -1
- package/dist/core/message/aun-ipc-sender.js +279 -107
- package/dist/core/message/contact-admission.js +91 -6
- package/dist/core/message/contact-pending-inbound.js +113 -0
- package/dist/core/message/contact-thread-approval.js +212 -0
- package/dist/core/message/im-renderer.js +41 -2
- package/dist/core/message/message-admission.js +5 -39
- package/dist/core/message/message-bridge.js +140 -370
- package/dist/core/message/message-log.js +29 -0
- package/dist/core/message/message-queue.js +119 -15
- package/dist/core/message/message-utils.js +8 -0
- package/dist/core/message/response-engine.js +580 -134
- package/dist/core/message/send-routing.js +5 -1
- package/dist/core/model/catalog-service.js +31 -11
- package/dist/core/model/config-scope.js +6 -14
- package/dist/core/model/model-capabilities.js +22 -4
- package/dist/core/model/model-catalog.js +1 -0
- package/dist/core/model/model-diagnostics.js +19 -0
- package/dist/core/model/model-fallback.js +13 -2
- package/dist/core/ownership/owner-resolver.js +328 -50
- package/dist/core/pack-auth.js +3 -0
- package/dist/core/pack-install.js +1 -1
- package/dist/core/permission/ec-command-parser.js +106 -19
- package/dist/core/permission/protected-paths.js +6 -6
- package/dist/core/permission/services-path-acl.js +451 -0
- package/dist/core/permission/tool-policy.js +5 -1
- package/dist/core/relation/peer-identity.js +36 -1
- package/dist/core/relation/same-owner-proof.js +81 -112
- package/dist/core/session/adapters/codex-session-file-adapter.js +96 -15
- package/dist/core/session/session-file-health.js +13 -7
- package/dist/core/session/session-fs-store.js +91 -35
- package/dist/core/session/session-manager.js +68 -24
- package/dist/core/session/session-mapper.js +14 -34
- package/dist/core/session/session-transcript.js +5 -1
- package/dist/core/task/task-activity-store.js +84 -0
- package/dist/core/task/task-recovery-service.js +13 -0
- package/dist/core/thread/command-parser.js +7 -12
- package/dist/core/thread/thread-context-storage.js +3 -2
- package/dist/core/thread/thread-operation.js +2 -13
- package/dist/core/thread/thread-service.js +15 -46
- package/dist/core/thread/topic-id.js +15 -0
- package/dist/directory/owner-directory-admission.js +12 -9
- package/dist/directory/owner-directory-cache.js +64 -28
- package/dist/directory/owner-directory-markdown.js +14 -2
- package/dist/directory/owner-directory-policy.js +5 -30
- package/dist/directory/owner-directory-query-operation.js +29 -3
- package/dist/directory/owner-directory-remarks.js +11 -3
- package/dist/directory/owner-directory-request-operation.js +5 -2
- package/dist/eck/kit-renderer.js +1 -1
- package/dist/eck/message-renderer.js +112 -29
- package/dist/ecweb/basic-settings-service.js +3 -1
- package/dist/ecweb/message-context-service.js +1 -1
- package/dist/ecweb/pairing.js +4 -3
- package/dist/ecweb/providers-service.js +26 -1
- package/dist/ecweb/runtime/lifecycle.js +18 -8
- package/dist/ecweb/runtime/proxy-access.js +74 -0
- package/dist/ecweb/runtime/supervisor.js +36 -6
- package/dist/event-center/center-config.js +9 -5
- package/dist/event-center/dispatcher.js +10 -1
- package/dist/event-center/ipc-operation.js +19 -0
- package/dist/event-center/registry.js +29 -3
- package/dist/event-center/runtime.js +106 -11
- package/dist/event-center/script-runner.js +5 -5
- package/dist/index.js +96 -59
- package/dist/ipc.js +38 -3
- package/dist/outputs/authorization.js +16 -0
- package/dist/outputs/cards.js +336 -0
- package/dist/outputs/events.js +63 -0
- package/dist/outputs/protocol.js +103 -0
- package/dist/outputs/service.js +266 -0
- package/dist/paths.js +3 -0
- package/dist/proxy/manager.js +43 -13
- package/dist/services/index.js +114 -5
- package/dist/services/ipc-operation.js +88 -15
- package/dist/services/pack-manager.js +13 -1
- package/dist/services/router.js +21 -6
- package/dist/services/script-runner.js +5 -4
- package/dist/services/service-payload.js +13 -7
- package/dist/services/validation.js +1 -1
- package/dist/stats/budget.js +2 -2
- package/dist/stats/db.js +19 -0
- package/dist/stats/index.js +1 -1
- package/dist/stats/{price-resolver.js → model-resolver.js} +304 -23
- package/dist/stats/normalizer.js +2 -0
- package/dist/stats/query.js +35 -27
- package/dist/stats/quota-query.js +95 -0
- package/dist/stats/role-budget.js +5 -2
- package/dist/stats/writer.js +10 -6
- package/dist/trigger/audit.js +7 -0
- package/dist/trigger/authorization.js +105 -11
- package/dist/trigger/feedback.js +10 -0
- package/dist/trigger/history.js +37 -11
- package/dist/trigger/ipc-service.js +12 -1
- package/dist/trigger/manager.js +1 -0
- package/dist/trigger/scheduler.js +7 -5
- package/dist/trigger/script-executor.js +2 -1
- package/dist/trigger/script-sandbox.js +21 -3
- package/dist/trigger/validation.js +22 -0
- package/dist/utils/atomic-write.js +22 -8
- package/dist/utils/cross-platform.js +73 -26
- package/dist/utils/error-dict.json +94 -4
- package/dist/utils/error-utils.js +27 -4
- package/dist/utils/evolcore-version.js +36 -65
- package/dist/utils/host-info.js +100 -1
- package/dist/utils/msg-diag.js +1 -0
- package/dist/utils/npm-ops.js +43 -8
- package/dist/utils/process-introspect.js +12 -7
- package/dist/utils/process-tree.js +50 -2
- package/dist/utils/windows-shell-trust.js +2 -0
- package/dist/workbench/protocol.js +80 -0
- package/dist/workbench/service.js +359 -0
- package/ecagent/dist/types.d.ts +6 -2
- package/kits/docs/context-assembly.md +1 -1
- package/kits/docs/evolcore/INDEX.md +4 -2
- package/kits/docs/evolcore/aid.md +25 -0
- package/kits/docs/evolcore/config.md +16 -1
- package/kits/docs/evolcore/directory.md +30 -12
- package/kits/docs/evolcore/ecweb-lifecycle.md +15 -0
- package/kits/docs/evolcore/model.md +10 -0
- package/kits/docs/evolcore/msg.md +9 -0
- package/kits/docs/evolcore/peer.md +19 -65
- package/kits/docs/evolcore/provider.md +124 -4
- package/kits/docs/evolcore/quota.md +54 -0
- package/kits/docs/evolcore/role.md +83 -0
- package/kits/docs/evolcore/services.md +6 -6
- package/kits/docs/evolcore/stats.md +2 -0
- package/kits/docs/evolcore/team-workspace.md +1 -1
- package/kits/docs/evolcore/thread-chain.md +14 -15
- package/kits/docs/evolcore/tool-authorization.md +5 -0
- package/kits/docs/evolcore/trigger.md +12 -0
- package/kits/eck_message_manifest.json +12 -0
- package/kits/provider-templates.json +1213 -0
- package/kits/rules/04-relation.md +3 -3
- package/kits/schemas/_meta.json +14 -2
- package/kits/schemas/agent-config.schema.20.json +24 -0
- package/kits/schemas/contact-book.schema.4.json +52 -0
- package/kits/schemas/providers.schema.3.json +200 -0
- package/kits/skills/.switches.json +8 -0
- package/kits/skills/ability/references/calling.md +1 -1
- package/kits/skills/agent-output-cards/SKILL.md +57 -0
- package/kits/skills/ec-group/SKILL.md +2 -2
- package/kits/skills/ec-identity/SKILL.md +19 -72
- package/kits/skills/ec-provider/SKILL.md +270 -0
- package/kits/skills/ec-provider/scripts/check-model.mjs +80 -0
- package/kits/skills/ec-trigger/SKILL.md +1 -1
- package/kits/skills/thread-ops/SKILL.md +34 -21
- package/kits/templates/message-fragments/group-batch-item.md +1 -1
- package/kits/templates/message-fragments/group-batch.md +1 -1
- package/kits/templates/message-fragments/inject-default.md +1 -1
- package/kits/templates/message-fragments/interrupt-insert.md +1 -0
- package/kits/templates/message-fragments/item-group.md +1 -1
- package/kits/templates/message-fragments/item-private.md +1 -1
- package/kits/templates/message-fragments/thread-context.md +1 -1
- package/kits/templates/message-fragments/trigger-session.md +1 -1
- package/kits/templates/message-fragments/trigger-thread-check.md +1 -1
- package/kits/templates/roles/admin.json +2 -19
- package/kits/templates/roles/member.json +0 -3
- package/kits/templates/roles/visitor.json +1 -0
- package/kits/templates/system-fragments/baseagent.md +6 -0
- package/kits/templates/system-fragments/commands.md +4 -3
- package/kits/templates/system-fragments/directory-contacts.md +3 -4
- package/kits/templates/system-fragments/managed-runtime.md +1 -1
- package/kits/templates/system-fragments/relation.md +1 -1
- package/kits/templates/system-fragments/thread.md +7 -5
- package/kits/templates/system-fragments/venue.md +11 -0
- package/package.json +6 -4
- package/scripts/agent-template/inspect.mjs +50 -11
- package/scripts/agent-template/shared/common.mjs +11 -6
- package/scripts/agent-template/shared/team-schema.json +6 -4
- package/scripts/agent-template/shared/template-contract.mjs +62 -11
- package/scripts/agent-template/shared/template-package.mjs +189 -21
- package/scripts/agent-template/shared/template-runtime.mjs +54 -6
- package/scripts/agent-template/shared/template.mjs +2 -2
- package/scripts/agent-template/team-pack.mjs +52 -14
- package/dist/cli/peer.js +0 -127
- package/dist/config/peer-operation-service.js +0 -132
- package/dist/config/peer-request-service.js +0 -532
- package/dist/core/command/connect-menu.js +0 -624
|
@@ -62,12 +62,15 @@ export async function executeDirectoryRequestCommand(command, send) {
|
|
|
62
62
|
};
|
|
63
63
|
try {
|
|
64
64
|
const result = await send({ from: command.selfAid, to: command.targetAid, payload, encrypt: true });
|
|
65
|
-
if (!result.ok || !result.message_id) {
|
|
65
|
+
if (!result.ok || (!result.message_id && result.status !== 'queued')) {
|
|
66
66
|
return { ok: false, code: String(result.code ?? 'FRIEND_INVITE_FAILED'),
|
|
67
67
|
error: `向目标 ${command.targetAid} 发送加好友申请失败:${result.error ?? '未获得消息发送回执'}` };
|
|
68
68
|
}
|
|
69
69
|
return { ok: true, action: 'request', selfAid: command.selfAid, targetAid: command.targetAid,
|
|
70
|
-
status: '
|
|
70
|
+
status: result.status === 'queued' ? 'queued' : 'sent',
|
|
71
|
+
...(result.message_id ? { message_id: result.message_id } : {}),
|
|
72
|
+
...(result.outbox_id ? { outbox_id: result.outbox_id } : {}),
|
|
73
|
+
};
|
|
71
74
|
}
|
|
72
75
|
catch (error) {
|
|
73
76
|
return { ok: false, code: 'FRIEND_INVITE_FAILED',
|
package/dist/eck/kit-renderer.js
CHANGED
|
@@ -248,7 +248,7 @@ const PARAM_DESCRIPTIONS = {
|
|
|
248
248
|
personalAssistantName: '个人助理的显示名(名录快照)',
|
|
249
249
|
isPersonalAssistant: '当前 agent 是否就是 Owner 的个人助理(即时比较,读不到身份时为 false)',
|
|
250
250
|
isOwner: '当前 agent 是否就是协议确认的 Owner(即时比较;Owner 通常是人,一般恒为 false)',
|
|
251
|
-
contactsState: '
|
|
251
|
+
contactsState: '出站可发送与入站须准入的说明',
|
|
252
252
|
peerId: '对端在该渠道的原生 ID',
|
|
253
253
|
peerKey: '对端跨渠道唯一标识(channel#urlEncode(peerId))',
|
|
254
254
|
peerName: '对端显示名',
|
|
@@ -16,7 +16,17 @@ const MESSAGE_MANIFEST_FILE = 'eck_message_manifest.json';
|
|
|
16
16
|
// ── time formatting (per IANA timezone) ──
|
|
17
17
|
function timeParts(epochMs, timeZone, opts) {
|
|
18
18
|
const d = new Date(epochMs);
|
|
19
|
-
|
|
19
|
+
// 时区可能来自客户端上报(sender_ctx.timezone)或 agent 配置,非法 IANA 名会让
|
|
20
|
+
// Intl 抛 RangeError——那会整个消息渲染失败、消息直接丢给模型。这里退化为本机时区,
|
|
21
|
+
// 宁可时间基准退回本地,也不能让一条消息因为时区串写错而整条渲染不出来。
|
|
22
|
+
let p;
|
|
23
|
+
try {
|
|
24
|
+
p = new Intl.DateTimeFormat('en-US', { ...(timeZone ? { timeZone } : {}), ...opts }).formatToParts(d);
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
logger.debug(`[MessageRenderer] invalid timezone ignored: ${String(timeZone)}`);
|
|
28
|
+
p = new Intl.DateTimeFormat('en-US', opts).formatToParts(d);
|
|
29
|
+
}
|
|
20
30
|
const out = {};
|
|
21
31
|
for (const part of p)
|
|
22
32
|
out[part.type] = part.value;
|
|
@@ -56,19 +66,28 @@ function identityLabel(name, aid, type, exttype) {
|
|
|
56
66
|
const e = String(exttype ?? '').trim();
|
|
57
67
|
return e ? `${display}[${t}/${e}]` : `${display}[${t}]`;
|
|
58
68
|
}
|
|
59
|
-
|
|
60
|
-
|
|
69
|
+
/** 本端 `名称(AID)[type/exttype]`;`self:` 前缀由模版提供。 */
|
|
70
|
+
function selfIdentityOf(sessionVars) {
|
|
71
|
+
return identityLabel(sessionVars.selfName, sessionVars.selfAid, sessionVars.selfType ?? 'agent', sessionVars.selfExttype);
|
|
61
72
|
}
|
|
62
73
|
function groupTagOf(sessionVars) {
|
|
63
74
|
const groupAid = String(sessionVars.groupId ?? '').trim();
|
|
64
75
|
const groupName = String(sessionVars.groupName ?? '').trim();
|
|
65
76
|
return groupName && groupAid ? `${groupName}<${groupAid}>` : (groupAid || groupName);
|
|
66
77
|
}
|
|
67
|
-
|
|
68
|
-
|
|
78
|
+
/** 关系角色:逐条显式值优先,其次按会话类型兜底。`关系角色:` 前缀由模版提供。 */
|
|
79
|
+
function speakerRelationOf(item, sessionVars) {
|
|
80
|
+
return String(item.speakerRelation
|
|
81
|
+
?? (String(sessionVars.chatType ?? '') === 'group' ? 'visitor' : (item.peerRole ?? sessionVars.peerRole ?? 'visitor')));
|
|
69
82
|
}
|
|
70
|
-
/**
|
|
71
|
-
|
|
83
|
+
/**
|
|
84
|
+
* `ctx: scene=… · activity=… · location=地址(纬度,经度 ±精度, 采集于 时刻)`;无 sender_ctx 返回空串。
|
|
85
|
+
*
|
|
86
|
+
* 精度与采集时刻缺省时**整段不写**——缺省的含义是「发件人没上报」,不是「精确」也
|
|
87
|
+
* 不是「就是此刻」。坐标恒定保留 6 位小数(协议原值的展示形态),精度另以 `±Nm` 标注,
|
|
88
|
+
* 两者语义分离:小数位只表示上报精度,不表示真实定位精度。
|
|
89
|
+
*/
|
|
90
|
+
function formatSenderCtx(ctx, timeZone) {
|
|
72
91
|
if (!ctx)
|
|
73
92
|
return '';
|
|
74
93
|
const parts = [];
|
|
@@ -80,7 +99,14 @@ function formatSenderCtx(ctx) {
|
|
|
80
99
|
if (loc && Number.isFinite(loc.latitude_e6) && Number.isFinite(loc.longitude_e6)) {
|
|
81
100
|
const lat = (loc.latitude_e6 / 1e6).toFixed(6);
|
|
82
101
|
const lon = (loc.longitude_e6 / 1e6).toFixed(6);
|
|
83
|
-
|
|
102
|
+
let coord = `${lat},${lon}`;
|
|
103
|
+
if (Number.isFinite(loc.accuracy_m) && loc.accuracy_m > 0) {
|
|
104
|
+
coord += ` ±${Math.round(loc.accuracy_m)}m`;
|
|
105
|
+
}
|
|
106
|
+
if (Number.isFinite(loc.timestamp_ms) && loc.timestamp_ms > 0) {
|
|
107
|
+
coord += `, 采集于 ${formatLocalTime(loc.timestamp_ms, timeZone)}`;
|
|
108
|
+
}
|
|
109
|
+
parts.push(`location=${loc.address ? `${loc.address}(${coord})` : coord}`);
|
|
84
110
|
}
|
|
85
111
|
return parts.length > 0 ? `ctx: ${parts.join(' · ')}` : '';
|
|
86
112
|
}
|
|
@@ -103,6 +129,34 @@ function renderOneItem(item, sessionVars, sessionCache, contentSentinel, compact
|
|
|
103
129
|
const isHandoff = item.kind === 'handoff';
|
|
104
130
|
const isThreadContext = item.kind === 'thread-context';
|
|
105
131
|
const isTriggerMsg = item.kind === 'trigger';
|
|
132
|
+
// 「因上一轮被新消息中断而插入」的那一条。与 kind 正交:普通消息直接写
|
|
133
|
+
// kind='interrupt-insert',已有专属 kind 的消息(trigger 等)用 interruptInsert 布尔位。
|
|
134
|
+
const isInterruptInsert = item.kind === 'interrupt-insert' || item.interruptInsert === true;
|
|
135
|
+
// 中断原因 → 提示文案。模板引擎只有真值判断、没有等值条件,逐原因文案在 JS 侧选好,
|
|
136
|
+
// 模板只做 {{interruptNotice}} 占位。首段文字保持「【中断后新消息…】」形态:
|
|
137
|
+
// 历史剥离正则(session-manager / session-transcript)按该前缀清理会话记录。
|
|
138
|
+
const interruptNotice = !isInterruptInsert ? undefined : (() => {
|
|
139
|
+
switch (item.interruptReason) {
|
|
140
|
+
case 'daemon_restart':
|
|
141
|
+
return '【中断后新消息 · 上一轮因进程重启中断,这是待处理的新消息;请根据前后消息酌情处理】';
|
|
142
|
+
case 'proactive_circuit_break':
|
|
143
|
+
return '【中断后新消息 · 上一轮因长时间无反馈被自动中断;请根据前后消息酌情处理】';
|
|
144
|
+
case 'timeout':
|
|
145
|
+
case 'execution_error':
|
|
146
|
+
return '【中断后新消息 · 上一轮执行异常中断,这是新的消息;请根据前后消息酌情处理】';
|
|
147
|
+
case 'stop':
|
|
148
|
+
case 'explicit_cancel':
|
|
149
|
+
return '【中断后新消息 · 上一轮已被叫停,这是新的消息;请根据前后消息酌情处理】';
|
|
150
|
+
case 'recalled':
|
|
151
|
+
return '【中断后新消息 · 上一轮原消息已撤回,这是新的消息;请根据前后消息酌情处理】';
|
|
152
|
+
case 'new_message':
|
|
153
|
+
case 'restart':
|
|
154
|
+
return '【中断后新消息 · 上一轮被这条新消息打断;请根据前后消息酌情处理】';
|
|
155
|
+
default:
|
|
156
|
+
// 未知/缺省原因也要出提示,不能漏。
|
|
157
|
+
return '【中断后新消息 · 请根据前后消息酌情处理】';
|
|
158
|
+
}
|
|
159
|
+
})();
|
|
106
160
|
const handoffPreviousSentinel = `\x00ECMSG-HANDOFF-PREV-${randomUUID()}\x00`;
|
|
107
161
|
const requiredReplacements = (item.handoff?.requiredEntries ?? []).map(entry => ({
|
|
108
162
|
entry,
|
|
@@ -157,7 +211,8 @@ function renderOneItem(item, sessionVars, sessionCache, contentSentinel, compact
|
|
|
157
211
|
}]
|
|
158
212
|
: [];
|
|
159
213
|
const allOriginReplacements = [...originReplacements, ...fallbackOriginEntries];
|
|
160
|
-
//
|
|
214
|
+
// 信封字段只在这里「取值」,`from:`/`self:`/`关系角色:`/`chat:`/`mid:` 等词与
|
|
215
|
+
// ` · ` 分隔符一律写在模版里(条件块内嵌分隔符,假值分支整块消失,不留悬空 `·`)。
|
|
161
216
|
const tz = sessionVars.timezone ? String(sessionVars.timezone) : undefined;
|
|
162
217
|
const selfAid = String(sessionVars.selfAid ?? '');
|
|
163
218
|
const selfName = String(sessionVars.selfName ?? '');
|
|
@@ -173,14 +228,8 @@ function renderOneItem(item, sessionVars, sessionCache, contentSentinel, compact
|
|
|
173
228
|
const fromType = selfAddressed ? selfType : itemPeerType;
|
|
174
229
|
const fromExttype = selfAddressed ? selfExttype : itemPeerExttype;
|
|
175
230
|
const modeToken = selfAddressed ? '跨话题自派' : (item.originThreadId ? '跨话题委托' : '');
|
|
176
|
-
const modePart = modeToken ? ` · ${modeToken}` : '';
|
|
177
|
-
const topicPart = item.originThreadId
|
|
178
|
-
? ` · 话题:${item.originThreadId}${item.originPeer ? `(对端:${item.originPeer})` : ''}`
|
|
179
|
-
: '';
|
|
180
|
-
const groupRolePart = item.groupRole ? ` · 群角色:${item.groupRole}` : '';
|
|
181
231
|
const isMentioned = item.isMentioned === true
|
|
182
232
|
|| (item.mentionAids ?? []).some(aid => String(aid).toLowerCase() === selfAid.toLowerCase());
|
|
183
|
-
const mentionPart = isMentioned ? ' · @我' : '';
|
|
184
233
|
const timestamp = item.timestamp ?? Date.now();
|
|
185
234
|
// 时间基准是本机时间;发件人时区与本机不同时,追加对方当地时刻与时区名,
|
|
186
235
|
// 避免模型自己换算(时区名 + 当地时刻才可直接引用)。
|
|
@@ -194,18 +243,23 @@ function renderOneItem(item, sessionVars, sessionCache, contentSentinel, compact
|
|
|
194
243
|
now: nowText,
|
|
195
244
|
shortNow: shortNowText,
|
|
196
245
|
batchTime: formatBatchTime(timestamp, tz),
|
|
197
|
-
modePart,
|
|
198
|
-
topicPart,
|
|
199
|
-
groupRolePart,
|
|
200
|
-
mentionPart,
|
|
201
246
|
groupTag: groupTagOf(sessionVars),
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
247
|
+
fromIdentity: identityLabel(fromName, fromAid, fromType, fromExttype),
|
|
248
|
+
selfIdentity: selfIdentityOf(sessionVars),
|
|
249
|
+
// 消息接收者:本会话的投递目标。与 `fromIdentity`(逐条 item 的发送方)是两个维度,
|
|
250
|
+
// 供「消息维度」的模版(如 thread-context 提醒)显式渲染 from/to。
|
|
251
|
+
// 群聊的 peerId 是**发言人**(群消息的发送者),投递目标其实是群本身,故按群 tag 渲染。
|
|
252
|
+
// 当前话题的对端:优先用会话提供的 topicPeer*(与「本轮谁唤醒」正交)。
|
|
253
|
+
// 只有伪对端(trigger:/bg:)轮次才有值;普通轮次落空,仍按 peerId 渲染。
|
|
254
|
+
toIdentity: String(sessionVars.chatType ?? '') === 'group'
|
|
255
|
+
? groupTagOf(sessionVars)
|
|
256
|
+
: (sessionVars.topicPeerId
|
|
257
|
+
? identityLabel(sessionVars.topicPeerName ?? sessionVars.peerName, sessionVars.topicPeerId, sessionVars.topicPeerType ?? sessionVars.peerType, sessionVars.peerExttype)
|
|
258
|
+
: identityLabel(sessionVars.peerName, sessionVars.peerId, sessionVars.peerType, sessionVars.peerExttype)),
|
|
259
|
+
speakerRelation: speakerRelationOf(item, sessionVars),
|
|
260
|
+
// `mid:` 是恒出现字段:缺 messageId(非 AUN 渠道)时保留占位,不能让整段消失。
|
|
261
|
+
messageId: item.messageId ?? '-',
|
|
262
|
+
senderCtxLine: formatSenderCtx(item.senderCtx, tz),
|
|
209
263
|
batchItem: compact || undefined,
|
|
210
264
|
// 跨话题委托提醒:原消息与来源会话,供回查定位。
|
|
211
265
|
threadContextMessageId: item.threadContext?.messageId,
|
|
@@ -220,6 +274,12 @@ function renderOneItem(item, sessionVars, sessionCache, contentSentinel, compact
|
|
|
220
274
|
peerType: item.peerType ?? sessionVars.peerType,
|
|
221
275
|
// 本端给自己派的任务:信封头标「跨话题自派」,让模型分清「我派的活」和「对端说的话」。
|
|
222
276
|
selfAddressed: item.selfAddressed || undefined,
|
|
277
|
+
// 信封可选段的原值:`{{?x}} ... {{/}}` 的开关与内容都由模版自己拼。
|
|
278
|
+
modeToken: modeToken || undefined,
|
|
279
|
+
originThreadId: item.originThreadId,
|
|
280
|
+
originPeer: item.originThreadId ? item.originPeer : undefined,
|
|
281
|
+
groupRole: item.groupRole,
|
|
282
|
+
isMentioned,
|
|
223
283
|
peerRole: item.peerRole ?? sessionVars.peerRole,
|
|
224
284
|
sameDevice: item.sameDevice ?? sessionVars.sameDevice,
|
|
225
285
|
sameNetwork: item.sameNetwork ?? sessionVars.sameNetwork,
|
|
@@ -234,6 +294,11 @@ function renderOneItem(item, sessionVars, sessionCache, contentSentinel, compact
|
|
|
234
294
|
renderMode_private: activeMode('private'),
|
|
235
295
|
renderMode_group: activeMode('group'),
|
|
236
296
|
renderMode_inject: activeMode('inject'),
|
|
297
|
+
// 中断插入标记:只给被插入的那一条挂一行提示(见 interrupt-insert.md)。
|
|
298
|
+
// 与 kind 正交,已有专属信封的消息用 interruptInsert 布尔位标记。
|
|
299
|
+
isInterruptInsert,
|
|
300
|
+
interruptNotice,
|
|
301
|
+
interruptReason: item.interruptReason,
|
|
237
302
|
// owner 插话提示标记 + 信封头字段
|
|
238
303
|
isOwnerHint,
|
|
239
304
|
ownerAid: isOwnerHint ? (item.ownerAid ?? undefined) : undefined,
|
|
@@ -244,6 +309,12 @@ function renderOneItem(item, sessionVars, sessionCache, contentSentinel, compact
|
|
|
244
309
|
isThreadContext,
|
|
245
310
|
threadContextOriginThreadId: item.threadContext?.originThreadId,
|
|
246
311
|
threadContextOriginPeer: item.threadContext?.originPeer,
|
|
312
|
+
// 来源话题对端的展示形态:有名字用 `名称(AID)[type]`,旧条目只有裸 AID。
|
|
313
|
+
// 类型取 inbox 落盘的真实值;旧条目没有该字段时由 identityLabel 落成 `unknown`,
|
|
314
|
+
// 不能硬编码 'agent'——来源对端常常是人。
|
|
315
|
+
threadContextOriginPeerLabel: item.threadContext?.originPeer
|
|
316
|
+
? identityLabel(item.threadContext.originPeerName, item.threadContext.originPeer, item.threadContext.originPeerType, undefined)
|
|
317
|
+
: undefined,
|
|
247
318
|
threadContextTime: item.timestamp !== undefined
|
|
248
319
|
? formatLocalTime(item.timestamp, sessionVars.timezone ? String(sessionVars.timezone) : undefined)
|
|
249
320
|
: undefined,
|
|
@@ -283,6 +354,16 @@ function renderOneItem(item, sessionVars, sessionCache, contentSentinel, compact
|
|
|
283
354
|
...(isTriggerMsg && item.triggerInfo?.labels
|
|
284
355
|
? Object.fromEntries(Object.entries(item.triggerInfo.labels).map(([k, v]) => [`triggerMsgLabel_${k}`, v]))
|
|
285
356
|
: {}),
|
|
357
|
+
// 来源话题对端的展示形态:labels 里存了名称就显示 `名称(AID)[type]`,否则退回裸 AID。
|
|
358
|
+
// 模版引擎没有 else,兜底在 JS 侧合成,模版只插一个变量。
|
|
359
|
+
triggerOriginPeerLabel: (() => {
|
|
360
|
+
const aid = item.triggerInfo?.labels?.originPeer;
|
|
361
|
+
if (!isTriggerMsg || !aid)
|
|
362
|
+
return undefined;
|
|
363
|
+
// 与 thread-context 的 `threadContextOriginPeerLabel` 同形态:缺名字也带类型标签,
|
|
364
|
+
// 类型取 labels 里落盘的真实值,旧 Trigger 缺失时落成 `unknown`。
|
|
365
|
+
return identityLabel(item.triggerInfo?.labels?.originPeerName, aid, item.triggerInfo?.labels?.originPeerType, undefined);
|
|
366
|
+
})(),
|
|
286
367
|
// msg send 跨会话一次性上下文
|
|
287
368
|
isHandoff,
|
|
288
369
|
handoffKind: item.handoff?.kind,
|
|
@@ -367,8 +448,7 @@ function renderGroupHeader(sessionVars, first, sessionCache) {
|
|
|
367
448
|
...sessionVars,
|
|
368
449
|
batchTime: formatBatchTime(first.timestamp ?? Date.now(), tz),
|
|
369
450
|
groupTag: groupTagOf(sessionVars),
|
|
370
|
-
|
|
371
|
-
chatLabel: chatLabelOf(sessionVars),
|
|
451
|
+
selfIdentity: selfIdentityOf(sessionVars),
|
|
372
452
|
};
|
|
373
453
|
const section = {
|
|
374
454
|
id: 'msg-group-batch',
|
|
@@ -439,7 +519,10 @@ function writeMessageDebug(sessionId, items, body) {
|
|
|
439
519
|
if (!isEckSnapshotsEnabled())
|
|
440
520
|
return;
|
|
441
521
|
try {
|
|
442
|
-
|
|
522
|
+
// 文件名精确到毫秒并带随机后缀:同一秒内多次渲染(同批多段、并发会话)会撞名,
|
|
523
|
+
// 异步 writeFile 覆盖同一路径时两个写流交错,落盘的是半截拼接内容。
|
|
524
|
+
const ts = new Date().toISOString().replace(/[T:.]/g, '-').slice(0, 23);
|
|
525
|
+
const uniq = randomUUID().slice(0, 8);
|
|
443
526
|
const dir = eckDebugDir();
|
|
444
527
|
fs.mkdirSync(dir, { recursive: true });
|
|
445
528
|
const out = [
|
|
@@ -2,6 +2,7 @@ import crypto from 'node:crypto';
|
|
|
2
2
|
import { assertProjectPathConfig } from '../utils/project-path.js';
|
|
3
3
|
import { ConfigTarget, mutateConfig, read, validateConfig, } from '../config/config-manager.js';
|
|
4
4
|
import { getLogStreamStates, LOG_LEVELS } from '../utils/logger.js';
|
|
5
|
+
import { resolveDaemonServices } from '../config/daemon-services.js';
|
|
5
6
|
const BASEAGENTS = ['claude', 'codex', 'gemini', 'ecagent'];
|
|
6
7
|
const BASEAGENT_SET = new Set(BASEAGENTS);
|
|
7
8
|
const EFFORTS = new Set(['low', 'medium', 'high', 'xhigh', 'max']);
|
|
@@ -197,7 +198,8 @@ function hideBaseagentConnectionFields(config) {
|
|
|
197
198
|
export function readBasicSettings() {
|
|
198
199
|
const rawDaemon = readSettingsFile('daemon');
|
|
199
200
|
const rawDefaults = readSettingsFile('defaults');
|
|
200
|
-
const daemon = rawDaemon ? clone(rawDaemon) :
|
|
201
|
+
const daemon = rawDaemon ? clone(rawDaemon) : {};
|
|
202
|
+
daemon.services = resolveDaemonServices(daemon.services);
|
|
201
203
|
if (daemon) {
|
|
202
204
|
delete daemon.owner;
|
|
203
205
|
delete daemon.owners;
|
|
@@ -110,7 +110,7 @@ export function createEcwebMessageContextProvider(sessionManager, resolveRuntime
|
|
|
110
110
|
result.status = status;
|
|
111
111
|
if (session.agentSessionId && session.projectPath && session.baseagent) {
|
|
112
112
|
try {
|
|
113
|
-
const fileInfo = sessionManager.
|
|
113
|
+
const fileInfo = await sessionManager.getSessionFileInfoAsync(session.projectPath, session.agentSessionId, session.baseagent, session.selfAID);
|
|
114
114
|
if (Number.isFinite(fileInfo.turns) && fileInfo.turns > 0)
|
|
115
115
|
result.turns = fileInfo.turns;
|
|
116
116
|
}
|
package/dist/ecweb/pairing.js
CHANGED
|
@@ -3,7 +3,8 @@ import { ipcQuery } from '../ipc.js';
|
|
|
3
3
|
import { ecwebService } from '../config/daemon-services.js';
|
|
4
4
|
export function resolveEcwebExternalUrl(config) {
|
|
5
5
|
const aid = config.aid?.trim();
|
|
6
|
-
|
|
6
|
+
const service = ecwebService(config.services);
|
|
7
|
+
if (!aid || service?.enabled !== true || service.proxy?.enabled !== true)
|
|
7
8
|
return null;
|
|
8
9
|
return `https://${aid}/proxy/ecweb`;
|
|
9
10
|
}
|
|
@@ -11,11 +12,11 @@ export function resolveEcwebExternalUrl(config) {
|
|
|
11
12
|
* One-click ECWeb pairing link. The code travels in the URL fragment so it never
|
|
12
13
|
* reaches proxy-server or ECWeb access logs; the page redeems it on load.
|
|
13
14
|
*/
|
|
14
|
-
export function buildEcwebPairingUrl(config, code) {
|
|
15
|
+
export function buildEcwebPairingUrl(config, code, initialization = false) {
|
|
15
16
|
const externalUrl = resolveEcwebExternalUrl(config);
|
|
16
17
|
if (!externalUrl || !/^\d{6}$/.test(code))
|
|
17
18
|
return null;
|
|
18
|
-
return `${externalUrl}
|
|
19
|
+
return `${externalUrl}/${initialization ? 'init' : ''}#code=${code}`;
|
|
19
20
|
}
|
|
20
21
|
/** Shared pairing-code announcement used by the control-AID and slash /pair paths. */
|
|
21
22
|
export function formatPairingCodeMessage(pair, config, now = Date.now()) {
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { isProviderModelPattern, providerModelLiteralId, providerModelEnabled, readProvidersFile, resolveProviderService } from '../config/providers.js';
|
|
2
2
|
import { resolveProviderId } from '../config/providers-config.js';
|
|
3
|
-
import { createProvider, importOrMergeBaseagentProvider, parseProviderImport, previewProviderImport, previewProviderValue, readProviderForExport, readProvidersSnapshot, resolveProviderDraftService, saveProviderChanges, updateProvider, } from '../config/providers-management.js';
|
|
3
|
+
import { createProvider, importOrMergeBaseagentProvider, parseProviderImport, previewProviderImport, previewProviderValue, readProviderForExport, readProvidersSnapshot, resolveProviderDraftService, saveProviderChanges, updateProvider, prepareProviderTemplate, previewProviderTemplate, } from '../config/providers-management.js';
|
|
4
|
+
import { readProviderTemplates, providerTemplateDetail } from '../config/provider-templates.js';
|
|
4
5
|
import { listBaseagentImportSources, providerFromBaseagent } from '../config/providers-import.js';
|
|
5
6
|
import { getProviderCatalog, previewProviderCatalog } from '../core/model/model-catalog.js';
|
|
6
7
|
function isRecord(value) {
|
|
@@ -49,6 +50,10 @@ async function resolveImports(value) {
|
|
|
49
50
|
return parseProviderImport(item.text);
|
|
50
51
|
if (item.provider !== undefined)
|
|
51
52
|
return item.provider;
|
|
53
|
+
if (isRecord(item.template)) {
|
|
54
|
+
const draft = prepareProviderTemplate(String(item.template.templateId), item.template.config);
|
|
55
|
+
return { templateProvider: draft.incoming };
|
|
56
|
+
}
|
|
52
57
|
throw new Error('Invalid Provider import');
|
|
53
58
|
});
|
|
54
59
|
}
|
|
@@ -70,6 +75,26 @@ export async function handleProvidersService(input) {
|
|
|
70
75
|
if (input.method === 'GET' && !parts.length) {
|
|
71
76
|
return response(200, { success: true, data: readProvidersSnapshot() });
|
|
72
77
|
}
|
|
78
|
+
if (parts[0] === 'templates') {
|
|
79
|
+
if (input.method === 'GET' && parts.length === 1) {
|
|
80
|
+
return response(200, { success: true, data: readProviderTemplates() });
|
|
81
|
+
}
|
|
82
|
+
if (input.method === 'GET' && parts.length === 2) {
|
|
83
|
+
return response(200, { success: true, data: providerTemplateDetail(parts[1]) });
|
|
84
|
+
}
|
|
85
|
+
if (input.method === 'POST' && parts.length === 3 && parts[2] === 'preview') {
|
|
86
|
+
const body = requestBody(input.body);
|
|
87
|
+
let context;
|
|
88
|
+
if (body.draft !== undefined) {
|
|
89
|
+
if (!isRecord(body.draft) || typeof body.draft.providerId !== 'string')
|
|
90
|
+
throw new Error('Invalid Provider draft');
|
|
91
|
+
context = { providerId: body.draft.providerId, value: body.draft.provider,
|
|
92
|
+
imports: await resolveImports(body.draft.imports) };
|
|
93
|
+
}
|
|
94
|
+
return response(200, { success: true, data: previewProviderTemplate(parts[1], body.config ?? body, context) });
|
|
95
|
+
}
|
|
96
|
+
return response(405, { success: false, error: 'Unsupported template operation' });
|
|
97
|
+
}
|
|
73
98
|
if (input.method === 'POST' && !parts.length) {
|
|
74
99
|
const body = requestBody(input.body);
|
|
75
100
|
if (typeof body.revision !== 'string')
|
|
@@ -9,10 +9,10 @@ import { resolveGlobalPkg } from '../../utils/npm-ops.js';
|
|
|
9
9
|
import { resolveEcwebLaunchCommand } from './launch.js';
|
|
10
10
|
import { WEB_PACKAGE_NAME } from '../../product.js';
|
|
11
11
|
async function sameProcess(identity) {
|
|
12
|
-
if (!platform.
|
|
12
|
+
if (!await platform.isProcessRunningAsync(identity.pid))
|
|
13
13
|
return false;
|
|
14
14
|
const actual = await getProcessStartTimeAsync(identity.pid, { fresh: true });
|
|
15
|
-
if (!platform.
|
|
15
|
+
if (!await platform.isProcessRunningAsync(identity.pid))
|
|
16
16
|
return false;
|
|
17
17
|
if (identity.startedAt === null || actual === null) {
|
|
18
18
|
throw new Error(`Cannot verify ECWeb process identity (PID: ${identity.pid}); refusing to terminate it`);
|
|
@@ -94,13 +94,15 @@ export async function stopEcwebProcess(identity, timeoutMs = FORCED_STOP_MS, onT
|
|
|
94
94
|
// before falling back to PID-addressed signals, including on IPC failure.
|
|
95
95
|
if (await waitForExit(false, IPC_GRACEFUL_STOP_MS, supervisedChild))
|
|
96
96
|
return;
|
|
97
|
+
}
|
|
98
|
+
// Verify immediately before each PID-addressed signal. Windows has no TERM
|
|
99
|
+
// attempt here, so it only needs the verification before forced termination.
|
|
100
|
+
if (!platform.isWindows) {
|
|
97
101
|
if (!await sameProcess(identity))
|
|
98
102
|
return;
|
|
103
|
+
if (await waitForExit(false, POSIX_GRACEFUL_STOP_MS))
|
|
104
|
+
return;
|
|
99
105
|
}
|
|
100
|
-
else if (!await sameProcess(identity))
|
|
101
|
-
return;
|
|
102
|
-
if (!platform.isWindows && await waitForExit(false, POSIX_GRACEFUL_STOP_MS))
|
|
103
|
-
return;
|
|
104
106
|
if (!await sameProcess(identity))
|
|
105
107
|
return;
|
|
106
108
|
if (await waitForExit(true, timeoutMs))
|
|
@@ -211,6 +213,8 @@ export async function stopEcwebForRestart(paths, port, log) {
|
|
|
211
213
|
// and exclusive bind must still prove the port was actually released.
|
|
212
214
|
if (!(await platform.findProcessByPortAsync(targetPort)).includes(pid))
|
|
213
215
|
continue;
|
|
216
|
+
if (!await platform.isProcessRunningAsync(pid))
|
|
217
|
+
continue;
|
|
214
218
|
throw new Error(`ECWeb 端口 ${targetPort} 被身份未确认的进程占用 (PID: ${pid});未终止该进程`);
|
|
215
219
|
}
|
|
216
220
|
let health;
|
|
@@ -223,6 +227,8 @@ export async function stopEcwebForRestart(paths, port, log) {
|
|
|
223
227
|
if (!matchesEcwebInstanceHealth(health, { pid, port: targetPort })) {
|
|
224
228
|
if (!(await platform.findProcessByPortAsync(targetPort)).includes(pid))
|
|
225
229
|
continue;
|
|
230
|
+
if (!await platform.isProcessRunningAsync(pid))
|
|
231
|
+
continue;
|
|
226
232
|
throw new Error(`ECWeb 端口 ${targetPort} 的服务身份无法确认 (PID: ${pid});未终止该进程`);
|
|
227
233
|
}
|
|
228
234
|
identities.set(pid, { pid, startedAt });
|
|
@@ -237,8 +243,12 @@ export async function stopEcwebForRestart(paths, port, log) {
|
|
|
237
243
|
}
|
|
238
244
|
for (const targetPort of ports) {
|
|
239
245
|
const listeners = platform.findProcessByPort(targetPort);
|
|
240
|
-
|
|
241
|
-
|
|
246
|
+
// Listener scans can race with process exit. Never signal a stale PID
|
|
247
|
+
// or fail on that row alone; exclusive binding remains mandatory below.
|
|
248
|
+
const running = await Promise.all(listeners.map(pid => platform.isProcessRunningAsync(pid)));
|
|
249
|
+
const liveListeners = listeners.filter((_pid, index) => running[index]);
|
|
250
|
+
if (liveListeners.length > 0)
|
|
251
|
+
throw new Error(`ECWeb 端口 ${targetPort} 未释放 (PID: ${liveListeners.join(', ')});已中止重启`);
|
|
242
252
|
await verifyPortReleased(targetPort);
|
|
243
253
|
}
|
|
244
254
|
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { DEFAULT_ECWEB_PORT, ecwebService } from '../../config/daemon-services.js';
|
|
2
|
+
import { ipcQuery } from '../../ipc.js';
|
|
3
|
+
import { resolvePaths } from '../../paths.js';
|
|
4
|
+
import { resolveEcwebExternalUrl } from '../pairing.js';
|
|
5
|
+
export async function readEcwebProxyAccess(config, options = {}) {
|
|
6
|
+
if (!config.aid && ecwebService(config.services).enabled && ecwebService(config.services).proxy?.enabled) {
|
|
7
|
+
return { state: 'starting', url: null, message: '主机身份待准备;请运行 ec init --web,本地 ECWeb 可继续访问' };
|
|
8
|
+
}
|
|
9
|
+
const url = resolveEcwebExternalUrl(config);
|
|
10
|
+
if (!url)
|
|
11
|
+
return { state: 'disabled', url: null, message: '未启用,保留当前设置' };
|
|
12
|
+
const deadline = Date.now() + (options.timeoutMs ?? 3000);
|
|
13
|
+
let snapshot = options.snapshot;
|
|
14
|
+
if (snapshot === undefined) {
|
|
15
|
+
try {
|
|
16
|
+
const response = await ipcQuery(resolvePaths().socket, { type: 'status' }, Math.max(1, Math.min(1000, deadline - Date.now())));
|
|
17
|
+
snapshot = response?.serviceProxy;
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return { state: 'unconfirmed', url: null, message: '运行状态暂不可用;本地初始化不受影响' };
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
const configured = snapshot?.items.find(service => service.name === 'ecweb');
|
|
24
|
+
if (configured && (!configured.serviceEnabled || !configured.proxyEnabled)) {
|
|
25
|
+
return { state: 'starting', url: null, message: '等待 daemon 应用代理配置' };
|
|
26
|
+
}
|
|
27
|
+
const transport = snapshot?.transport;
|
|
28
|
+
if (!transport)
|
|
29
|
+
return { state: 'unconfirmed', url: null, message: '尚未取得代理运行状态' };
|
|
30
|
+
if (!transport.gatewayRegistered || !transport.registeredServices.includes('ecweb')) {
|
|
31
|
+
return {
|
|
32
|
+
state: transport.state === 'degraded' ? 'failed' : 'starting', url: null,
|
|
33
|
+
message: transport.error ?? '等待控制通道、服务端点与网关登记就绪',
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
const timeoutMs = Math.min(2000, deadline - Date.now());
|
|
37
|
+
if (timeoutMs <= 0)
|
|
38
|
+
return { state: 'unconfirmed', url: null, message: '代理已登记,外网连通性尚未验证' };
|
|
39
|
+
try {
|
|
40
|
+
const port = ecwebService(config.services)?.port ?? DEFAULT_ECWEB_PORT;
|
|
41
|
+
const [localResponse, remoteResponse] = await Promise.all([
|
|
42
|
+
fetch(`http://127.0.0.1:${port}/api/health`, { signal: AbortSignal.timeout(timeoutMs), redirect: 'error' }),
|
|
43
|
+
fetch(`${url}/api/health`, { signal: AbortSignal.timeout(timeoutMs), redirect: 'follow' }),
|
|
44
|
+
]);
|
|
45
|
+
if (!localResponse.ok || !remoteResponse.ok) {
|
|
46
|
+
return { state: 'unconfirmed', url: null, message: `代理已登记,外网连通性未确认(本地 HTTP ${localResponse.status},外网 HTTP ${remoteResponse.status})` };
|
|
47
|
+
}
|
|
48
|
+
const [local, remote] = await Promise.all([localResponse.json(), remoteResponse.json()]);
|
|
49
|
+
if (local?.ok === true && remote?.ok === true && local.service === 'ecweb' && remote.service === 'ecweb'
|
|
50
|
+
&& typeof local.instanceId === 'string' && local.instanceId.length > 0 && remote.instanceId === local.instanceId
|
|
51
|
+
&& typeof local.homeId === 'string' && local.homeId.length > 0 && remote.homeId === local.homeId
|
|
52
|
+
&& remote.ready === true && remote.daemonProtocolCompatible === true) {
|
|
53
|
+
return { state: 'ready', url, message: '已就绪' };
|
|
54
|
+
}
|
|
55
|
+
return { state: 'unconfirmed', url: null, message: '代理已登记,外网响应尚未匹配当前就绪实例' };
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
return { state: 'unconfirmed', url: null, message: '代理已登记,外网访问暂未验证;可继续本地初始化' };
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
export async function waitForEcwebProxyAccess(config, timeoutMs = 15000) {
|
|
62
|
+
const deadline = Date.now() + timeoutMs;
|
|
63
|
+
let access;
|
|
64
|
+
do {
|
|
65
|
+
access = await readEcwebProxyAccess(config, { timeoutMs: Math.max(1, deadline - Date.now()) });
|
|
66
|
+
if (access.state === 'ready' || access.state === 'disabled' || !config.aid)
|
|
67
|
+
return access;
|
|
68
|
+
const remaining = deadline - Date.now();
|
|
69
|
+
if (remaining <= 0)
|
|
70
|
+
break;
|
|
71
|
+
await new Promise(resolve => setTimeout(resolve, Math.min(500, remaining)));
|
|
72
|
+
} while (Date.now() < deadline);
|
|
73
|
+
return { ...access, message: `${access.message};本次等待已超时,可继续本地初始化` };
|
|
74
|
+
}
|
|
@@ -13,6 +13,7 @@ import { sanitizeMenuLogValue } from '../../core/command/menu-protocol.js';
|
|
|
13
13
|
import { stopEcwebProcess } from './lifecycle.js';
|
|
14
14
|
import { sanitizeServiceEnvironment } from '../../core/permission/shell-environment.js';
|
|
15
15
|
const INSTANCE_FILE_RE = /^(?:ecweb|watch-web)-\d+\.json$/;
|
|
16
|
+
const OCCUPIED_PORT_DISCOVERY_MS = 3000;
|
|
16
17
|
function sleep(ms) {
|
|
17
18
|
return new Promise(resolve => setTimeout(resolve, ms));
|
|
18
19
|
}
|
|
@@ -226,7 +227,10 @@ export function createEcwebSupervisor(options) {
|
|
|
226
227
|
};
|
|
227
228
|
const waitForHealthyInstance = async (timeoutMs) => {
|
|
228
229
|
const deadline = Date.now() + timeoutMs;
|
|
230
|
+
const port = desiredPort;
|
|
229
231
|
do {
|
|
232
|
+
if (stopping || !desiredEnabled || runtimeMode !== 'managed' || desiredPort !== port)
|
|
233
|
+
return null;
|
|
230
234
|
const found = await findHealthyInstance();
|
|
231
235
|
if (found)
|
|
232
236
|
return found;
|
|
@@ -336,14 +340,40 @@ export function createEcwebSupervisor(options) {
|
|
|
336
340
|
scheduleRecovery();
|
|
337
341
|
return;
|
|
338
342
|
}
|
|
339
|
-
const
|
|
340
|
-
|
|
343
|
+
const port = desiredPort;
|
|
344
|
+
let occupiedPids = await platform.findProcessByPortAsync(port);
|
|
345
|
+
if (stopping || !desiredEnabled || runtimeMode !== 'managed' || desiredPort !== port)
|
|
341
346
|
return;
|
|
342
347
|
if (occupiedPids.length > 0) {
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
348
|
+
// A CLI-started instance can bind before publishing its record or
|
|
349
|
+
// becoming healthy. Give discovery a bounded window before treating
|
|
350
|
+
// that normal startup overlap as a failure. Only a verified instance
|
|
351
|
+
// from this HOME can be adopted; unknown port owners stay untouched.
|
|
352
|
+
const existing = await waitForHealthyInstance(OCCUPIED_PORT_DISCOVERY_MS);
|
|
353
|
+
if (stopping || !desiredEnabled || runtimeMode !== 'managed' || desiredPort !== port)
|
|
354
|
+
return;
|
|
355
|
+
if (existing && await setActiveFromEntry(existing, false)) {
|
|
356
|
+
if (stopping || !desiredEnabled || runtimeMode !== 'managed' || desiredPort !== port)
|
|
357
|
+
return;
|
|
358
|
+
healthy = true;
|
|
359
|
+
checkedAt = Date.now();
|
|
360
|
+
launchRequested = false;
|
|
361
|
+
cancelRecovery();
|
|
362
|
+
failureCount = 0;
|
|
363
|
+
hasBeenReady = true;
|
|
364
|
+
settleInitialHealth?.('ok');
|
|
365
|
+
options.logger.info(`✓ ECWeb supervisor 接管现有实例 (PID: ${existing.record.pid}, 端口: ${existing.record.port})`);
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
occupiedPids = await platform.findProcessByPortAsync(port);
|
|
369
|
+
if (stopping || !desiredEnabled || runtimeMode !== 'managed' || desiredPort !== port)
|
|
370
|
+
return;
|
|
371
|
+
if (occupiedPids.length > 0) {
|
|
372
|
+
options.logger.error(`ECWeb 本次启动失败:端口 ${port} 被占用 (PID: ${occupiedPids.join(', ')})`);
|
|
373
|
+
failureCount = failureThreshold;
|
|
374
|
+
scheduleRecovery();
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
347
377
|
}
|
|
348
378
|
fs.mkdirSync(resolvePaths().logs, { recursive: true });
|
|
349
379
|
fs.appendFileSync(logFile, `\n# daemon supervisor start ${new Date().toISOString()}\n`);
|
|
@@ -10,9 +10,9 @@ import { logger } from '../utils/logger.js';
|
|
|
10
10
|
import { EventCenterError } from './types.js';
|
|
11
11
|
import { AID_PATTERN, validateCenterConfig } from './validation.js';
|
|
12
12
|
export const EVENTS_CONFIG_JSON = 'events-config.json';
|
|
13
|
-
function defaultCenterConfig() {
|
|
13
|
+
function defaultCenterConfig(enabled = false) {
|
|
14
14
|
return {
|
|
15
|
-
enabled
|
|
15
|
+
enabled, authMode: 'allowlist',
|
|
16
16
|
admission: { coupling: 'on', rematerializeMs: 300_000 },
|
|
17
17
|
rules: {}, rateLimit: { perMinute: 60, perHour: 600 },
|
|
18
18
|
};
|
|
@@ -22,8 +22,12 @@ function readCenterConfig(filePath, migrateLegacyRules) {
|
|
|
22
22
|
try {
|
|
23
23
|
rawText = fs.readFileSync(filePath, 'utf8');
|
|
24
24
|
}
|
|
25
|
-
catch {
|
|
26
|
-
|
|
25
|
+
catch (error) {
|
|
26
|
+
if (error.code === 'ENOENT') {
|
|
27
|
+
return { config: defaultCenterConfig(true), exists: false, errors: [] };
|
|
28
|
+
}
|
|
29
|
+
return { config: defaultCenterConfig(), exists: true,
|
|
30
|
+
errors: [`Cannot read ${EVENTS_CONFIG_JSON}: ${error instanceof Error ? error.message : String(error)}`] };
|
|
27
31
|
}
|
|
28
32
|
let raw;
|
|
29
33
|
try {
|
|
@@ -54,7 +58,7 @@ function readCenterConfig(filePath, migrateLegacyRules) {
|
|
|
54
58
|
}
|
|
55
59
|
return { config: validated.value, exists: true, errors: [] };
|
|
56
60
|
}
|
|
57
|
-
/**
|
|
61
|
+
/** 缺少配置时启用默认通知;显式关闭、非法和不可读配置保持关闭。 */
|
|
58
62
|
export function loadCenterConfig(eventsDir) {
|
|
59
63
|
migrateLegacyFileName(eventsDir, 'center.json', EVENTS_CONFIG_JSON, 'events config');
|
|
60
64
|
return readCenterConfig(path.join(eventsDir, EVENTS_CONFIG_JSON), true);
|