evolcore 0.0.48 → 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 +34 -0
- package/dist/agent-template/runtime.js +5 -2
- package/dist/agents/codex-runner.js +5 -1
- package/dist/aun/msg/p2p.js +2 -1
- package/dist/build-identity.json +1 -1
- package/dist/channels/aun.js +643 -273
- package/dist/cli/directory.js +6 -1
- package/dist/cli/index.js +7 -1
- package/dist/cli/managed-command-guard.js +2 -0
- package/dist/cli/model.js +20 -5
- package/dist/cli/quota.js +89 -0
- package/dist/cli/role.js +1 -0
- package/dist/cli/services-command.js +1 -0
- package/dist/cli/team-workspace-command.js +56 -2
- package/dist/config/config-field-policy.js +71 -1
- package/dist/config/config-manager.js +11 -1
- package/dist/config/providers-config.js +8 -4
- package/dist/config/providers-management.js +11 -3
- package/dist/config/resolved-config-op.js +3 -2
- package/dist/core/auth/delegation-authorization.js +33 -26
- package/dist/core/auth/operation-catalog.js +9 -0
- package/dist/core/command/cli-intent-parser.js +13 -0
- package/dist/core/command/command-handler.js +45 -2
- package/dist/core/command/menu-handler.js +6 -1
- package/dist/core/command/menu-protocol.js +24 -0
- package/dist/core/command/remote-shell.js +565 -0
- package/dist/core/daemon-control.js +57 -1
- package/dist/core/daemon-lifecycle.js +16 -2
- package/dist/core/evolagent-registry.js +6 -2
- package/dist/core/ipc-registration.js +1 -0
- package/dist/core/message/aun-ipc-sender.js +118 -56
- 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 +40 -1
- package/dist/core/message/message-admission.js +5 -39
- package/dist/core/message/message-bridge.js +92 -39
- package/dist/core/message/message-log.js +24 -0
- package/dist/core/message/message-queue.js +97 -15
- package/dist/core/message/response-engine.js +151 -18
- package/dist/core/model/config-scope.js +6 -14
- package/dist/core/model/model-diagnostics.js +19 -0
- package/dist/core/model/model-fallback.js +13 -2
- 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/services-path-acl.js +451 -0
- package/dist/core/permission/tool-policy.js +5 -1
- package/dist/core/relation/peer-identity.js +13 -0
- package/dist/core/task/task-recovery-service.js +1 -0
- package/dist/core/thread/topic-id.js +15 -0
- package/dist/directory/owner-directory-admission.js +11 -8
- package/dist/directory/owner-directory-cache.js +19 -0
- package/dist/directory/owner-directory-markdown.js +1 -1
- package/dist/directory/owner-directory-policy.js +5 -30
- package/dist/directory/owner-directory-request-operation.js +5 -2
- package/dist/eck/kit-renderer.js +1 -1
- package/dist/eck/message-renderer.js +28 -5
- package/dist/ecweb/runtime/supervisor.js +36 -8
- 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 +20 -5
- package/dist/event-center/runtime.js +10 -7
- package/dist/index.js +4 -0
- package/dist/ipc.js +25 -1
- package/dist/outputs/authorization.js +16 -0
- package/dist/outputs/cards.js +336 -0
- package/dist/outputs/events.js +3 -2
- package/dist/outputs/protocol.js +1 -0
- package/dist/outputs/service.js +2 -15
- package/dist/services/index.js +29 -5
- package/dist/services/ipc-operation.js +84 -0
- package/dist/services/pack-manager.js +1 -0
- package/dist/services/service-payload.js +13 -7
- package/dist/stats/budget.js +1 -1
- package/dist/stats/model-resolver.js +2 -2
- package/dist/stats/quota-query.js +95 -0
- package/dist/trigger/script-sandbox.js +12 -0
- package/dist/utils/atomic-write.js +22 -8
- package/dist/utils/evolcore-version.js +2 -2
- package/dist/utils/host-info.js +100 -1
- package/dist/utils/npm-ops.js +43 -8
- package/dist/workbench/service.js +1 -1
- package/kits/docs/evolcore/INDEX.md +2 -0
- package/kits/docs/evolcore/aid.md +25 -0
- package/kits/docs/evolcore/config.md +4 -1
- package/kits/docs/evolcore/directory.md +8 -9
- package/kits/docs/evolcore/msg.md +9 -0
- package/kits/docs/evolcore/provider.md +1 -1
- package/kits/docs/evolcore/quota.md +54 -0
- package/kits/docs/evolcore/role.md +3 -0
- package/kits/docs/evolcore/stats.md +2 -0
- package/kits/docs/evolcore/trigger.md +2 -0
- package/kits/schemas/agent-config.schema.20.json +24 -0
- package/kits/skills/.switches.json +4 -0
- package/kits/skills/agent-output-cards/SKILL.md +57 -0
- package/kits/skills/ec-provider/SKILL.md +57 -8
- package/kits/templates/roles/visitor.json +1 -0
- package/kits/templates/system-fragments/commands.md +1 -0
- package/kits/templates/system-fragments/directory-contacts.md +3 -4
- package/kits/templates/system-fragments/thread.md +1 -0
- package/kits/templates/system-fragments/venue.md +11 -0
- package/package.json +2 -2
- package/scripts/agent-template/inspect.mjs +46 -10
- package/scripts/agent-template/shared/common.mjs +9 -3
- package/scripts/agent-template/shared/team-schema.json +6 -4
- package/scripts/agent-template/shared/template-contract.mjs +60 -10
- package/scripts/agent-template/shared/template-package.mjs +182 -21
- package/scripts/agent-template/shared/template-runtime.mjs +35 -2
- package/scripts/agent-template/shared/template.mjs +2 -2
- package/scripts/agent-template/team-pack.mjs +46 -11
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { agentOutputDir } from '../paths.js';
|
|
5
|
+
import { atomicRemove, atomicWriteJson } from '../utils/atomic-write.js';
|
|
6
|
+
import { DataRootError } from '../core/command/team-workspace-store.js';
|
|
7
|
+
import { currentOutputOwner, authorizeOutput } from './authorization.js';
|
|
8
|
+
export { OUTPUT_CARDS_EVENT } from './protocol.js';
|
|
9
|
+
import { OUTPUT_CARDS_EVENT } from './protocol.js';
|
|
10
|
+
export const OUTPUT_CARDS_TYPES = ['snapshot', 'list', 'detail', 'changes']
|
|
11
|
+
.map(action => `services.outputs.cards.${action}`);
|
|
12
|
+
export const isOutputCardsType = (type) => OUTPUT_CARDS_TYPES.includes(type);
|
|
13
|
+
const KINDS = ['meeting', 'report', 'document', 'media', 'generic'];
|
|
14
|
+
const ROLES = ['primary', 'summary', 'transcript', 'recording', 'attachment', 'cover'];
|
|
15
|
+
const ID = /^[a-z0-9][a-z0-9._-]{0,63}$/;
|
|
16
|
+
const MAX_CARDS = 200;
|
|
17
|
+
const MAX_FILES = 8;
|
|
18
|
+
const MAX_CARD_BYTES = 4096;
|
|
19
|
+
const MAX_PAGE = 10;
|
|
20
|
+
function fail(message) {
|
|
21
|
+
throw new DataRootError('INVALID_CARD', message);
|
|
22
|
+
}
|
|
23
|
+
function safeRelative(value) {
|
|
24
|
+
return typeof value === 'string' && value.length > 0 && value.length <= 2048
|
|
25
|
+
&& !value.includes('\\') && !value.includes(':') && !/[\x00-\x1f\x7f]/.test(value)
|
|
26
|
+
&& value.split('/').every(part => part.length > 0 && part !== '.' && part !== '..' && !part.startsWith('.'));
|
|
27
|
+
}
|
|
28
|
+
function validateDraft(value) {
|
|
29
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
30
|
+
return fail('Card must be a JSON object');
|
|
31
|
+
const raw = value;
|
|
32
|
+
if (Object.keys(raw).some(key => !['schemaVersion', 'id', 'kind', 'title', 'summary', 'files'].includes(key))) {
|
|
33
|
+
return fail('Card contains unsupported fields');
|
|
34
|
+
}
|
|
35
|
+
if (raw.schemaVersion !== 1 || typeof raw.id !== 'string' || !ID.test(raw.id))
|
|
36
|
+
return fail('Card schemaVersion or id is invalid');
|
|
37
|
+
if (!KINDS.includes(raw.kind))
|
|
38
|
+
return fail('Card kind must be meeting, report, document, media or generic');
|
|
39
|
+
if (typeof raw.title !== 'string' || !raw.title.trim() || raw.title.length > 160)
|
|
40
|
+
return fail('Card title must contain 1 to 160 characters');
|
|
41
|
+
if (raw.summary !== undefined && (typeof raw.summary !== 'string' || raw.summary.length > 640))
|
|
42
|
+
return fail('Card summary is limited to 640 characters');
|
|
43
|
+
if (!Array.isArray(raw.files) || raw.files.length < 1 || raw.files.length > MAX_FILES)
|
|
44
|
+
return fail(`Card files must contain 1 to ${MAX_FILES} references`);
|
|
45
|
+
const files = [];
|
|
46
|
+
const seen = new Set();
|
|
47
|
+
for (const item of raw.files) {
|
|
48
|
+
if (!item || typeof item !== 'object' || Array.isArray(item))
|
|
49
|
+
return fail('Each file reference must be an object');
|
|
50
|
+
const file = item;
|
|
51
|
+
if (Object.keys(file).some(key => !['role', 'path', 'label'].includes(key)))
|
|
52
|
+
return fail('File reference contains unsupported fields');
|
|
53
|
+
if (!ROLES.includes(file.role) || !safeRelative(file.path))
|
|
54
|
+
return fail('File role or relative path is invalid');
|
|
55
|
+
if (seen.has(file.path))
|
|
56
|
+
return fail('Card file paths must be unique');
|
|
57
|
+
seen.add(file.path);
|
|
58
|
+
if (file.label !== undefined && (typeof file.label !== 'string' || file.label.length > 100))
|
|
59
|
+
return fail('File label is limited to 100 characters');
|
|
60
|
+
files.push({ role: file.role, path: file.path, label: file.label?.trim() || path.posix.basename(file.path) });
|
|
61
|
+
}
|
|
62
|
+
if (files.filter(file => file.role === 'primary').length !== 1)
|
|
63
|
+
return fail('Card requires exactly one primary file reference');
|
|
64
|
+
return { schemaVersion: 1, id: raw.id, kind: raw.kind, title: raw.title.trim(), summary: typeof raw.summary === 'string' ? raw.summary.trim() : '', files };
|
|
65
|
+
}
|
|
66
|
+
function outputRoot(aid, resolve = agentOutputDir) {
|
|
67
|
+
let root;
|
|
68
|
+
try {
|
|
69
|
+
root = fs.realpathSync(resolve(aid));
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
throw new DataRootError('OUTPUT_UNAVAILABLE', 'Agent output directory is unavailable');
|
|
73
|
+
}
|
|
74
|
+
if (!fs.statSync(root).isDirectory())
|
|
75
|
+
throw new DataRootError('OUTPUT_UNAVAILABLE', 'Agent output directory is unavailable');
|
|
76
|
+
return root;
|
|
77
|
+
}
|
|
78
|
+
function checkedFile(root, relative) {
|
|
79
|
+
const target = path.resolve(root, ...relative.split('/'));
|
|
80
|
+
const resolved = path.relative(root, target);
|
|
81
|
+
if (!resolved || resolved === '..' || resolved.startsWith(`..${path.sep}`) || path.isAbsolute(resolved))
|
|
82
|
+
fail('File reference escapes Agent output');
|
|
83
|
+
let real;
|
|
84
|
+
try {
|
|
85
|
+
real = fs.realpathSync(target);
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
throw new DataRootError('CARD_FILE_NOT_FOUND', `Referenced output file does not exist: ${relative}`);
|
|
89
|
+
}
|
|
90
|
+
const realRelative = path.relative(root, real);
|
|
91
|
+
if (realRelative === '..' || realRelative.startsWith(`..${path.sep}`) || path.isAbsolute(realRelative) || !fs.statSync(real).isFile()) {
|
|
92
|
+
return fail('File reference must resolve to a regular file inside Agent output');
|
|
93
|
+
}
|
|
94
|
+
const normalized = `output/${relative}`;
|
|
95
|
+
return { path: normalized, outputId: crypto.createHash('sha256').update(normalized).digest('hex').slice(0, 32) };
|
|
96
|
+
}
|
|
97
|
+
function cardDir(root) {
|
|
98
|
+
const directory = path.join(root, '.cards');
|
|
99
|
+
if (fs.existsSync(directory)) {
|
|
100
|
+
const real = fs.realpathSync(directory);
|
|
101
|
+
if (path.resolve(real) !== path.resolve(directory) || !fs.statSync(real).isDirectory())
|
|
102
|
+
fail('Card directory cannot be a link');
|
|
103
|
+
}
|
|
104
|
+
return directory;
|
|
105
|
+
}
|
|
106
|
+
function toCard(root, raw, updatedAt) {
|
|
107
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw))
|
|
108
|
+
return fail('Card must be a JSON object');
|
|
109
|
+
const { updatedAt: _updatedAt, ...draftData } = raw;
|
|
110
|
+
const draft = validateDraft(draftData);
|
|
111
|
+
const files = draft.files.map(file => {
|
|
112
|
+
const outputPath = `output/${file.path}`;
|
|
113
|
+
return { ...file, path: outputPath, outputId: crypto.createHash('sha256').update(outputPath).digest('hex').slice(0, 32) };
|
|
114
|
+
});
|
|
115
|
+
const core = { ...draft, updatedAt, files };
|
|
116
|
+
const version = crypto.createHash('sha256').update(JSON.stringify(core)).digest('hex').slice(0, 24);
|
|
117
|
+
return { ...core, version };
|
|
118
|
+
}
|
|
119
|
+
function readCards(root) {
|
|
120
|
+
const directory = cardDir(root);
|
|
121
|
+
if (!fs.existsSync(directory))
|
|
122
|
+
return [];
|
|
123
|
+
const entries = fs.readdirSync(directory, { withFileTypes: true })
|
|
124
|
+
.filter(entry => entry.isFile() && ID.test(entry.name.replace(/\.json$/, '')) && entry.name.endsWith('.json'));
|
|
125
|
+
if (entries.length > MAX_CARDS)
|
|
126
|
+
throw new DataRootError('CARD_LIMIT', `At most ${MAX_CARDS} output cards are allowed`);
|
|
127
|
+
const cards = [];
|
|
128
|
+
for (const entry of entries) {
|
|
129
|
+
try {
|
|
130
|
+
const file = path.join(directory, entry.name);
|
|
131
|
+
const stat = fs.lstatSync(file);
|
|
132
|
+
if (stat.isSymbolicLink() || stat.size > MAX_CARD_BYTES)
|
|
133
|
+
continue;
|
|
134
|
+
const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
135
|
+
const updatedAt = typeof raw.updatedAt === 'number' && Number.isSafeInteger(raw.updatedAt)
|
|
136
|
+
? Math.max(0, raw.updatedAt) : Math.max(0, Math.floor(stat.mtimeMs));
|
|
137
|
+
const card = toCard(root, raw, updatedAt);
|
|
138
|
+
if (card.id !== entry.name.slice(0, -5))
|
|
139
|
+
continue;
|
|
140
|
+
cards.push(card);
|
|
141
|
+
}
|
|
142
|
+
catch { /* One malformed descriptor must not hide other cards. */ }
|
|
143
|
+
}
|
|
144
|
+
return cards.sort((a, b) => b.updatedAt - a.updatedAt || a.id.localeCompare(b.id));
|
|
145
|
+
}
|
|
146
|
+
export function publishOutputCard(aid, value, resolveRoot = agentOutputDir) {
|
|
147
|
+
const root = outputRoot(aid, resolveRoot);
|
|
148
|
+
const draft = validateDraft(value);
|
|
149
|
+
const directory = cardDir(root);
|
|
150
|
+
fs.mkdirSync(directory, { recursive: true });
|
|
151
|
+
const file = path.join(directory, `${draft.id}.json`);
|
|
152
|
+
if (fs.existsSync(file) && fs.lstatSync(file).isSymbolicLink())
|
|
153
|
+
fail('Card descriptor cannot be a link');
|
|
154
|
+
if (!fs.existsSync(file) && fs.readdirSync(directory, { withFileTypes: true }).filter(item => item.isFile() && item.name.endsWith('.json')).length >= MAX_CARDS) {
|
|
155
|
+
throw new DataRootError('CARD_LIMIT', `At most ${MAX_CARDS} output cards are allowed`);
|
|
156
|
+
}
|
|
157
|
+
for (const item of draft.files)
|
|
158
|
+
checkedFile(root, item.path);
|
|
159
|
+
const valueWithTime = { ...draft, updatedAt: Date.now() };
|
|
160
|
+
if (Buffer.byteLength(JSON.stringify(valueWithTime)) > MAX_CARD_BYTES)
|
|
161
|
+
fail(`Card descriptor exceeds ${MAX_CARD_BYTES} bytes`);
|
|
162
|
+
atomicWriteJson(file, valueWithTime);
|
|
163
|
+
return toCard(root, valueWithTime, valueWithTime.updatedAt);
|
|
164
|
+
}
|
|
165
|
+
export function removeOutputCard(aid, id, resolveRoot = agentOutputDir) {
|
|
166
|
+
if (!ID.test(id))
|
|
167
|
+
fail('Card id is invalid');
|
|
168
|
+
const directory = cardDir(outputRoot(aid, resolveRoot));
|
|
169
|
+
const file = path.join(directory, `${id}.json`);
|
|
170
|
+
const existed = fs.existsSync(file);
|
|
171
|
+
atomicRemove(file);
|
|
172
|
+
return existed;
|
|
173
|
+
}
|
|
174
|
+
export class OutputCardsService {
|
|
175
|
+
aid;
|
|
176
|
+
options;
|
|
177
|
+
projection = { epoch: crypto.randomBytes(12).toString('hex'), seq: 0, revision: '', cards: new Map(), log: [] };
|
|
178
|
+
cached = new Map();
|
|
179
|
+
flights = new Map();
|
|
180
|
+
closed = false;
|
|
181
|
+
constructor(aid, options = {}) {
|
|
182
|
+
this.aid = aid;
|
|
183
|
+
this.options = options;
|
|
184
|
+
}
|
|
185
|
+
async handle(message) {
|
|
186
|
+
if (this.closed)
|
|
187
|
+
throw new DataRootError('OUTPUT_UNAVAILABLE', 'Output cards service is closed');
|
|
188
|
+
if (!isOutputCardsType(message.type))
|
|
189
|
+
throw new DataRootError('UNKNOWN_TYPE', 'Unknown output card query');
|
|
190
|
+
if (!message.encrypted)
|
|
191
|
+
throw new DataRootError('ENCRYPTION_REQUIRED', 'Output card queries require encryption');
|
|
192
|
+
const generation = await (this.options.authorize ?? authorizeOutput)(this.aid, message.fromAid);
|
|
193
|
+
const ensure = () => {
|
|
194
|
+
if (this.closed || !(this.options.current ?? currentOutputOwner)(this.aid, message.fromAid, generation)) {
|
|
195
|
+
this.cached.clear();
|
|
196
|
+
throw new DataRootError('OUTPUT_FORBIDDEN', 'Output authorization changed');
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
ensure();
|
|
200
|
+
const args = message.payload.data;
|
|
201
|
+
if (!args || typeof args !== 'object' || Array.isArray(args))
|
|
202
|
+
throw new DataRootError('INVALID_ARGUMENT', 'data must be an object');
|
|
203
|
+
const data = args;
|
|
204
|
+
const action = message.type.split('.').at(-1);
|
|
205
|
+
const allowed = {
|
|
206
|
+
snapshot: ['protocolVersion', 'limit', 'knownRevision'], list: ['protocolVersion', 'limit', 'pageCursor'],
|
|
207
|
+
detail: ['protocolVersion', 'id'], changes: ['protocolVersion', 'cursor'],
|
|
208
|
+
};
|
|
209
|
+
if (data.protocolVersion !== 1 || Object.keys(data).some(key => !allowed[action].includes(key)))
|
|
210
|
+
throw new DataRootError('INVALID_ARGUMENT', 'Unsupported output card query parameters');
|
|
211
|
+
if (action === 'detail' && (typeof data.id !== 'string' || !ID.test(data.id)))
|
|
212
|
+
throw new DataRootError('INVALID_ARGUMENT', 'Invalid output card id');
|
|
213
|
+
if (action === 'changes' && (typeof data.cursor !== 'string' || data.cursor.length > 128))
|
|
214
|
+
throw new DataRootError('INVALID_ARGUMENT', 'A bounded change cursor is required');
|
|
215
|
+
if (data.limit !== undefined && (!Number.isSafeInteger(data.limit) || Number(data.limit) < 1 || Number(data.limit) > MAX_PAGE))
|
|
216
|
+
throw new DataRootError('INVALID_ARGUMENT', `Output card page limit must be between 1 and ${MAX_PAGE}`);
|
|
217
|
+
const fingerprint = JSON.stringify([message.type, data]);
|
|
218
|
+
const key = `${generation}:${message.fromAid}:${message.requestId}`;
|
|
219
|
+
const saved = this.cached.get(key);
|
|
220
|
+
if (saved && saved.until > Date.now()) {
|
|
221
|
+
if (saved.fingerprint !== fingerprint)
|
|
222
|
+
throw new DataRootError('REQUEST_ID_CONFLICT', 'request_id was reused');
|
|
223
|
+
return saved.result;
|
|
224
|
+
}
|
|
225
|
+
const flight = this.flights.get(key);
|
|
226
|
+
if (flight && flight.fingerprint !== fingerprint)
|
|
227
|
+
throw new DataRootError('REQUEST_ID_CONFLICT', 'request_id was reused');
|
|
228
|
+
if (!flight && this.flights.size >= 3)
|
|
229
|
+
throw new DataRootError('RATE_LIMITED', 'Output card query concurrency exceeded');
|
|
230
|
+
const result = flight?.result ?? Promise.resolve().then(() => this.query(action, data));
|
|
231
|
+
if (!flight)
|
|
232
|
+
this.flights.set(key, { fingerprint, result });
|
|
233
|
+
try {
|
|
234
|
+
const response = await result;
|
|
235
|
+
ensure();
|
|
236
|
+
this.cached.set(key, { until: Date.now() + 30_000, fingerprint, result: response });
|
|
237
|
+
while (this.cached.size > 32)
|
|
238
|
+
this.cached.delete(this.cached.keys().next().value);
|
|
239
|
+
return response;
|
|
240
|
+
}
|
|
241
|
+
finally {
|
|
242
|
+
this.flights.delete(key);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
query(action, data) {
|
|
246
|
+
const root = outputRoot(this.aid, this.options.root);
|
|
247
|
+
const cards = readCards(root);
|
|
248
|
+
const next = new Map(cards.map(card => [card.id, card]));
|
|
249
|
+
const revision = crypto.createHash('sha256').update(JSON.stringify(cards.map(card => [card.id, card.version]))).digest('hex').slice(0, 24);
|
|
250
|
+
if (revision !== this.projection.revision) {
|
|
251
|
+
const previous = this.projection.cards;
|
|
252
|
+
const upserts = [...next].filter(([id, card]) => previous.get(id)?.version !== card.version).map(([id]) => id);
|
|
253
|
+
const deletes = [...previous.keys()].filter(id => !next.has(id));
|
|
254
|
+
this.projection.seq++;
|
|
255
|
+
this.projection.revision = revision;
|
|
256
|
+
this.projection.cards = next;
|
|
257
|
+
this.projection.log.push({ seq: this.projection.seq, revision, upserts, deletes, reset: upserts.length > 100 || deletes.length > 100 });
|
|
258
|
+
while (this.projection.log.length > 64)
|
|
259
|
+
this.projection.log.shift();
|
|
260
|
+
}
|
|
261
|
+
const cursor = `${this.projection.epoch}.${this.projection.seq}`;
|
|
262
|
+
const notifications = this.options.notifications?.() ?? hasOutputCardsNotifications(this.aid);
|
|
263
|
+
if (action === 'detail') {
|
|
264
|
+
const card = next.get(data.id);
|
|
265
|
+
if (!card)
|
|
266
|
+
throw new DataRootError('NOT_FOUND', 'Output card was removed');
|
|
267
|
+
return { protocol: 'evol.output-cards', protocolVersion: 1, sourceAid: this.aid, revision, cursor, generatedAt: Date.now(), notifications: notifications ? { busAid: this.aid, event: OUTPUT_CARDS_EVENT } : null, items: [card], nextCursor: null };
|
|
268
|
+
}
|
|
269
|
+
if (action === 'changes') {
|
|
270
|
+
const match = /^([a-f0-9]{24})\.(\d+)$/.exec(data.cursor);
|
|
271
|
+
const seq = match ? Number(match[2]) : -1;
|
|
272
|
+
const reset = !match || match[1] !== this.projection.epoch || seq > this.projection.seq || seq < (this.projection.log[0]?.seq ?? 1) - 1;
|
|
273
|
+
const changes = this.projection.log.filter(row => row.seq > seq);
|
|
274
|
+
const ids = [...new Set(changes.flatMap(row => row.upserts))];
|
|
275
|
+
const deletes = [...new Set(changes.flatMap(row => row.deletes))].filter(id => !next.has(id));
|
|
276
|
+
const needsReset = reset || changes.some(row => row.reset) || ids.length > MAX_PAGE || deletes.length > 100;
|
|
277
|
+
return { protocol: 'evol.output-cards', protocolVersion: 1, sourceAid: this.aid, revision, cursor, generatedAt: Date.now(), notifications: notifications ? { busAid: this.aid, event: OUTPUT_CARDS_EVENT } : null, items: needsReset ? [] : ids.flatMap(id => next.has(id) ? [next.get(id)] : []), nextCursor: null, reset: needsReset, deletes: needsReset ? [] : deletes };
|
|
278
|
+
}
|
|
279
|
+
const limit = Number(data.limit ?? MAX_PAGE);
|
|
280
|
+
let offset = 0;
|
|
281
|
+
if (data.pageCursor !== undefined) {
|
|
282
|
+
try {
|
|
283
|
+
const page = JSON.parse(Buffer.from(String(data.pageCursor), 'base64url').toString());
|
|
284
|
+
if (page.epoch !== this.projection.epoch || page.revision !== revision || !Number.isSafeInteger(page.offset) || Number(page.offset) < 0 || Number(page.offset) > MAX_CARDS)
|
|
285
|
+
throw new Error();
|
|
286
|
+
offset = Number(page.offset);
|
|
287
|
+
}
|
|
288
|
+
catch {
|
|
289
|
+
throw new DataRootError('INDEX_CHANGED', 'Restart output card pagination');
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
const page = cards.slice(offset, offset + limit);
|
|
293
|
+
const response = { protocol: 'evol.output-cards', protocolVersion: 1, sourceAid: this.aid, revision, cursor, generatedAt: Date.now(), notifications: notifications ? { busAid: this.aid, event: OUTPUT_CARDS_EVENT } : null, items: page, nextCursor: offset + page.length < cards.length ? Buffer.from(JSON.stringify({ epoch: this.projection.epoch, revision, offset: offset + page.length })).toString('base64url') : null };
|
|
294
|
+
if (action === 'snapshot' && data.knownRevision === revision) {
|
|
295
|
+
response.items = [];
|
|
296
|
+
response.notModified = true;
|
|
297
|
+
}
|
|
298
|
+
return response;
|
|
299
|
+
}
|
|
300
|
+
close() { this.closed = true; this.cached.clear(); this.flights.clear(); }
|
|
301
|
+
}
|
|
302
|
+
let outputCardsNotificationsAvailable = () => false;
|
|
303
|
+
export function setOutputCardsNotificationsAvailable(available = () => false) {
|
|
304
|
+
outputCardsNotificationsAvailable = available;
|
|
305
|
+
}
|
|
306
|
+
export function hasOutputCardsNotifications(aid) { return outputCardsNotificationsAvailable(aid); }
|
|
307
|
+
export function outputCardsRequestSchema(type) {
|
|
308
|
+
const action = type.split('.').at(-1);
|
|
309
|
+
const properties = { protocolVersion: { const: 1 } };
|
|
310
|
+
const required = ['protocolVersion'];
|
|
311
|
+
if (action === 'snapshot' || action === 'list')
|
|
312
|
+
Object.assign(properties, { limit: { type: 'integer', minimum: 1, maximum: MAX_PAGE }, ...(action === 'snapshot' ? { knownRevision: { type: 'string', maxLength: 128 } } : { pageCursor: { type: 'string', maxLength: 512 } }) });
|
|
313
|
+
if (action === 'detail') {
|
|
314
|
+
properties.id = { type: 'string', pattern: '^[a-z0-9][a-z0-9._-]{0,63}$' };
|
|
315
|
+
required.push('id');
|
|
316
|
+
}
|
|
317
|
+
if (action === 'changes') {
|
|
318
|
+
properties.cursor = { type: 'string', maxLength: 128 };
|
|
319
|
+
required.push('cursor');
|
|
320
|
+
}
|
|
321
|
+
return { type: 'object', additionalProperties: false, required: ['type', 'request_id', 'data'], properties: { type: { const: type }, request_id: { type: 'string', minLength: 1, maxLength: 128 }, data: { type: 'object', additionalProperties: false, required, properties } } };
|
|
322
|
+
}
|
|
323
|
+
export function outputCardsResponseSchema() {
|
|
324
|
+
return { type: 'object', additionalProperties: false,
|
|
325
|
+
required: ['protocol', 'protocolVersion', 'sourceAid', 'revision', 'cursor', 'generatedAt', 'notifications', 'items', 'nextCursor'],
|
|
326
|
+
properties: {
|
|
327
|
+
protocol: { const: 'evol.output-cards' }, protocolVersion: { const: 1 }, sourceAid: { type: 'string', minLength: 3, maxLength: 256 },
|
|
328
|
+
revision: { type: 'string', pattern: '^[a-f0-9]{24}$' }, cursor: { type: 'string', pattern: '^[a-f0-9]{24}\\.\\d+$', maxLength: 128 }, generatedAt: { type: 'integer', minimum: 0 },
|
|
329
|
+
notifications: { anyOf: [{ type: 'null' }, { type: 'object', additionalProperties: false, required: ['busAid', 'event'], properties: { busAid: { type: 'string' }, event: { const: OUTPUT_CARDS_EVENT } } }] },
|
|
330
|
+
items: { type: 'array', maxItems: MAX_PAGE, items: { type: 'object', additionalProperties: false, required: ['schemaVersion', 'id', 'kind', 'title', 'summary', 'updatedAt', 'version', 'files'], properties: {
|
|
331
|
+
schemaVersion: { const: 1 }, id: { type: 'string', pattern: '^[a-z0-9][a-z0-9._-]{0,63}$' }, kind: { enum: KINDS }, title: { type: 'string', maxLength: 160 }, summary: { type: 'string', maxLength: 640 }, updatedAt: { type: 'integer', minimum: 0 }, version: { type: 'string', pattern: '^[a-f0-9]{24}$' },
|
|
332
|
+
files: { type: 'array', minItems: 1, maxItems: MAX_FILES, items: { type: 'object', additionalProperties: false, required: ['role', 'path', 'label', 'outputId'], properties: { role: { enum: ROLES }, path: { type: 'string', maxLength: 2048, pattern: '^output/[^\\\\:\\u0000-\\u001f\\u007f]+$' }, label: { type: 'string', maxLength: 100 }, outputId: { type: 'string', pattern: '^[a-f0-9]{32}$' } } } },
|
|
333
|
+
} } },
|
|
334
|
+
nextCursor: { anyOf: [{ type: 'null' }, { type: 'string', maxLength: 512 }] }, reset: { type: 'boolean' }, notModified: { type: 'boolean' }, deletes: { type: 'array', maxItems: 100, uniqueItems: true, items: { type: 'string', pattern: '^[a-z0-9][a-z0-9._-]{0,63}$' } },
|
|
335
|
+
} };
|
|
336
|
+
}
|
package/dist/outputs/events.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { ownerResolver, OWNERSHIP_AUTHORIZATION_MAX_AGE_MS } from '../core/ownership/owner-resolver.js';
|
|
2
2
|
import { OUTPUT_EVENT } from './protocol.js';
|
|
3
|
+
import { OUTPUT_CARDS_EVENT } from './protocol.js';
|
|
3
4
|
import { WORKBENCH_EVENT } from '../workbench/protocol.js';
|
|
4
|
-
export const PRIVATE_PROJECTION_EVENTS = [OUTPUT_EVENT, WORKBENCH_EVENT];
|
|
5
|
+
export const PRIVATE_PROJECTION_EVENTS = [OUTPUT_EVENT, OUTPUT_CARDS_EVENT, WORKBENCH_EVENT];
|
|
5
6
|
/** Fixed event shares the configured Bus. No pack, connection or switch is created. */
|
|
6
7
|
export function registerOutputEvent(state) {
|
|
7
8
|
const conflicts = state.enabledPacks.filter(pack => pack.register.some(item => PRIVATE_PROJECTION_EVENTS.some(event => event === item.event)));
|
|
@@ -12,7 +13,7 @@ export function registerOutputEvent(state) {
|
|
|
12
13
|
state.catalog = state.catalog.filter(item => !PRIVATE_PROJECTION_EVENTS.some(event => event === item.event) && !ids.has(item.sourcePackId));
|
|
13
14
|
for (const event of PRIVATE_PROJECTION_EVENTS)
|
|
14
15
|
state.catalog.push({ event, ttl: 30, maxTtl: 60,
|
|
15
|
-
schemaVersion: 1, sourcePackId: event ===
|
|
16
|
+
schemaVersion: 1, sourcePackId: event === WORKBENCH_EVENT ? 'builtin.workbench' : 'builtin.outputs' });
|
|
16
17
|
}
|
|
17
18
|
export function outputAllowlist(aid, result) {
|
|
18
19
|
const owner = ownerResolver.snapshot(aid);
|
package/dist/outputs/protocol.js
CHANGED
|
@@ -2,6 +2,7 @@ import crypto from 'node:crypto';
|
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { parseDocument } from 'yaml';
|
|
4
4
|
export const OUTPUT_EVENT = 'team.outputs.changed';
|
|
5
|
+
export const OUTPUT_CARDS_EVENT = 'team.output-cards.changed';
|
|
5
6
|
export const OUTPUT_TYPES = ['snapshot', 'list', 'detail', 'changes'].map(action => `services.outputs.${action}`);
|
|
6
7
|
export const isOutputType = (type) => OUTPUT_TYPES.includes(type);
|
|
7
8
|
export const outputId = (relative) => crypto.createHash('sha256').update(relative).digest('hex').slice(0, 32);
|
package/dist/outputs/service.js
CHANGED
|
@@ -4,7 +4,7 @@ import crypto from 'node:crypto';
|
|
|
4
4
|
import { agentOutputDir } from '../paths.js';
|
|
5
5
|
import { TeamWorkspaceStore, DataRootError } from '../core/command/team-workspace-store.js';
|
|
6
6
|
import { TeamWorkspaceItemsIndex } from '../core/command/team-workspace-items.js';
|
|
7
|
-
import {
|
|
7
|
+
import { currentOutputOwner, authorizeOutput } from './authorization.js';
|
|
8
8
|
import { isOutputType, outputId, outputItem, outputKind, OUTPUT_EVENT } from './protocol.js';
|
|
9
9
|
let outputChangePublisher;
|
|
10
10
|
let outputNotificationsAvailable = () => false;
|
|
@@ -51,20 +51,7 @@ class OutputStore extends TeamWorkspaceStore {
|
|
|
51
51
|
entries: [{ id: 'output', title: 'Output', path: 'output', kind: 'directory', order: 0 }] };
|
|
52
52
|
}
|
|
53
53
|
}
|
|
54
|
-
export
|
|
55
|
-
const view = await ownerResolver.refresh(aid, { maxAgeMs: OWNERSHIP_AUTHORIZATION_MAX_AGE_MS, source: 'outputs.read', allowTransient: false });
|
|
56
|
-
if (view.authorizationStatus !== 'verified' || view.ownerAid !== from || view.refreshFailure?.fallbackUsed
|
|
57
|
-
|| (view.validUntil ?? 0) <= Date.now()) {
|
|
58
|
-
throw new DataRootError('OUTPUT_FORBIDDEN', 'Current protocol Owner authorization is required');
|
|
59
|
-
}
|
|
60
|
-
return `${view.ownerAid}:${view.revision}`;
|
|
61
|
-
}
|
|
62
|
-
export function currentOutputOwner(aid, from, generation) {
|
|
63
|
-
const view = ownerResolver.snapshot(aid);
|
|
64
|
-
return view.authorizationStatus === 'verified' && !view.refreshFailure?.fallbackUsed
|
|
65
|
-
&& (view.validUntil ?? 0) > Date.now()
|
|
66
|
-
&& view.ownerAid === from && `${view.ownerAid}:${view.revision}` === generation;
|
|
67
|
-
}
|
|
54
|
+
export { authorizeOutput, currentOutputOwner } from './authorization.js';
|
|
68
55
|
export class OutputService {
|
|
69
56
|
aid;
|
|
70
57
|
options;
|
package/dist/services/index.js
CHANGED
|
@@ -12,6 +12,7 @@ import { IdempotencyStore } from './idempotency.js';
|
|
|
12
12
|
import { readLocalSelfIdentity } from './identity.js';
|
|
13
13
|
import { writeServicesIndex } from './index-generator.js';
|
|
14
14
|
import { servicePackLedger as packLedger, routerLedger, ServiceLedger } from '../core/pack-ledger.js';
|
|
15
|
+
import { scheduleServicesAclHarden } from '../core/permission/services-path-acl.js';
|
|
15
16
|
import { ServiceMessageLog } from './message-log.js';
|
|
16
17
|
import { buildPackState, loadPackDir, loadPacks } from './pack-manager.js';
|
|
17
18
|
import { DEFAULT_ROUTER_CONFIG, loadRouterConfig, RateLimiter } from './router.js';
|
|
@@ -22,10 +23,11 @@ import { errorMessage } from './types.js';
|
|
|
22
23
|
import { isOutputType } from '../outputs/protocol.js';
|
|
23
24
|
import { outputRequestSchema, outputResponseSchema } from '../outputs/protocol.js';
|
|
24
25
|
import { OutputService } from '../outputs/service.js';
|
|
26
|
+
import { isOutputCardsType, outputCardsRequestSchema, outputCardsResponseSchema, OutputCardsService, OUTPUT_CARDS_TYPES } from '../outputs/cards.js';
|
|
25
27
|
import { DataRootError } from '../core/command/team-workspace-store.js';
|
|
26
28
|
import { isWorkbenchType, WORKBENCH_TYPES, workbenchRequestSchema, workbenchResponseSchema } from '../workbench/protocol.js';
|
|
27
29
|
import { WorkbenchService } from '../workbench/service.js';
|
|
28
|
-
export { classifyServicePayloadType, parseServiceType, isReservedServiceType, RESERVED_TYPES } from './service-payload.js';
|
|
30
|
+
export { classifyServicePayloadType, parseServiceType, isReservedServiceType, isProjectionServiceResult, RESERVED_TYPES } from './service-payload.js';
|
|
29
31
|
export { readLocalSelfIdentity } from './identity.js';
|
|
30
32
|
/**
|
|
31
33
|
* 未准入调用的回复预算。
|
|
@@ -63,6 +65,7 @@ export class ServiceRouter {
|
|
|
63
65
|
unauthorizedNotified = new Map();
|
|
64
66
|
started = false;
|
|
65
67
|
outputService;
|
|
68
|
+
outputCardsService;
|
|
66
69
|
workbenchService;
|
|
67
70
|
constructor(servicesDir, deps, limits,
|
|
68
71
|
/**
|
|
@@ -81,6 +84,7 @@ export class ServiceRouter {
|
|
|
81
84
|
this.scriptRunner = new ServiceScriptRunner(deps);
|
|
82
85
|
this.dispatcher = new ServiceDispatcher(this.scriptRunner, limits);
|
|
83
86
|
this.outputService = deps.outputService ?? new OutputService(deps.aid);
|
|
87
|
+
this.outputCardsService = new OutputCardsService(deps.aid);
|
|
84
88
|
this.workbenchService = deps.workbenchService ?? new WorkbenchService(deps.aid, { offline: readonlySnapshot });
|
|
85
89
|
}
|
|
86
90
|
/** 首次加载:读 services-config.json + 扫描包。identity 必须已就绪。重复调用只更新 identity。 */
|
|
@@ -90,6 +94,14 @@ export class ServiceRouter {
|
|
|
90
94
|
return;
|
|
91
95
|
this.reload();
|
|
92
96
|
this.started = true;
|
|
97
|
+
// ACL 兜底层自愈:存量包(加固逻辑上线前装的、或目录从别的机器拷贝来的)在这里收敛,
|
|
98
|
+
// 新包由 `pack add` 当场处理。用户不需要知道 ACL 存在。
|
|
99
|
+
//
|
|
100
|
+
// 异步 + 进程内去重:调度立即返回(实测 0ms),加固在后台子进程里跑,
|
|
101
|
+
// 不阻塞启动、不阻塞包执行。只读快照(offline router)不参与,查询不该改磁盘状态。
|
|
102
|
+
if (!this.readonlySnapshot) {
|
|
103
|
+
scheduleServicesAclHarden(this.servicesDir, message => logger.warn(`[Services] ${message}`));
|
|
104
|
+
}
|
|
93
105
|
}
|
|
94
106
|
/** 重新加载 services-config.json 与全部包(ec services reload / 热重载用)。 */
|
|
95
107
|
reload() {
|
|
@@ -214,7 +226,7 @@ export class ServiceRouter {
|
|
|
214
226
|
this.rejectLedger('BLOCKED', type, message);
|
|
215
227
|
return buildSilentReply(type, message.requestId);
|
|
216
228
|
}
|
|
217
|
-
if (isOutputType(type) || isWorkbenchType(type)) {
|
|
229
|
+
if (isOutputType(type) || isOutputCardsType(type) || isWorkbenchType(type)) {
|
|
218
230
|
if (options.admission === 'not_authorized')
|
|
219
231
|
return this.unauthorizedReply(type, message, 'business');
|
|
220
232
|
const rule = this.callRuleFor(type);
|
|
@@ -224,7 +236,11 @@ export class ServiceRouter {
|
|
|
224
236
|
if (!limit.allow)
|
|
225
237
|
return buildErrorReply(type, message.requestId, 'RATE_LIMITED', 'Output query rate exceeded');
|
|
226
238
|
try {
|
|
227
|
-
const data =
|
|
239
|
+
const data = isWorkbenchType(type)
|
|
240
|
+
? await this.workbenchService.handle(message)
|
|
241
|
+
: isOutputCardsType(type)
|
|
242
|
+
? await this.outputCardsService.handle(message)
|
|
243
|
+
: await this.outputService.handle(message);
|
|
228
244
|
return buildSuccessReply(type, message.requestId, data);
|
|
229
245
|
}
|
|
230
246
|
catch (error) {
|
|
@@ -447,7 +463,7 @@ export class ServiceRouter {
|
|
|
447
463
|
catch { /* private capabilities */ }
|
|
448
464
|
const native = [...outputs, ...(workbenchAuthorized ? this.workbenchDescriptions() : [])];
|
|
449
465
|
const requestedService = readStringField(message.payload, 'service');
|
|
450
|
-
if (requestedService && isOutputType(requestedService) && !outputAuthorized) {
|
|
466
|
+
if (requestedService && (isOutputType(requestedService) || isOutputCardsType(requestedService)) && !outputAuthorized) {
|
|
451
467
|
return buildErrorReply(type, message.requestId, 'OUTPUT_FORBIDDEN', 'Current protocol Owner authorization is required');
|
|
452
468
|
}
|
|
453
469
|
if (requestedService && isWorkbenchType(requestedService) && !workbenchAuthorized) {
|
|
@@ -480,6 +496,10 @@ export class ServiceRouter {
|
|
|
480
496
|
return buildSuccessReply(type, message.requestId, {
|
|
481
497
|
type: target, schema: workbenchRequestSchema(target), responseDataSchema: workbenchResponseSchema(target),
|
|
482
498
|
});
|
|
499
|
+
if (isOutputCardsType(target))
|
|
500
|
+
return buildSuccessReply(type, message.requestId, {
|
|
501
|
+
type: target, schema: outputCardsRequestSchema(target), responseDataSchema: outputCardsResponseSchema(),
|
|
502
|
+
});
|
|
483
503
|
if (isOutputType(target))
|
|
484
504
|
return buildSuccessReply(type, message.requestId, {
|
|
485
505
|
type: target, schema: outputRequestSchema(target), responseDataSchema: outputResponseSchema(),
|
|
@@ -496,6 +516,9 @@ export class ServiceRouter {
|
|
|
496
516
|
if (isWorkbenchType(target))
|
|
497
517
|
return buildSuccessReply(type, message.requestId, { type: target,
|
|
498
518
|
skill: 'Read-only Owner-private workbench. Requires encrypted AUN and the current verified protocol Owner. Send protocolVersion:1. Snapshot includes current tasks and retained past executions only; no future schedules. Subscribe to team.workbench.changed on the same Bus and read changes when invalidated. Results are bounded; follow history nextCursor, reset on INDEX_CHANGED. Never poll. Task details use the existing Activity command with taskId.' });
|
|
519
|
+
if (isOutputCardsType(target))
|
|
520
|
+
return buildSuccessReply(type, message.requestId, { type: target,
|
|
521
|
+
skill: 'Owner-authorized output card projection. Cards are declaration-only metadata linked to real files in this Agent output. Use services.outputs.cards.snapshot/list/detail/changes, follow nextCursor, and reset on INDEX_CHANGED. Never poll. Publish or remove cards with ec team cards after referenced files are complete.' });
|
|
499
522
|
if (isOutputType(target))
|
|
500
523
|
return buildSuccessReply(type, message.requestId, { type: target,
|
|
501
524
|
skill: 'Read-only fixed Agent output. Requires encrypted AUN and current verified protocol Owner. Send protocolVersion:1 and the schema-defined data fields. Results are bounded; follow nextCursor and reset on INDEX_CHANGED. No periodic reads.' });
|
|
@@ -608,13 +631,14 @@ export class ServiceRouter {
|
|
|
608
631
|
close() {
|
|
609
632
|
this.dispatcher.close();
|
|
610
633
|
void this.outputService.close();
|
|
634
|
+
this.outputCardsService.close();
|
|
611
635
|
this.workbenchService.close();
|
|
612
636
|
}
|
|
613
637
|
outputDescriptions() {
|
|
614
638
|
return [{
|
|
615
639
|
pack: 'builtin.outputs', name: 'Agent output projection',
|
|
616
640
|
description: 'Owner-authorized read-only Agent output snapshots and changes',
|
|
617
|
-
types: ['services.outputs.snapshot', 'services.outputs.list', 'services.outputs.detail', 'services.outputs.changes'],
|
|
641
|
+
types: ['services.outputs.snapshot', 'services.outputs.list', 'services.outputs.detail', 'services.outputs.changes', ...OUTPUT_CARDS_TYPES],
|
|
618
642
|
unmatched: 'silent', reply: true,
|
|
619
643
|
}];
|
|
620
644
|
}
|
|
@@ -23,6 +23,7 @@ import { getAunRequestRegistry } from '../core/message/aun-request-registry.js';
|
|
|
23
23
|
import { ServiceError, errorMessage } from './types.js';
|
|
24
24
|
import { authorizePackTarget, packOperation } from '../core/pack-auth.js';
|
|
25
25
|
import { installPack, listPackDirs, removePack, setPackEnabled } from '../core/pack-install.js';
|
|
26
|
+
import { hardenServicesAcl, planServicesAclRepair, readServicesAcl } from '../core/permission/services-path-acl.js';
|
|
26
27
|
const HELP = `ec services — 服务路由运维
|
|
27
28
|
|
|
28
29
|
用法:
|
|
@@ -31,6 +32,7 @@ const HELP = `ec services — 服务路由运维
|
|
|
31
32
|
ec services ledger <包名> [--tail N] [--aid <aid>] 台账
|
|
32
33
|
ec services tail <包名> [--tail N] [--aid <aid>] 服务消息日志
|
|
33
34
|
ec services doctor [<包名>] [--aid <aid>] 诊断
|
|
35
|
+
ec services repair-acl [--aid <aid>] 收紧 services/ 的 NTFS ACL(幂等,仅 Windows)
|
|
34
36
|
ec services reload [--aid <aid>] 重载(全部包)
|
|
35
37
|
ec services enable / disable [--aid <aid>] 总闸
|
|
36
38
|
ec services rules show [<type>] [--aid <aid>] 调用准入规则
|
|
@@ -355,6 +357,23 @@ async function execute(deps, parsed) {
|
|
|
355
357
|
}
|
|
356
358
|
case 'doctor':
|
|
357
359
|
return { ok: true, result: { aid, findings: doctor(aid, router, parsed.pack) } };
|
|
360
|
+
case 'repair-acl': {
|
|
361
|
+
// 幂等收口:历史包(装包时还没有加固逻辑)靠这条命令补齐。
|
|
362
|
+
// 加固只改 ACL、不碰文件内容,失败也只报告不抛出。
|
|
363
|
+
const result = hardenServicesAcl(servicesDir);
|
|
364
|
+
return {
|
|
365
|
+
ok: result.errors.length === 0,
|
|
366
|
+
...(result.errors.length > 0 ? { code: 'ACL_HARDEN_FAILED', error: result.errors.join('; ') } : {}),
|
|
367
|
+
result: {
|
|
368
|
+
aid,
|
|
369
|
+
servicesDir,
|
|
370
|
+
changed: result.changed,
|
|
371
|
+
plans: result.plans
|
|
372
|
+
.filter(item => item.plan.removeSids.length > 0 || item.plan.needsDenyWrite)
|
|
373
|
+
.map(item => ({ path: item.path, removeSids: item.plan.removeSids, addDenyWrite: item.plan.needsDenyWrite })),
|
|
374
|
+
},
|
|
375
|
+
};
|
|
376
|
+
}
|
|
358
377
|
case 'reload': {
|
|
359
378
|
// 不支持单包重载:`reload()` 全量重扫。曾把位置参数原样回显成
|
|
360
379
|
// `reloaded: <包名>`,等于向调用方谎报"只重载了一个包"。
|
|
@@ -408,12 +427,19 @@ async function execute(deps, parsed) {
|
|
|
408
427
|
// 配置存在但坏了:装包成功、总闸却回落到 enabled=false,业务消息全被静默丢弃。
|
|
409
428
|
// 不替用户改文件,但必须把原因带回去。
|
|
410
429
|
const configErrors = createdRouter ? [] : loadRouterConfig(servicesDirForPack).errors;
|
|
430
|
+
// ACL 加固:新包目录与 services 根都要收口。失败不阻断安装——包已经 rename
|
|
431
|
+
// 到位,加固只是加一层兜底;把原因带回去,`doctor` 也会持续报。
|
|
432
|
+
const acl = hardenServicesAcl(servicesDirForPack);
|
|
433
|
+
if (acl.errors.length > 0) {
|
|
434
|
+
logger.warn(`[Services] services ACL hardening failed for aid=${aid}: ${acl.errors.join('; ')}`);
|
|
435
|
+
}
|
|
411
436
|
return {
|
|
412
437
|
ok: true,
|
|
413
438
|
result: {
|
|
414
439
|
aid, ...installed,
|
|
415
440
|
...(createdRouter ? { createdRouter: true } : {}),
|
|
416
441
|
...(configErrors.length > 0 ? { configErrors } : {}),
|
|
442
|
+
...(acl.errors.length > 0 ? { aclErrors: acl.errors } : {}),
|
|
417
443
|
},
|
|
418
444
|
};
|
|
419
445
|
}
|
|
@@ -642,8 +668,66 @@ function doctor(aid, router, only) {
|
|
|
642
668
|
}
|
|
643
669
|
// 6. services/ 未进 L_CLASS(由 protected-paths 的运行时常量核对)。
|
|
644
670
|
findings.push(lClassFinding());
|
|
671
|
+
// 7. ACL 兜底层:沙箱组不得对包代码与声明持有写权限。
|
|
672
|
+
findings.push(servicesAclFinding(aid, only));
|
|
645
673
|
return findings;
|
|
646
674
|
}
|
|
675
|
+
/**
|
|
676
|
+
* `services/` 的 ACL 兜底层是否生效。
|
|
677
|
+
*
|
|
678
|
+
* policy 层的写拒绝来自「没有 write 授权」,只有这一层时任何一个策略放宽都会直接
|
|
679
|
+
* 让包脚本能自改代码。这里报告的是**ACL 层有没有第二道门**:
|
|
680
|
+
* - 存在非继承的写授权(沙箱组 / 外来机器 SID)→ `warn`,给出修复命令;
|
|
681
|
+
* - 缺少 DENY(写) 兜底 → `warn`;
|
|
682
|
+
* - 非 Windows 或本机没有沙箱组 → `ok` + 说明(没有可加固对象)。
|
|
683
|
+
*/
|
|
684
|
+
function servicesAclFinding(aid, only) {
|
|
685
|
+
if (process.platform !== 'win32') {
|
|
686
|
+
return { level: 'ok', check: 'acl', detail: 'not applicable on this platform (Windows-only hardening)' };
|
|
687
|
+
}
|
|
688
|
+
const servicesDir = agentServicesDir(aid);
|
|
689
|
+
let snapshot;
|
|
690
|
+
try {
|
|
691
|
+
snapshot = readServicesAcl(servicesDir);
|
|
692
|
+
}
|
|
693
|
+
catch (error) {
|
|
694
|
+
return { level: 'warn', check: 'acl', detail: `cannot read ACL: ${errorMessage(error)}` };
|
|
695
|
+
}
|
|
696
|
+
if (!snapshot.sandboxSid) {
|
|
697
|
+
return { level: 'ok', check: 'acl', detail: 'CodexSandboxUsers group not present; sandbox scripts cannot run as a sandbox identity' };
|
|
698
|
+
}
|
|
699
|
+
const rows = snapshot.entries
|
|
700
|
+
.filter(entry => !only || sameAsPackDir(entry.path, servicesDir, only))
|
|
701
|
+
.map(entry => ({ path: entry.path, plan: planServicesAclRepair(entry.aces, snapshot) }));
|
|
702
|
+
const violations = rows.flatMap(row => row.plan.violations.map(detail => `${relativeTo(servicesDir, row.path)}: ${detail}`));
|
|
703
|
+
const missingDeny = rows.filter(row => row.plan.needsDenyWrite && samePathWith(row.path, servicesDir));
|
|
704
|
+
if (violations.length === 0 && missingDeny.length === 0) {
|
|
705
|
+
return { level: 'ok', check: 'acl', detail: 'no explicit write grant for the sandbox group; DENY(write) in place' };
|
|
706
|
+
}
|
|
707
|
+
const parts = [];
|
|
708
|
+
if (violations.length > 0)
|
|
709
|
+
parts.push(`explicit write grants: ${violations.slice(0, 5).join('; ')}${violations.length > 5 ? ` (+${violations.length - 5} more)` : ''}`);
|
|
710
|
+
if (missingDeny.length > 0)
|
|
711
|
+
parts.push('services root lacks an inheritable DENY(write) for the sandbox group');
|
|
712
|
+
return {
|
|
713
|
+
level: 'warn',
|
|
714
|
+
check: 'acl',
|
|
715
|
+
detail: `${parts.join(' / ')}. Run "ec services repair-acl${only ? '' : ` --aid ${aid}`}" to harden.`,
|
|
716
|
+
};
|
|
717
|
+
}
|
|
718
|
+
/** `packDir` 是否是 `servicesDir/<only>` 自身或其子路径。 */
|
|
719
|
+
function sameAsPackDir(candidate, servicesDir, pack) {
|
|
720
|
+
const base = path.join(servicesDir, pack).toLowerCase();
|
|
721
|
+
const value = path.resolve(candidate).toLowerCase();
|
|
722
|
+
return value === base || value.startsWith(`${base}${path.sep}`);
|
|
723
|
+
}
|
|
724
|
+
function samePathWith(left, right) {
|
|
725
|
+
return path.resolve(left).toLowerCase() === path.resolve(right).toLowerCase();
|
|
726
|
+
}
|
|
727
|
+
function relativeTo(base, target) {
|
|
728
|
+
const relative = path.relative(path.resolve(base), path.resolve(target));
|
|
729
|
+
return relative || '.';
|
|
730
|
+
}
|
|
647
731
|
/** 运行期核对 L_CLASS 是否覆盖每个 agent 的 services 目录。 */
|
|
648
732
|
function lClassFinding() {
|
|
649
733
|
try {
|
|
@@ -161,6 +161,7 @@ export function buildPackState(packs, invalidPacks, identity) {
|
|
|
161
161
|
for (const pack of candidates) {
|
|
162
162
|
const reserved = pack.listen.filter(entry => entry.type === 'services.outputs.snapshot' || entry.type === 'services.outputs.list'
|
|
163
163
|
|| entry.type === 'services.outputs.detail' || entry.type === 'services.outputs.changes'
|
|
164
|
+
|| entry.type.startsWith('services.outputs.cards.')
|
|
164
165
|
|| entry.type === 'services.outputs.*' || entry.type.startsWith('services.workbench.'));
|
|
165
166
|
if (reserved.length) {
|
|
166
167
|
reservedOutputInvalid.push({
|