evolcore 0.0.49 → 0.0.50
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 +64 -1
- package/bin/ecmsg.js +9 -4
- package/dist/ability/caller/authorization.js +21 -0
- package/dist/ability/caller/command.js +164 -0
- package/dist/ability/caller/contract.js +102 -0
- package/dist/ability/caller/daemon.js +158 -0
- package/dist/ability/caller/service.js +380 -0
- package/dist/ability/command-contract.js +5 -0
- package/dist/ability/daemon.js +5 -1
- package/dist/ability/interop-v1.js +10 -3
- package/dist/ability/management.js +1 -0
- package/dist/agent-template/jobs.js +173 -1
- package/dist/agent-template/runtime.js +280 -6
- package/dist/agent-template/service.js +1159 -40
- package/dist/agent-template/types.js +2 -1
- package/dist/agents/baseagent-availability.js +27 -3
- package/dist/agents/baseagent-capability-adapter.js +102 -0
- package/dist/agents/baseagent-plugin-descriptor.js +274 -0
- package/dist/agents/baseagent-plugin-loader.js +145 -0
- package/dist/agents/baseagent.js +68 -2
- package/dist/agents/claude-gateway/agent-registration.js +389 -0
- package/dist/agents/claude-gateway/binding.js +96 -0
- package/dist/agents/claude-gateway/inbox.js +138 -0
- package/dist/agents/claude-gateway/index.js +125 -0
- package/dist/agents/claude-gateway/listing.js +330 -0
- package/dist/agents/claude-gateway/router.js +328 -0
- package/dist/agents/claude-gateway/sessions.js +128 -0
- package/dist/agents/claude-gateway/terminal.js +250 -0
- package/dist/agents/claude-gateway/transcript.js +272 -0
- package/dist/agents/claude-gateway/types.js +14 -0
- package/dist/agents/claude-runner.js +6 -10
- package/dist/agents/codex-runner.js +4 -1
- package/dist/agents/{gemini-runner.js → gemini/gemini-runner.js} +17 -17
- package/dist/{core/session/adapters → agents/gemini}/gemini-session-file-adapter.js +2 -2
- package/dist/agents/gemini/index.js +51 -0
- package/dist/aun/aid/control-aid.js +52 -32
- package/dist/aun/group/invite-service.js +6 -36
- package/dist/aun/group/operations.js +6 -0
- package/dist/aun/msg/mention-schema.js +1 -1
- package/dist/aun/msg/p2p.js +29 -1
- package/dist/aun/msg/upload.js +126 -3
- package/dist/build-identity.json +1 -1
- package/dist/channels/aun.js +537 -189
- package/dist/cli/ability-command.js +42 -0
- package/dist/cli/agent-command.js +20 -1
- package/dist/cli/agent-create.js +78 -18
- package/dist/cli/agent-template.js +5 -3
- package/dist/cli/agent.js +91 -0
- package/dist/cli/aun-commands.js +92 -34
- package/dist/cli/bench.js +5 -2
- package/dist/cli/config.js +22 -6
- package/dist/cli/daemon-commands.js +245 -101
- package/dist/cli/ecmsg-gateway.js +11 -9
- package/dist/cli/index.js +23 -4
- package/dist/cli/init.js +39 -63
- package/dist/cli/managed-command-guard.js +1 -0
- package/dist/cli/menu-client.js +32 -7
- package/dist/cli/pay-command.js +30 -0
- package/dist/cli/provider-command.js +6 -2
- package/dist/cli/restart-monitor.js +2 -2
- package/dist/cli/services-command.js +11 -9
- package/dist/cli/thread-command.js +78 -12
- package/dist/config/access-policy.js +16 -3
- package/dist/config/config-field-policy.js +17 -8
- package/dist/config/config-manager.js +86 -46
- package/dist/config/config-operation-service.js +22 -1
- package/dist/config/gateway-config.js +9 -8
- package/dist/config/owner-config.js +0 -16
- package/dist/config/peer-role-resolver.js +1 -7
- package/dist/config/providers-config.js +99 -16
- package/dist/config/providers-management.js +35 -19
- package/dist/config/resolved-config-op.js +1 -42
- package/dist/config/schema-migration.js +78 -5
- package/dist/config/schema-registry.js +52 -7
- package/dist/config-store.js +1309 -17
- package/dist/core/agent-application-service.js +220 -1
- package/dist/core/agent-ipc-registration.js +19 -2
- package/dist/core/agent-reload-coordinator.js +5 -0
- package/dist/core/agent-runtime.js +198 -54
- package/dist/core/auth/agent-delegation.js +14 -0
- package/dist/core/auth/operation-authorizer.js +16 -1
- package/dist/core/auth/operation-catalog.js +50 -7
- package/dist/core/baseagent-loader.js +30 -3
- package/dist/core/capability/capability-manager.js +16 -7
- package/dist/core/channel-runtime.js +4 -2
- package/dist/core/command/agent-control.js +20 -2
- package/dist/core/command/agent-template-menu.js +4 -3
- package/dist/core/command/cli-intent-parser.js +15 -0
- package/dist/core/command/menu-catalog.js +20 -4
- package/dist/core/command/menu-file-path.js +70 -0
- package/dist/core/command/menu-handler.js +91 -72
- package/dist/core/command/menu-protocol.js +5 -0
- package/dist/core/command/menu-query-batch.js +2 -2
- package/dist/core/command/private-mention-menu.js +71 -0
- package/dist/core/command/slash-handler.js +17 -26
- package/dist/core/command/team-workspace-bootstrap.js +2 -1
- package/dist/core/command/topic-slash.js +7 -1
- package/dist/core/daemon-bootstrap.js +0 -4
- package/dist/core/daemon-control.js +2 -1
- package/dist/core/daemon-lifecycle.js +13 -5
- package/dist/core/evolagent-registry.js +12 -7
- package/dist/core/handoff/runtime.js +1 -1
- package/dist/core/host-snapshot.js +8 -3
- package/dist/core/initialization/service.js +3 -0
- package/dist/core/interaction-router.js +130 -0
- package/dist/core/ipc-registration.js +4 -0
- package/dist/core/memory/consolidation-context.js +2 -1
- package/dist/core/memory/consolidation.js +35 -64
- package/dist/core/message/aun-ipc-sender.js +98 -21
- package/dist/core/message/aun-request-registry.js +31 -0
- package/dist/core/message/message-bridge.js +105 -6
- package/dist/core/message/message-log.js +8 -0
- package/dist/core/message/message-queue.js +5 -3
- package/dist/core/message/peer-mode.js +15 -4
- package/dist/core/message/response-engine.js +23 -8
- package/dist/core/message/send-options.js +37 -3
- package/dist/core/message/send-routing.js +11 -7
- package/dist/core/model/model-catalog.js +5 -5
- package/dist/core/ownership/owner-resolver.js +12 -86
- package/dist/core/pack-auth.js +4 -0
- package/dist/core/permission/ec-command-parser.js +182 -58
- package/dist/core/permission/protected-paths.js +64 -9
- package/dist/core/permission/services-path-acl.js +9 -2
- package/dist/core/permission/tool-policy.js +21 -9
- package/dist/core/session/adapters/claude-session-file-adapter.js +6 -2
- package/dist/core/session/adapters/codex-session-file-adapter.js +4 -0
- package/dist/core/session/session-manager.js +47 -10
- package/dist/core/session/session-mapper.js +16 -0
- package/dist/core/skill/index-generator.js +2 -3
- package/dist/core/skill/switch-resolver.js +3 -0
- package/dist/core/thread/command-parser.js +4 -1
- package/dist/core/thread/ipc-operation.js +4 -2
- package/dist/core/thread/thread-operation.js +25 -10
- package/dist/core/thread/thread-service.js +294 -55
- package/dist/core/thread/topic-id.js +52 -2
- package/dist/core/thread/types.js +15 -1
- package/dist/eck/kit-renderer.js +2 -1
- package/dist/ecweb/basic-settings-service.js +5 -9
- package/dist/ecweb/providers-service.js +4 -2
- package/dist/index.js +116 -41
- package/dist/ipc.js +58 -2
- package/dist/paths.js +48 -1
- package/dist/pay/command.js +38 -0
- package/dist/pay/protocol.js +136 -0
- package/dist/pay/runtime.js +188 -0
- package/dist/pay/service.js +384 -0
- package/dist/pay/store.js +81 -0
- package/dist/response-system/engines/v1/proactive-flow.js +29 -2
- package/dist/services/dispatcher.js +23 -5
- package/dist/services/host/main.js +388 -0
- package/dist/services/host/protocol.js +118 -0
- package/dist/services/host/resident.js +310 -0
- package/dist/services/host-client.js +386 -0
- package/dist/services/host-deploy.js +180 -0
- package/dist/services/host-launch.js +117 -0
- package/dist/services/host-recycle.js +203 -0
- package/dist/services/host-runtime.js +802 -0
- package/dist/services/idempotency.js +44 -86
- package/dist/services/index-generator.js +4 -3
- package/dist/services/index.js +176 -18
- package/dist/services/ipc-operation.js +204 -44
- package/dist/services/script-runner.js +515 -83
- package/dist/services/validation.js +109 -4
- package/dist/trigger/application-service.js +6 -4
- package/dist/trigger/local-files.js +19 -9
- package/dist/trigger/scheduler.js +22 -12
- package/dist/trigger/script-sandbox.js +51 -20
- package/dist/utils/aid-bind.js +3 -0
- package/dist/utils/evolcore-version.js +2 -2
- package/dist/utils/host-info.js +73 -0
- package/dist/utils/logger.js +2 -2
- package/dist/utils/media-cache.js +190 -43
- package/dist/utils/restart-safety.js +14 -1
- package/dist/utils/system-memory.js +113 -25
- package/dist/utils/systemd-lifecycle.js +154 -0
- package/dist/utils/windows-shell-trust.js +7 -3
- package/kits/docs/INDEX.md +3 -2
- package/kits/docs/aun/AUN/346/266/210/346/201/257/347/261/273/345/236/213/344/270/216/345/261/236/346/200/247.md +1 -0
- package/kits/docs/channels/aun.md +1 -1
- package/kits/docs/evolcore/INDEX.md +7 -6
- package/kits/docs/evolcore/agent.md +36 -1
- package/kits/docs/evolcore/aid.md +20 -3
- package/kits/docs/evolcore/config.md +1 -1
- package/kits/docs/evolcore/group.md +2 -1
- package/kits/docs/evolcore/memory-tags.md +2 -0
- package/kits/docs/evolcore/menu-client.md +3 -3
- package/kits/docs/evolcore/menu-protocol.md +7 -0
- package/kits/docs/evolcore/model.md +3 -0
- package/kits/docs/evolcore/msg.md +68 -10
- package/kits/docs/evolcore/pay.md +34 -0
- package/kits/docs/evolcore/provider.md +21 -0
- package/kits/docs/evolcore/services.md +46 -18
- package/kits/docs/evolcore/thread-chain.md +2 -0
- package/kits/docs/evolcore/tool-authorization.md +10 -0
- package/kits/rules/01-overview.md +11 -32
- package/kits/rules/02-navigation.md +7 -0
- package/kits/rules/06-channel.md +3 -3
- package/kits/schemas/_meta.json +38 -5
- package/kits/schemas/agent-config.schema.21.json +974 -0
- package/kits/schemas/agent-config.schema.22.json +977 -0
- package/kits/schemas/agent-config.schema.23.json +958 -0
- package/kits/schemas/daemon.schema.10.json +373 -0
- package/kits/schemas/daemon.schema.9.json +12 -0
- package/kits/schemas/defaults.schema.7.json +472 -0
- package/kits/schemas/providers.schema.3.json +18 -2
- package/kits/schemas/relation-config.schema.13.json +289 -0
- package/kits/skills/.switches.json +13 -1
- package/kits/skills/ability/SKILL.md +229 -34
- package/kits/skills/ability/STRUCTURE.md +333 -0
- package/kits/skills/ability/references/cli.md +208 -0
- package/kits/skills/ability/references/development.md +107 -37
- package/kits/skills/ability/references/management.md +106 -46
- package/kits/skills/ability/references/runtime-protocol.md +65 -63
- package/kits/skills/agent-output-cards/SKILL.md +12 -5
- package/kits/skills/ec-group/SKILL.md +8 -6
- package/kits/skills/ec-group/TASK.md +186 -0
- package/kits/skills/ec-group/WORKLOG.md +180 -0
- package/kits/skills/ec-group-collaboration/SKILL.md +3 -3
- package/kits/skills/ec-pay/SKILL.md +101 -0
- package/kits/skills/ec-pay/references/pay-cli.md +110 -0
- package/kits/skills/ec-provider/SKILL.md +1 -1
- package/kits/skills/{ec-service-proxy → ec-proxy}/SKILL.md +8 -5
- package/kits/skills/ec-service-call/SKILL.md +135 -0
- package/kits/skills/ec-service-pack/SKILL.md +277 -0
- package/kits/skills/ec-trigger/SKILL.md +1 -1
- package/kits/templates/memory-consolidation/notes.md +2 -2
- package/kits/templates/memory-consolidation/workflow.md +46 -0
- package/kits/templates/system-fragments/channel.md +13 -4
- package/kits/templates/system-fragments/commands.md +4 -3
- package/kits/templates/system-fragments/reply.md +1 -0
- package/kits/templates/system-fragments/session.md +1 -1
- package/kits/templates/system-fragments/thread.md +27 -129
- package/kits/templates/system-fragments/venue.md +16 -0
- package/package.json +4 -5
- package/scripts/agent-template/inspect.mjs +37 -23
- package/scripts/agent-template/overlay.mjs +20 -2
- package/scripts/agent-template/shared/common.mjs +16 -4
- package/scripts/agent-template/shared/team-schema.json +20 -4
- package/scripts/agent-template/shared/template-contract.mjs +53 -13
- package/scripts/agent-template/shared/template-package.mjs +90 -26
- package/scripts/agent-template/shared/template-runtime.mjs +111 -1
- package/scripts/agent-template/shared/template.mjs +65 -7
- package/scripts/agent-template/team-pack.mjs +89 -33
- package/scripts/agent-template/team-preview.mjs +249 -5
- package/kits/docs/aun/ABILITY_CALLING.md +0 -280
- package/kits/docs/evolcore/ability.md +0 -185
- package/kits/skills/ability/references/calling.md +0 -56
- package/kits/skills/ability/references/contract-checklist.md +0 -37
- package/kits/skills/ability/references/recovery.md +0 -27
- /package/dist/{core/capability/providers → agents/gemini}/gemini-capability-provider.js +0 -0
|
@@ -11,7 +11,7 @@ import path from 'path';
|
|
|
11
11
|
import fs from 'fs';
|
|
12
12
|
import crypto from 'crypto';
|
|
13
13
|
import { logger } from './logger.js';
|
|
14
|
-
import { agentRelationDir } from '../paths.js';
|
|
14
|
+
import { agentRelationDir, agentAttachmentsDir, agentAttachmentIndexDir, } from '../paths.js';
|
|
15
15
|
import { parsePeerKey } from '../core/relation/peer-identity.js';
|
|
16
16
|
import { isSameOrDescendant } from '../core/permission/protected-paths.js';
|
|
17
17
|
// ── 常量 ──────────────────────────────────────────────────────────────────────
|
|
@@ -112,68 +112,149 @@ export async function validateImage(buffer, opts) {
|
|
|
112
112
|
}
|
|
113
113
|
return { mime: type.mime };
|
|
114
114
|
}
|
|
115
|
-
|
|
115
|
+
/** 旧版附件目录(升级前的落点,仅用于兼容读取)。 */
|
|
116
|
+
function legacyRelationAttachmentsDir(selfAid, peerKey) {
|
|
116
117
|
parsePeerKey(peerKey);
|
|
117
118
|
return path.join(agentRelationDir(selfAid, peerKey), 'attachments');
|
|
118
119
|
}
|
|
119
|
-
/**
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
throw new Error(`Relation attachment must be between 1 byte and ${RELATION_ATTACHMENT_MAX_BYTES} bytes`);
|
|
126
|
-
}
|
|
127
|
-
const directory = relationAttachmentsDir(selfAid, peerKey);
|
|
120
|
+
/** 关系归属索引文件:`$AGENT_DIR/attachments/index/<peerKey>.jsonl`。 */
|
|
121
|
+
function attachmentIndexPath(selfAid, peerKey) {
|
|
122
|
+
parsePeerKey(peerKey);
|
|
123
|
+
return path.join(agentAttachmentIndexDir(selfAid), `${peerKey}.jsonl`);
|
|
124
|
+
}
|
|
125
|
+
function ensureDir(directory) {
|
|
128
126
|
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
129
127
|
if (process.platform !== 'win32')
|
|
130
128
|
fs.chmodSync(directory, 0o700);
|
|
129
|
+
}
|
|
130
|
+
/** 读取索引文件的全部记录;文件不存在时返回空数组。 */
|
|
131
|
+
function readIndexRecords(indexPath) {
|
|
132
|
+
let text;
|
|
133
|
+
try {
|
|
134
|
+
text = fs.readFileSync(indexPath, 'utf8');
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
return [];
|
|
138
|
+
}
|
|
139
|
+
const records = [];
|
|
140
|
+
for (const line of text.split('\n')) {
|
|
141
|
+
if (!line.trim())
|
|
142
|
+
continue;
|
|
143
|
+
try {
|
|
144
|
+
records.push(JSON.parse(line));
|
|
145
|
+
}
|
|
146
|
+
catch { /* skip malformed line */ }
|
|
147
|
+
}
|
|
148
|
+
return records;
|
|
149
|
+
}
|
|
150
|
+
function appendIndexRecord(indexPath, metadata) {
|
|
151
|
+
fs.appendFileSync(indexPath, `${JSON.stringify(metadata)}\n`, { mode: 0o600 });
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* 在 agent 级附件目录里为 `filename` 找一个落点。
|
|
155
|
+
*
|
|
156
|
+
* 规则(2026-11-16 起):
|
|
157
|
+
* - 同名文件存在且 **大小与 sha256 都相同** → 复用已有文件,不新增副本;
|
|
158
|
+
* - 同名但内容不同 → 依次尝试 `<base>-1<ext>`、`<base>-2<ext>`…,已存在同名候选时
|
|
159
|
+
* 同样先做内容比对,命中即复用;
|
|
160
|
+
* - 全部空闲 → 用原始文件名。
|
|
161
|
+
*/
|
|
162
|
+
/** 与附件本体同级的保留名:索引子目录不能用作用户文件名。 */
|
|
163
|
+
const RESERVED_ATTACHMENT_NAMES = new Set(['index']);
|
|
164
|
+
function resolveAttachmentTarget(directory, filename, buffer, sha256) {
|
|
165
|
+
const ext = path.extname(filename);
|
|
166
|
+
const base = ext ? filename.slice(0, -ext.length) : filename;
|
|
167
|
+
for (let index = 0; index < 10_000; index++) {
|
|
168
|
+
const candidate = index === 0 ? filename : `${base}-${index}${ext}`;
|
|
169
|
+
// 保留名(如 index 子目录)不能作为附件本体名,直接跳到下一个编号。
|
|
170
|
+
if (RESERVED_ATTACHMENT_NAMES.has(candidate.toLowerCase()))
|
|
171
|
+
continue;
|
|
172
|
+
const candidatePath = path.join(directory, candidate);
|
|
173
|
+
if (!fs.existsSync(candidatePath)) {
|
|
174
|
+
return { filename: candidate, filePath: candidatePath, reused: false };
|
|
175
|
+
}
|
|
176
|
+
try {
|
|
177
|
+
const stat = fs.lstatSync(candidatePath);
|
|
178
|
+
// 目录(如 index/)不是可复用候选,跳过后继续找编号。
|
|
179
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size !== buffer.length)
|
|
180
|
+
continue;
|
|
181
|
+
const existingSha = crypto.createHash('sha256').update(fs.readFileSync(candidatePath)).digest('hex');
|
|
182
|
+
if (existingSha === sha256)
|
|
183
|
+
return { filename: candidate, filePath: candidatePath, reused: true };
|
|
184
|
+
}
|
|
185
|
+
catch {
|
|
186
|
+
continue;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
throw new Error(`Too many same-name attachments in agent attachment directory: ${filename}`);
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Save one attachment (image or arbitrary file).
|
|
193
|
+
*
|
|
194
|
+
* 文件本体进 agent 级目录(按内容去重,同一份文件发给多个对端只占一份磁盘);
|
|
195
|
+
* 归属信息追加到该对端的索引 `$AGENT_DIR/attachments/index/<peerKey>.jsonl`,
|
|
196
|
+
* 保留「这段关系什么时候收发过什么」的痕迹。
|
|
197
|
+
*/
|
|
198
|
+
export function saveRelationAttachment(buffer, selfAid, peerKey, mimeType, opts = {}) {
|
|
199
|
+
const originalName = opts.filename ? sanitizeFileName(opts.filename) : '';
|
|
200
|
+
let extension;
|
|
201
|
+
if (opts.allowAnyExtension && originalName) {
|
|
202
|
+
extension = path.extname(originalName);
|
|
203
|
+
}
|
|
204
|
+
else {
|
|
205
|
+
extension = RELATION_ATTACHMENT_EXTENSIONS[mimeType] ?? '';
|
|
206
|
+
if (!extension)
|
|
207
|
+
throw new Error(`Unsupported relation attachment MIME type: ${mimeType}`);
|
|
208
|
+
}
|
|
209
|
+
if (buffer.length < 1 || buffer.length > RELATION_ATTACHMENT_MAX_BYTES) {
|
|
210
|
+
throw new Error(`Relation attachment must be between 1 byte and ${RELATION_ATTACHMENT_MAX_BYTES} bytes`);
|
|
211
|
+
}
|
|
212
|
+
const directory = agentAttachmentsDir(selfAid);
|
|
213
|
+
ensureDir(directory);
|
|
214
|
+
const indexDir = agentAttachmentIndexDir(selfAid);
|
|
215
|
+
ensureDir(indexDir);
|
|
131
216
|
const attachmentId = crypto.randomBytes(16).toString('hex');
|
|
132
|
-
const
|
|
133
|
-
const filePath = path.join(directory, filename);
|
|
134
|
-
const metadataPath = path.join(directory, `${attachmentId}.json`);
|
|
217
|
+
const requestedName = originalName || `${attachmentId}${extension}`;
|
|
135
218
|
const sha256 = crypto.createHash('sha256').update(buffer).digest('hex');
|
|
219
|
+
const target = resolveAttachmentTarget(directory, requestedName, buffer, sha256);
|
|
136
220
|
const metadata = {
|
|
137
|
-
version: 1, attachmentId, selfAid, peerKey,
|
|
138
|
-
|
|
221
|
+
version: 1, attachmentId, selfAid, peerKey,
|
|
222
|
+
filename: requestedName, storage: target.filename, mimeType,
|
|
223
|
+
sha256, size: buffer.length, direction: opts.direction ?? 'in', createdAt: Date.now(),
|
|
139
224
|
};
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
225
|
+
if (!target.reused) {
|
|
226
|
+
fs.writeFileSync(target.filePath, buffer, { flag: 'wx', mode: 0o600 });
|
|
227
|
+
}
|
|
228
|
+
// 索引一律追加:同一份内容收发 N 次就有 N 条记录,文件本体只落一份。
|
|
229
|
+
appendIndexRecord(attachmentIndexPath(selfAid, peerKey), metadata);
|
|
230
|
+
return { ...metadata, filePath: target.filePath };
|
|
143
231
|
}
|
|
144
232
|
/** Resolve an attachment only inside the authenticated Agent/peer relation. */
|
|
145
233
|
export function readRelationAttachment(selfAid, peerKey, attachmentSource) {
|
|
146
|
-
|
|
234
|
+
// 兼容三种输入:新版文件名(会话内认知名)、旧版 32 位 hex ID、绝对路径。
|
|
235
|
+
const basename = path.basename(attachmentSource);
|
|
236
|
+
const legacyId = RELATION_ATTACHMENT_ID_RE.test(attachmentSource)
|
|
147
237
|
? attachmentSource
|
|
148
|
-
: path.basename(
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
const
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
const metadata = JSON.parse(fs.readFileSync(metadataPath, 'utf8'));
|
|
157
|
-
if (metadata.version !== 1 || metadata.attachmentId !== attachmentId
|
|
158
|
-
|| metadata.selfAid !== selfAid || metadata.peerKey !== peerKey
|
|
159
|
-
|| RELATION_ATTACHMENT_EXTENSIONS[metadata.mimeType] === undefined
|
|
160
|
-
|| metadata.filename !== `${attachmentId}${RELATION_ATTACHMENT_EXTENSIONS[metadata.mimeType]}`) {
|
|
238
|
+
: (RELATION_ATTACHMENT_ID_RE.test(path.basename(basename, path.extname(basename)))
|
|
239
|
+
? path.basename(basename, path.extname(basename))
|
|
240
|
+
: '');
|
|
241
|
+
const metadata = resolveIndexedMetadata(selfAid, peerKey, basename)
|
|
242
|
+
?? (legacyId ? resolveLegacyMetadata(selfAid, peerKey, legacyId, basename) : null);
|
|
243
|
+
if (!metadata)
|
|
244
|
+
throw new Error('Attachment metadata not found');
|
|
245
|
+
if (metadata.version !== 1 || metadata.selfAid !== selfAid || metadata.peerKey !== peerKey) {
|
|
161
246
|
throw new Error('Attachment ownership metadata mismatch');
|
|
162
247
|
}
|
|
163
|
-
const
|
|
164
|
-
|
|
248
|
+
const attachmentId = metadata.attachmentId;
|
|
249
|
+
if (!RELATION_ATTACHMENT_ID_RE.test(attachmentId))
|
|
250
|
+
throw new Error('Invalid attachment ID');
|
|
251
|
+
const realPath = resolveAttachmentFile(selfAid, peerKey, metadata);
|
|
252
|
+
const stat = fs.lstatSync(realPath);
|
|
165
253
|
if (!stat.isFile() || stat.isSymbolicLink() || stat.size !== metadata.size
|
|
166
254
|
|| stat.size < 1 || stat.size > RELATION_ATTACHMENT_MAX_BYTES) {
|
|
167
255
|
throw new Error('Attachment file is missing or invalid');
|
|
168
256
|
}
|
|
169
|
-
const
|
|
170
|
-
const realPath = fs.realpathSync(filePath);
|
|
171
|
-
if (!isSameOrDescendant(realPath, realDirectory))
|
|
172
|
-
throw new Error('Attachment path escaped its relation directory');
|
|
173
|
-
if (path.isAbsolute(attachmentSource) && fs.realpathSync(attachmentSource) !== realPath) {
|
|
174
|
-
throw new Error('Attachment path does not match the current relation');
|
|
175
|
-
}
|
|
176
|
-
const buffer = fs.readFileSync(filePath);
|
|
257
|
+
const buffer = fs.readFileSync(realPath);
|
|
177
258
|
const sha256 = crypto.createHash('sha256').update(buffer).digest('hex');
|
|
178
259
|
if (sha256 !== metadata.sha256)
|
|
179
260
|
throw new Error('Attachment content hash mismatch');
|
|
@@ -185,6 +266,72 @@ export function readRelationAttachment(selfAid, peerKey, attachmentSource) {
|
|
|
185
266
|
buffer,
|
|
186
267
|
};
|
|
187
268
|
}
|
|
269
|
+
/** 旧版:`<peerKey>/attachments/<id>.json` + `<id><ext>`,仍在关系目录里。 */
|
|
270
|
+
function resolveLegacyMetadata(selfAid, peerKey, legacyId, requestedBasename) {
|
|
271
|
+
const directory = legacyRelationAttachmentsDir(selfAid, peerKey);
|
|
272
|
+
const legacyPath = path.join(directory, `${legacyId}.json`);
|
|
273
|
+
try {
|
|
274
|
+
const stat = fs.lstatSync(legacyPath);
|
|
275
|
+
if (!stat.isFile() || stat.isSymbolicLink())
|
|
276
|
+
return null;
|
|
277
|
+
const raw = JSON.parse(fs.readFileSync(legacyPath, 'utf8'));
|
|
278
|
+
if (!raw || typeof raw !== 'object')
|
|
279
|
+
return null;
|
|
280
|
+
// 旧记录没有 storage/direction 字段,落盘名按旧约定推导。
|
|
281
|
+
const filename = typeof raw.filename === 'string' ? raw.filename : '';
|
|
282
|
+
return {
|
|
283
|
+
...raw,
|
|
284
|
+
filename: requestedBasename || filename,
|
|
285
|
+
storage: filename,
|
|
286
|
+
direction: 'in',
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
catch {
|
|
290
|
+
return null;
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
/** 新版:`$AGENT_DIR/attachments/index/<peerKey>.jsonl` 里按 filename 取最后一条。 */
|
|
294
|
+
function resolveIndexedMetadata(selfAid, peerKey, filename) {
|
|
295
|
+
if (!filename || filename.includes('\0') || filename === '.' || filename === '..'
|
|
296
|
+
|| path.basename(filename) !== filename) {
|
|
297
|
+
throw new Error('Invalid attachment name');
|
|
298
|
+
}
|
|
299
|
+
const records = readIndexRecords(attachmentIndexPath(selfAid, peerKey));
|
|
300
|
+
for (let index = records.length - 1; index >= 0; index--) {
|
|
301
|
+
const record = records[index];
|
|
302
|
+
if (record.filename === filename || record.storage === filename || record.attachmentId === filename)
|
|
303
|
+
return record;
|
|
304
|
+
}
|
|
305
|
+
return null;
|
|
306
|
+
}
|
|
307
|
+
/** 取文件本体路径:新版在 agent 级目录,旧版回落到关系目录。 */
|
|
308
|
+
function resolveAttachmentFile(selfAid, peerKey, metadata) {
|
|
309
|
+
const storage = typeof metadata.storage === 'string' && metadata.storage
|
|
310
|
+
? metadata.storage
|
|
311
|
+
: metadata.filename;
|
|
312
|
+
if (!storage || path.basename(storage) !== storage)
|
|
313
|
+
throw new Error('Invalid attachment storage name');
|
|
314
|
+
const agentDirPath = agentAttachmentsDir(selfAid);
|
|
315
|
+
const agentCandidate = path.join(agentDirPath, storage);
|
|
316
|
+
if (fs.existsSync(agentCandidate)) {
|
|
317
|
+
const realRoot = fs.realpathSync(agentDirPath);
|
|
318
|
+
const realPath = fs.realpathSync(agentCandidate);
|
|
319
|
+
if (!isSameOrDescendant(realPath, realRoot))
|
|
320
|
+
throw new Error('Attachment path escaped the agent attachment directory');
|
|
321
|
+
return realPath;
|
|
322
|
+
}
|
|
323
|
+
// 旧版附件仍在关系目录里。
|
|
324
|
+
const legacyDir = legacyRelationAttachmentsDir(selfAid, peerKey);
|
|
325
|
+
const legacyCandidate = path.join(legacyDir, storage);
|
|
326
|
+
if (fs.existsSync(legacyCandidate)) {
|
|
327
|
+
const realRoot = fs.realpathSync(legacyDir);
|
|
328
|
+
const realPath = fs.realpathSync(legacyCandidate);
|
|
329
|
+
if (!isSameOrDescendant(realPath, realRoot))
|
|
330
|
+
throw new Error('Attachment path escaped its relation directory');
|
|
331
|
+
return realPath;
|
|
332
|
+
}
|
|
333
|
+
throw new Error('Attachment file is missing or invalid');
|
|
334
|
+
}
|
|
188
335
|
/**
|
|
189
336
|
* 把已下载的附件 Buffer 转成入站图片条目(供 baseagent 视觉通道)。
|
|
190
337
|
*
|
|
@@ -5,7 +5,15 @@ const REAL_RESTART_TEST_OVERRIDE = 'EVOLCORE_ALLOW_REAL_RESTART_IN_TEST';
|
|
|
5
5
|
export function readRestartRequest(filePath, requestId) {
|
|
6
6
|
try {
|
|
7
7
|
const request = JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
|
8
|
-
|
|
8
|
+
if (!request?.requestId || (requestId && request.requestId !== requestId))
|
|
9
|
+
return null;
|
|
10
|
+
// A failed unit may never start a replacement process. Readers can still
|
|
11
|
+
// observe a terminal timeout without requiring a surviving supervisor.
|
|
12
|
+
if (request.backend === 'systemd' && ['requested', 'accepted'].includes(request.status)
|
|
13
|
+
&& request.deadline && request.deadline <= Date.now()) {
|
|
14
|
+
return { ...request, status: 'timeout', reason: 'Systemd replacement did not confirm ready before the restart deadline' };
|
|
15
|
+
}
|
|
16
|
+
return request;
|
|
9
17
|
}
|
|
10
18
|
catch {
|
|
11
19
|
return null;
|
|
@@ -15,6 +23,9 @@ export function createRestartRequest(filePath, request, isProcessAlive) {
|
|
|
15
23
|
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
16
24
|
try {
|
|
17
25
|
const previous = JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
|
26
|
+
if (previous.backend === 'systemd' && ['requested', 'accepted'].includes(previous.status)
|
|
27
|
+
&& Number(previous.deadline) > Date.now())
|
|
28
|
+
return false;
|
|
18
29
|
if ([previous.launcherPid, previous.monitorPid]
|
|
19
30
|
.some(pid => typeof pid === 'number' && isProcessAlive(pid))
|
|
20
31
|
|| Date.now() - Number(previous.updatedAt ?? previous.timestamp ?? 0) < 30_000)
|
|
@@ -39,6 +50,8 @@ export function updateRestartRequest(filePath, requestId, update) {
|
|
|
39
50
|
const request = readRestartRequest(filePath, requestId);
|
|
40
51
|
if (!request)
|
|
41
52
|
return false;
|
|
53
|
+
if (['ready', 'failed', 'timeout'].includes(request.status) && update.status && update.status !== request.status)
|
|
54
|
+
return false;
|
|
42
55
|
atomicWriteJson(filePath, { ...request, ...update, updatedAt: Date.now() });
|
|
43
56
|
return true;
|
|
44
57
|
}
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import fs from 'fs';
|
|
2
2
|
import os from 'os';
|
|
3
|
+
import path from 'node:path';
|
|
3
4
|
function readNumber(filePath) {
|
|
4
5
|
try {
|
|
5
|
-
const
|
|
6
|
-
|
|
6
|
+
const raw = fs.readFileSync(filePath, 'utf8').trim();
|
|
7
|
+
const value = /^\d+$/u.test(raw) ? Number(raw) : NaN;
|
|
8
|
+
return Number.isSafeInteger(value) && value >= 0 ? value : null;
|
|
7
9
|
}
|
|
8
10
|
catch {
|
|
9
11
|
return null;
|
|
@@ -19,39 +21,125 @@ export function parseCgroupV2MemoryStat(input) {
|
|
|
19
21
|
}
|
|
20
22
|
return values;
|
|
21
23
|
}
|
|
24
|
+
function readText(file) {
|
|
25
|
+
try {
|
|
26
|
+
return fs.readFileSync(file, 'utf8').trim();
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
return '';
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
function memoryHierarchies(cgroupRoot) {
|
|
33
|
+
if (cgroupRoot !== '/sys/fs/cgroup') {
|
|
34
|
+
return [{ directory: cgroupRoot, mountPoint: cgroupRoot, version: 2 }];
|
|
35
|
+
}
|
|
36
|
+
const memberships = readText('/proc/self/cgroup').split('\n')
|
|
37
|
+
.map(line => line.match(/^\d+:([^:]*):(\/.*)$/u))
|
|
38
|
+
.filter((match) => match !== null);
|
|
39
|
+
const hierarchies = [];
|
|
40
|
+
const decode = (value) => value.replace(/\\([0-7]{3})/gu, (_match, octal) => String.fromCharCode(Number.parseInt(octal, 8)));
|
|
41
|
+
for (const line of readText('/proc/self/mountinfo').split('\n')) {
|
|
42
|
+
const [mount, filesystem] = line.split(' - ');
|
|
43
|
+
if (!mount || !filesystem)
|
|
44
|
+
continue;
|
|
45
|
+
const fields = mount.split(' ');
|
|
46
|
+
const [type, , options = ''] = filesystem.split(' ');
|
|
47
|
+
if (type !== 'cgroup2' && !(type === 'cgroup' && options.split(',').includes('memory')))
|
|
48
|
+
continue;
|
|
49
|
+
if (!fields[3] || !fields[4])
|
|
50
|
+
continue;
|
|
51
|
+
const version = type === 'cgroup2' ? 2 : 1;
|
|
52
|
+
const member = memberships.find(match => version === 2
|
|
53
|
+
? match[1] === '' : match[1].split(',').includes('memory'));
|
|
54
|
+
if (!member)
|
|
55
|
+
continue;
|
|
56
|
+
const mountPoint = decode(fields[4]);
|
|
57
|
+
const relative = path.posix.relative(decode(fields[3]), member[2]);
|
|
58
|
+
const suffix = relative === '..' || relative.startsWith('../') ? member[2] : relative;
|
|
59
|
+
const directory = path.posix.resolve(mountPoint, `./${suffix}`);
|
|
60
|
+
if (directory === mountPoint || directory.startsWith(`${mountPoint}/`)) {
|
|
61
|
+
hierarchies.push({ directory, mountPoint, version });
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
if (hierarchies.length === 0) {
|
|
65
|
+
for (const [mountPoint, version] of [['/sys/fs/cgroup', 2], ['/sys/fs/cgroup/memory', 1]]) {
|
|
66
|
+
const member = memberships.find(match => version === 2
|
|
67
|
+
? match[1] === '' : match[1].split(',').includes('memory'));
|
|
68
|
+
const directory = path.posix.resolve(mountPoint, `.${member?.[2] ?? '/'}`);
|
|
69
|
+
if (directory === mountPoint || directory.startsWith(`${mountPoint}/`)) {
|
|
70
|
+
hierarchies.push({ directory, mountPoint, version });
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return hierarchies;
|
|
75
|
+
}
|
|
22
76
|
/**
|
|
23
77
|
* System memory for the current container/host namespace.
|
|
24
78
|
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
79
|
+
* Total is bounded by visible cgroup hard limits, including ancestors. Usage
|
|
80
|
+
* excludes filesystem cache when available. Free is hard-limit headroom;
|
|
81
|
+
* available also includes the cache estimate, bounded by parent headroom and
|
|
82
|
+
* host free memory. These are estimates, not guarantees of future allocation.
|
|
29
83
|
*/
|
|
30
84
|
export function readSystemMemoryUsage(cgroupRoot = '/sys/fs/cgroup') {
|
|
31
|
-
const
|
|
32
|
-
const
|
|
85
|
+
const hostTotal = os.totalmem();
|
|
86
|
+
const hostAvailable = os.freemem();
|
|
87
|
+
let memTotal = hostTotal;
|
|
33
88
|
if (process.platform === 'linux') {
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
89
|
+
let headroom = hostAvailable;
|
|
90
|
+
let available = hostAvailable;
|
|
91
|
+
let usage;
|
|
92
|
+
for (const hierarchy of memoryHierarchies(cgroupRoot)) {
|
|
93
|
+
let directory = hierarchy.directory;
|
|
94
|
+
while (true) {
|
|
95
|
+
const limit = readNumber(`${directory}/${hierarchy.version === 2 ? 'memory.max' : 'memory.limit_in_bytes'}`);
|
|
96
|
+
const current = readNumber(`${directory}/${hierarchy.version === 2 ? 'memory.current' : 'memory.usage_in_bytes'}`);
|
|
97
|
+
const stat = parseCgroupV2MemoryStat(readText(`${directory}/memory.stat`));
|
|
98
|
+
const cache = hierarchy.version === 2 ? stat.get('file') : stat.get('total_cache') ?? stat.get('cache');
|
|
99
|
+
if (directory === hierarchy.directory && current !== null) {
|
|
100
|
+
usage = { current, cache, version: hierarchy.version };
|
|
101
|
+
}
|
|
102
|
+
// v1's unlimited sentinel exceeds safe integer precision and is ignored.
|
|
103
|
+
if (limit !== null) {
|
|
104
|
+
memTotal = Math.min(memTotal, limit);
|
|
105
|
+
if (current !== null) {
|
|
106
|
+
headroom = Math.min(headroom, Math.max(0, limit - current));
|
|
107
|
+
available = Math.min(available, Math.max(0, limit - Math.max(0, current - (cache ?? 0))));
|
|
108
|
+
}
|
|
50
109
|
}
|
|
110
|
+
if (directory === hierarchy.mountPoint)
|
|
111
|
+
break;
|
|
112
|
+
directory = path.posix.dirname(directory);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
if (usage) {
|
|
116
|
+
const { current, cache, version } = usage;
|
|
117
|
+
const memUsed = Math.min(memTotal, Math.max(0, current - (cache ?? 0)));
|
|
118
|
+
return {
|
|
119
|
+
memTotal, memUsed,
|
|
120
|
+
memFree: Math.min(headroom, Math.max(0, memTotal - current)),
|
|
121
|
+
memAvailable: Math.min(available, Math.max(0, memTotal - memUsed)),
|
|
122
|
+
memorySource: version === 2
|
|
123
|
+
? cache === undefined ? 'cgroup-v2-current' : 'cgroup-v2-current-minus-file'
|
|
124
|
+
: cache === undefined ? 'cgroup-v1-usage' : 'cgroup-v1-usage-minus-cache',
|
|
125
|
+
cgroupCurrent: current,
|
|
126
|
+
...(cache === undefined ? {} : { fileCache: cache }),
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
// Even if usage files are unreadable, keep a discovered hard limit and use
|
|
130
|
+
// Node's container-aware availability instead of subtracting host metrics.
|
|
131
|
+
if (memTotal < hostTotal) {
|
|
132
|
+
let memAvailable = 0;
|
|
133
|
+
try {
|
|
134
|
+
memAvailable = process.availableMemory();
|
|
51
135
|
}
|
|
52
|
-
catch { /*
|
|
136
|
+
catch { /* conservative fallback */ }
|
|
137
|
+
memAvailable = Number.isFinite(memAvailable) ? Math.max(0, Math.min(memTotal, hostAvailable, memAvailable)) : 0;
|
|
138
|
+
return { memTotal, memUsed: memTotal - memAvailable, memFree: memAvailable,
|
|
139
|
+
memAvailable, memorySource: 'runtime-available' };
|
|
53
140
|
}
|
|
54
141
|
}
|
|
142
|
+
const memAvailable = Math.max(0, Math.min(memTotal, hostAvailable));
|
|
55
143
|
return {
|
|
56
144
|
memTotal,
|
|
57
145
|
memUsed: Math.max(0, memTotal - memAvailable),
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import { execFile } from 'child_process';
|
|
4
|
+
import { promisify } from 'util';
|
|
5
|
+
import { withFileLock } from './atomic-write.js';
|
|
6
|
+
import { getProcessStartTime, startTimeMatches } from './process-introspect.js';
|
|
7
|
+
import { readRestartRequest, updateRestartRequest } from './restart-safety.js';
|
|
8
|
+
const execFileAsync = promisify(execFile);
|
|
9
|
+
const SHOW_PROPERTIES = 'Id,LoadState,ActiveState,MainPID,ControlGroup,InvocationID';
|
|
10
|
+
function processCgroup(pid) {
|
|
11
|
+
const groups = fs.readFileSync(`/proc/${pid}/cgroup`, 'utf8').trim().split('\n')
|
|
12
|
+
.map(line => line.match(/^\d+:([^:]*):(\/.*)$/))
|
|
13
|
+
.filter(match => match && (match[1] === '' || match[1].split(',').includes('name=systemd')))
|
|
14
|
+
.map(match => match[2]);
|
|
15
|
+
if (groups.length !== 1 || path.posix.normalize(groups[0]) !== groups[0]) {
|
|
16
|
+
throw new Error(`Cannot determine systemd cgroup for daemon PID ${pid}`);
|
|
17
|
+
}
|
|
18
|
+
return groups[0];
|
|
19
|
+
}
|
|
20
|
+
function assertIdentity(pid, startedAt) {
|
|
21
|
+
if (!Number.isInteger(pid) || pid <= 1 || !Number.isFinite(startedAt)
|
|
22
|
+
|| !startTimeMatches(startedAt, getProcessStartTime(pid, { fresh: true }))) {
|
|
23
|
+
throw new Error(`Daemon identity changed or is unavailable (PID ${pid}); refusing systemd restart`);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
function hasAncestor(pid, ancestor) {
|
|
27
|
+
const visited = new Set();
|
|
28
|
+
while (pid > 1 && visited.size < 64 && !visited.has(pid)) {
|
|
29
|
+
if (pid === ancestor)
|
|
30
|
+
return true;
|
|
31
|
+
visited.add(pid);
|
|
32
|
+
const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8');
|
|
33
|
+
pid = Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[1]);
|
|
34
|
+
}
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
function scopeArgs(scope) {
|
|
38
|
+
return scope === 'user' ? ['--user'] : ['--system'];
|
|
39
|
+
}
|
|
40
|
+
/** Inspect the target daemon, never the calling CLI's cgroup or environment. */
|
|
41
|
+
export async function discoverSystemdService(pid, startedAt) {
|
|
42
|
+
if (process.platform !== 'linux')
|
|
43
|
+
return null;
|
|
44
|
+
assertIdentity(pid, startedAt);
|
|
45
|
+
const controlGroup = processCgroup(pid);
|
|
46
|
+
// The innermost unit owns the process. An ancestor user@/docker service is
|
|
47
|
+
// not ownership when a session/container scope is nested underneath it.
|
|
48
|
+
const units = controlGroup.split('/').filter(part => /\.(service|scope)$/.test(part));
|
|
49
|
+
const unit = units.at(-1);
|
|
50
|
+
if (!unit?.endsWith('.service'))
|
|
51
|
+
return null;
|
|
52
|
+
if (!/^[a-zA-Z0-9_:@.\\-]+\.service$/.test(unit) || unit.startsWith('-')) {
|
|
53
|
+
throw new Error('Invalid systemd service name in daemon cgroup');
|
|
54
|
+
}
|
|
55
|
+
// A container may expose a host cgroup while having its own PID namespace.
|
|
56
|
+
// Never ask a host/container manager to restart an enclosing host service.
|
|
57
|
+
if (fs.readFileSync('/proc/1/comm', 'utf8').trim() !== 'systemd') {
|
|
58
|
+
throw new Error('Daemon has a service cgroup but its systemd manager is not visible; restart from the owning host');
|
|
59
|
+
}
|
|
60
|
+
const userManager = controlGroup.match(/\/user@(\d+)\.service\//);
|
|
61
|
+
const scope = userManager ? 'user' : 'system';
|
|
62
|
+
if (userManager && Number(userManager[1]) !== process.getuid?.()) {
|
|
63
|
+
throw new Error('User systemd restart requires the owning user and its user manager');
|
|
64
|
+
}
|
|
65
|
+
const { stdout } = await execFileAsync('systemctl', [
|
|
66
|
+
...scopeArgs(scope), '--no-ask-password', 'show', `--property=${SHOW_PROPERTIES}`, '--', unit,
|
|
67
|
+
], { encoding: 'utf8', timeout: 5_000, maxBuffer: 64 * 1024 });
|
|
68
|
+
const properties = Object.fromEntries(stdout.trim().split('\n').map(line => {
|
|
69
|
+
const equals = line.indexOf('=');
|
|
70
|
+
return [line.slice(0, equals), line.slice(equals + 1)];
|
|
71
|
+
}));
|
|
72
|
+
const mainPid = Number(properties.MainPID);
|
|
73
|
+
if (properties.Id !== unit || properties.LoadState !== 'loaded' || properties.ActiveState !== 'active'
|
|
74
|
+
|| properties.ControlGroup !== controlGroup
|
|
75
|
+
|| !/^[a-f0-9]{32}$/.test(properties.InvocationID)
|
|
76
|
+
|| !Number.isInteger(mainPid) || mainPid <= 1
|
|
77
|
+
|| !hasAncestor(pid, mainPid) || processCgroup(mainPid) !== controlGroup) {
|
|
78
|
+
throw new Error(`Cannot verify daemon ownership by ${scope} unit ${unit}; service was not stopped`);
|
|
79
|
+
}
|
|
80
|
+
const command = fs.readFileSync(`/proc/${mainPid}/cmdline`, 'utf8').split('\0');
|
|
81
|
+
if (!command.includes('start') || !command.includes('--foreground')) {
|
|
82
|
+
throw new Error(`Unit ${unit} does not run start --foreground; automatic systemd restart is unsupported`);
|
|
83
|
+
}
|
|
84
|
+
assertIdentity(pid, startedAt);
|
|
85
|
+
return { scope, unit, controlGroup, invocationId: properties.InvocationID, mainPid, daemonPid: pid, daemonStartedAt: startedAt };
|
|
86
|
+
}
|
|
87
|
+
/** Persist ownership before submission: systemd can kill this caller before execFile resolves. */
|
|
88
|
+
export async function submitSystemdRestart(file, requestId, service) {
|
|
89
|
+
await withFileLock(`${file}.systemd.lock`, async () => {
|
|
90
|
+
const pending = readRestartRequest(file, requestId);
|
|
91
|
+
if (!pending || pending.status !== 'requested' || pending.backend) {
|
|
92
|
+
throw new Error('Restart request changed or was already submitted');
|
|
93
|
+
}
|
|
94
|
+
const current = await discoverSystemdService(service.daemonPid, service.daemonStartedAt);
|
|
95
|
+
if (!current || current.invocationId !== service.invocationId || current.unit !== service.unit
|
|
96
|
+
|| current.scope !== service.scope || current.controlGroup !== service.controlGroup) {
|
|
97
|
+
throw new Error('Systemd ownership changed before restart submission');
|
|
98
|
+
}
|
|
99
|
+
if (!updateRestartRequest(file, requestId, {
|
|
100
|
+
backend: 'systemd', systemd: service, deadline: Date.now() + 120_000,
|
|
101
|
+
}))
|
|
102
|
+
throw new Error('Restart request changed before systemd submission');
|
|
103
|
+
try {
|
|
104
|
+
await execFileAsync('systemctl', [
|
|
105
|
+
...scopeArgs(service.scope), '--no-ask-password', '--no-block', 'restart', '--', service.unit,
|
|
106
|
+
], { encoding: 'utf8', timeout: 5_000, maxBuffer: 64 * 1024 });
|
|
107
|
+
updateRestartRequest(file, requestId, { status: 'accepted' });
|
|
108
|
+
}
|
|
109
|
+
catch (error) {
|
|
110
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
111
|
+
// A timeout can happen after the job was enqueued. Keep the durable
|
|
112
|
+
// binding so a replacement can still prove ready; forbid another restart.
|
|
113
|
+
const uncertain = error.killed === true;
|
|
114
|
+
updateRestartRequest(file, requestId, { ...(uncertain ? {} : { status: 'failed' }), reason });
|
|
115
|
+
throw error;
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
/** Called only after this daemon has written its own ready signal. */
|
|
120
|
+
export async function completeSystemdRestart(file) {
|
|
121
|
+
const pending = readRestartRequest(file);
|
|
122
|
+
if (pending?.backend !== 'systemd' || !pending.systemd
|
|
123
|
+
|| !['requested', 'accepted'].includes(pending.status))
|
|
124
|
+
return false;
|
|
125
|
+
return withFileLock(`${file}.systemd.lock`, async () => {
|
|
126
|
+
const request = readRestartRequest(file, pending.requestId);
|
|
127
|
+
if (!request?.systemd || !['requested', 'accepted'].includes(request.status))
|
|
128
|
+
return false;
|
|
129
|
+
if (!await resumeSystemdRestart(file))
|
|
130
|
+
return false;
|
|
131
|
+
const startedAt = getProcessStartTime(process.pid, { fresh: true });
|
|
132
|
+
if (!startedAt)
|
|
133
|
+
return false;
|
|
134
|
+
return updateRestartRequest(file, request.requestId, {
|
|
135
|
+
status: 'ready', daemonPid: process.pid, daemonStartedAt: startedAt,
|
|
136
|
+
});
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
/** The foreground launcher must preserve pure-restart intent on the new invocation. */
|
|
140
|
+
export async function resumeSystemdRestart(file) {
|
|
141
|
+
const request = readRestartRequest(file);
|
|
142
|
+
if (request?.backend !== 'systemd' || !request.systemd
|
|
143
|
+
|| !['requested', 'accepted'].includes(request.status))
|
|
144
|
+
return null;
|
|
145
|
+
const startedAt = getProcessStartTime(process.pid, { fresh: true });
|
|
146
|
+
if (!startedAt || startedAt <= request.systemd.daemonStartedAt)
|
|
147
|
+
return null;
|
|
148
|
+
const service = await discoverSystemdService(process.pid, startedAt);
|
|
149
|
+
if (!service || service.unit !== request.systemd.unit || service.scope !== request.systemd.scope
|
|
150
|
+
|| service.controlGroup !== request.systemd.controlGroup
|
|
151
|
+
|| service.invocationId === request.systemd.invocationId)
|
|
152
|
+
return null;
|
|
153
|
+
return request;
|
|
154
|
+
}
|
|
@@ -246,16 +246,20 @@ function cacheKey(filePath) {
|
|
|
246
246
|
* the existing parser behavior; only Windows enters the Authenticode path.
|
|
247
247
|
*/
|
|
248
248
|
export function isTrustedWindowsShellExecutable(executable, kind) {
|
|
249
|
-
if (process.platform !== 'win32')
|
|
250
|
-
return true;
|
|
251
249
|
try {
|
|
252
|
-
|
|
250
|
+
requireTrustedWindowsShellExecutable(executable, kind);
|
|
253
251
|
return true;
|
|
254
252
|
}
|
|
255
253
|
catch {
|
|
256
254
|
return false;
|
|
257
255
|
}
|
|
258
256
|
}
|
|
257
|
+
/** Preserve the concrete failure for EC permission checks and CLI diagnostics. */
|
|
258
|
+
export function requireTrustedWindowsShellExecutable(executable, kind) {
|
|
259
|
+
if (process.platform !== 'win32')
|
|
260
|
+
return executable;
|
|
261
|
+
return verifyWindowsShellExecutable(executable, kind);
|
|
262
|
+
}
|
|
259
263
|
function verifyWindowsShellExecutable(executable, kind) {
|
|
260
264
|
const resolved = resolveShellPath(executable, kind);
|
|
261
265
|
if (!resolved) {
|