evolcore 0.0.47 → 0.0.49
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +90 -1
- package/bin/ec-build.mjs +86 -0
- package/dist/agent-template/jobs.js +12 -4
- package/dist/agent-template/runtime.js +143 -40
- package/dist/agent-template/service.js +66 -13
- package/dist/agents/baseagent.js +60 -20
- package/dist/agents/claude-runner.js +34 -17
- package/dist/agents/codex-runner.js +36 -17
- package/dist/agents/ecagent-runner.js +7 -4
- package/dist/agents/gemini-runner.js +5 -2
- package/dist/agents/runner-types.js +5 -21
- package/dist/aun/aid/agentmd.js +5 -1
- package/dist/aun/msg/p2p.js +2 -1
- package/dist/aun/service-proxy.js +4 -2
- package/dist/build-identity.json +1 -0
- package/dist/channels/aun.js +722 -295
- package/dist/channels/daemon.js +9 -25
- package/dist/cli/aun-commands.js +86 -51
- package/dist/cli/code-stats.js +19 -8
- package/dist/cli/command-log.js +1 -1
- package/dist/cli/daemon-commands.js +44 -43
- package/dist/cli/directory.js +13 -2
- package/dist/cli/ecmsg-gateway.js +5 -2
- package/dist/cli/index.js +9 -9
- package/dist/cli/init-channel.js +4 -6
- package/dist/cli/init.js +72 -50
- package/dist/cli/invoke-command.js +1 -1
- package/dist/cli/managed-command-guard.js +2 -0
- package/dist/cli/model.js +20 -5
- package/dist/cli/provider-command.js +74 -13
- package/dist/cli/quota.js +89 -0
- package/dist/cli/role.js +62 -17
- package/dist/cli/services-command.js +1 -0
- package/dist/cli/stats.js +3 -3
- package/dist/cli/team-workspace-command.js +56 -2
- package/dist/cli/thread-command.js +16 -51
- package/dist/config/boot-log.js +3 -9
- package/dist/config/builtin-roles.js +5 -7
- package/dist/config/config-field-policy.js +71 -1
- package/dist/config/config-manager.js +13 -7
- package/dist/config/daemon-services.js +30 -3
- package/dist/config/gateway-config.js +2 -2
- package/dist/config/invoke-ipc-service.js +6 -4
- package/dist/config/peer-bind-code.js +3 -4
- package/dist/config/peer-book-store.js +62 -229
- package/dist/config/peer-book.js +26 -27
- package/dist/config/peer-role-resolver.js +16 -1
- package/dist/config/provider-identity-migration.js +4 -1
- package/dist/config/provider-ipc-service.js +56 -11
- package/dist/config/provider-menu-request.js +24 -5
- package/dist/config/provider-templates.js +127 -0
- package/dist/config/providers-config.js +67 -12
- package/dist/config/providers-management.js +477 -51
- package/dist/config/resolved-config-op.js +3 -2
- package/dist/config/role-command-service.js +248 -1
- package/dist/config/schema-migration.js +105 -4
- package/dist/core/agent-application-service.js +6 -1
- package/dist/core/agent-runtime.js +4 -0
- package/dist/core/auth/agent-delegation.js +2 -1
- package/dist/core/auth/auth-gateway.js +2 -1
- package/dist/core/auth/delegation-authorization.js +36 -26
- package/dist/core/auth/operation-authorizer.js +25 -0
- package/dist/core/auth/operation-catalog.js +37 -64
- package/dist/core/capability/providers/codex-capability-provider.js +7 -8
- package/dist/core/channel-loader.js +18 -0
- package/dist/core/command/agent-control.js +32 -0
- package/dist/core/command/cli-intent-parser.js +13 -0
- package/dist/core/command/command-handler.js +126 -87
- package/dist/core/command/menu-catalog.js +1 -0
- package/dist/core/command/menu-handler.js +67 -150
- package/dist/core/command/menu-protocol.js +31 -1
- package/dist/core/command/provider-menu.js +13 -3
- package/dist/core/command/remote-shell.js +565 -0
- package/dist/core/command/role-menu.js +47 -23
- package/dist/core/command/slash-handler.js +26 -43
- package/dist/core/command/team-workspace-items.js +81 -12
- package/dist/core/command/team-workspace-team.js +9 -71
- package/dist/core/command/topic-slash.js +9 -30
- package/dist/core/daemon-bootstrap.js +8 -1
- package/dist/core/daemon-control.js +64 -8
- package/dist/core/daemon-lifecycle.js +16 -2
- package/dist/core/evolagent-registry.js +20 -3
- package/dist/core/file-integrity/store.js +2 -0
- package/dist/core/handoff/runtime.js +37 -1
- package/dist/core/inference/text-inference.js +3 -1
- package/dist/core/initialization/service.js +11 -6
- package/dist/core/interaction-router.js +3 -0
- package/dist/core/invoke/executors/text.js +72 -19
- package/dist/core/ipc-registration.js +3 -1
- package/dist/core/message/aun-ipc-sender.js +279 -107
- package/dist/core/message/contact-admission.js +91 -6
- package/dist/core/message/contact-pending-inbound.js +113 -0
- package/dist/core/message/contact-thread-approval.js +212 -0
- package/dist/core/message/im-renderer.js +41 -2
- package/dist/core/message/message-admission.js +5 -39
- package/dist/core/message/message-bridge.js +140 -370
- package/dist/core/message/message-log.js +29 -0
- package/dist/core/message/message-queue.js +119 -15
- package/dist/core/message/message-utils.js +8 -0
- package/dist/core/message/response-engine.js +580 -134
- package/dist/core/message/send-routing.js +5 -1
- package/dist/core/model/catalog-service.js +31 -11
- package/dist/core/model/config-scope.js +6 -14
- package/dist/core/model/model-capabilities.js +22 -4
- package/dist/core/model/model-catalog.js +1 -0
- package/dist/core/model/model-diagnostics.js +19 -0
- package/dist/core/model/model-fallback.js +13 -2
- package/dist/core/ownership/owner-resolver.js +328 -50
- package/dist/core/pack-auth.js +3 -0
- package/dist/core/pack-install.js +1 -1
- package/dist/core/permission/ec-command-parser.js +106 -19
- package/dist/core/permission/protected-paths.js +6 -6
- package/dist/core/permission/services-path-acl.js +451 -0
- package/dist/core/permission/tool-policy.js +5 -1
- package/dist/core/relation/peer-identity.js +36 -1
- package/dist/core/relation/same-owner-proof.js +81 -112
- package/dist/core/session/adapters/codex-session-file-adapter.js +96 -15
- package/dist/core/session/session-file-health.js +13 -7
- package/dist/core/session/session-fs-store.js +91 -35
- package/dist/core/session/session-manager.js +68 -24
- package/dist/core/session/session-mapper.js +14 -34
- package/dist/core/session/session-transcript.js +5 -1
- package/dist/core/task/task-activity-store.js +84 -0
- package/dist/core/task/task-recovery-service.js +13 -0
- package/dist/core/thread/command-parser.js +7 -12
- package/dist/core/thread/thread-context-storage.js +3 -2
- package/dist/core/thread/thread-operation.js +2 -13
- package/dist/core/thread/thread-service.js +15 -46
- package/dist/core/thread/topic-id.js +15 -0
- package/dist/directory/owner-directory-admission.js +12 -9
- package/dist/directory/owner-directory-cache.js +64 -28
- package/dist/directory/owner-directory-markdown.js +14 -2
- package/dist/directory/owner-directory-policy.js +5 -30
- package/dist/directory/owner-directory-query-operation.js +29 -3
- package/dist/directory/owner-directory-remarks.js +11 -3
- package/dist/directory/owner-directory-request-operation.js +5 -2
- package/dist/eck/kit-renderer.js +1 -1
- package/dist/eck/message-renderer.js +112 -29
- package/dist/ecweb/basic-settings-service.js +3 -1
- package/dist/ecweb/message-context-service.js +1 -1
- package/dist/ecweb/pairing.js +4 -3
- package/dist/ecweb/providers-service.js +26 -1
- package/dist/ecweb/runtime/lifecycle.js +18 -8
- package/dist/ecweb/runtime/proxy-access.js +74 -0
- package/dist/ecweb/runtime/supervisor.js +36 -6
- package/dist/event-center/center-config.js +9 -5
- package/dist/event-center/dispatcher.js +10 -1
- package/dist/event-center/ipc-operation.js +19 -0
- package/dist/event-center/registry.js +29 -3
- package/dist/event-center/runtime.js +106 -11
- package/dist/event-center/script-runner.js +5 -5
- package/dist/index.js +96 -59
- package/dist/ipc.js +38 -3
- package/dist/outputs/authorization.js +16 -0
- package/dist/outputs/cards.js +336 -0
- package/dist/outputs/events.js +63 -0
- package/dist/outputs/protocol.js +103 -0
- package/dist/outputs/service.js +266 -0
- package/dist/paths.js +3 -0
- package/dist/proxy/manager.js +43 -13
- package/dist/services/index.js +114 -5
- package/dist/services/ipc-operation.js +88 -15
- package/dist/services/pack-manager.js +13 -1
- package/dist/services/router.js +21 -6
- package/dist/services/script-runner.js +5 -4
- package/dist/services/service-payload.js +13 -7
- package/dist/services/validation.js +1 -1
- package/dist/stats/budget.js +2 -2
- package/dist/stats/db.js +19 -0
- package/dist/stats/index.js +1 -1
- package/dist/stats/{price-resolver.js → model-resolver.js} +304 -23
- package/dist/stats/normalizer.js +2 -0
- package/dist/stats/query.js +35 -27
- package/dist/stats/quota-query.js +95 -0
- package/dist/stats/role-budget.js +5 -2
- package/dist/stats/writer.js +10 -6
- package/dist/trigger/audit.js +7 -0
- package/dist/trigger/authorization.js +105 -11
- package/dist/trigger/feedback.js +10 -0
- package/dist/trigger/history.js +37 -11
- package/dist/trigger/ipc-service.js +12 -1
- package/dist/trigger/manager.js +1 -0
- package/dist/trigger/scheduler.js +7 -5
- package/dist/trigger/script-executor.js +2 -1
- package/dist/trigger/script-sandbox.js +21 -3
- package/dist/trigger/validation.js +22 -0
- package/dist/utils/atomic-write.js +22 -8
- package/dist/utils/cross-platform.js +73 -26
- package/dist/utils/error-dict.json +94 -4
- package/dist/utils/error-utils.js +27 -4
- package/dist/utils/evolcore-version.js +36 -65
- package/dist/utils/host-info.js +100 -1
- package/dist/utils/msg-diag.js +1 -0
- package/dist/utils/npm-ops.js +43 -8
- package/dist/utils/process-introspect.js +12 -7
- package/dist/utils/process-tree.js +50 -2
- package/dist/utils/windows-shell-trust.js +2 -0
- package/dist/workbench/protocol.js +80 -0
- package/dist/workbench/service.js +359 -0
- package/ecagent/dist/types.d.ts +6 -2
- package/kits/docs/context-assembly.md +1 -1
- package/kits/docs/evolcore/INDEX.md +4 -2
- package/kits/docs/evolcore/aid.md +25 -0
- package/kits/docs/evolcore/config.md +16 -1
- package/kits/docs/evolcore/directory.md +30 -12
- package/kits/docs/evolcore/ecweb-lifecycle.md +15 -0
- package/kits/docs/evolcore/model.md +10 -0
- package/kits/docs/evolcore/msg.md +9 -0
- package/kits/docs/evolcore/peer.md +19 -65
- package/kits/docs/evolcore/provider.md +124 -4
- package/kits/docs/evolcore/quota.md +54 -0
- package/kits/docs/evolcore/role.md +83 -0
- package/kits/docs/evolcore/services.md +6 -6
- package/kits/docs/evolcore/stats.md +2 -0
- package/kits/docs/evolcore/team-workspace.md +1 -1
- package/kits/docs/evolcore/thread-chain.md +14 -15
- package/kits/docs/evolcore/tool-authorization.md +5 -0
- package/kits/docs/evolcore/trigger.md +12 -0
- package/kits/eck_message_manifest.json +12 -0
- package/kits/provider-templates.json +1213 -0
- package/kits/rules/04-relation.md +3 -3
- package/kits/schemas/_meta.json +14 -2
- package/kits/schemas/agent-config.schema.20.json +24 -0
- package/kits/schemas/contact-book.schema.4.json +52 -0
- package/kits/schemas/providers.schema.3.json +200 -0
- package/kits/skills/.switches.json +8 -0
- package/kits/skills/ability/references/calling.md +1 -1
- package/kits/skills/agent-output-cards/SKILL.md +57 -0
- package/kits/skills/ec-group/SKILL.md +2 -2
- package/kits/skills/ec-identity/SKILL.md +19 -72
- package/kits/skills/ec-provider/SKILL.md +270 -0
- package/kits/skills/ec-provider/scripts/check-model.mjs +80 -0
- package/kits/skills/ec-trigger/SKILL.md +1 -1
- package/kits/skills/thread-ops/SKILL.md +34 -21
- package/kits/templates/message-fragments/group-batch-item.md +1 -1
- package/kits/templates/message-fragments/group-batch.md +1 -1
- package/kits/templates/message-fragments/inject-default.md +1 -1
- package/kits/templates/message-fragments/interrupt-insert.md +1 -0
- package/kits/templates/message-fragments/item-group.md +1 -1
- package/kits/templates/message-fragments/item-private.md +1 -1
- package/kits/templates/message-fragments/thread-context.md +1 -1
- package/kits/templates/message-fragments/trigger-session.md +1 -1
- package/kits/templates/message-fragments/trigger-thread-check.md +1 -1
- package/kits/templates/roles/admin.json +2 -19
- package/kits/templates/roles/member.json +0 -3
- package/kits/templates/roles/visitor.json +1 -0
- package/kits/templates/system-fragments/baseagent.md +6 -0
- package/kits/templates/system-fragments/commands.md +4 -3
- package/kits/templates/system-fragments/directory-contacts.md +3 -4
- package/kits/templates/system-fragments/managed-runtime.md +1 -1
- package/kits/templates/system-fragments/relation.md +1 -1
- package/kits/templates/system-fragments/thread.md +7 -5
- package/kits/templates/system-fragments/venue.md +11 -0
- package/package.json +6 -4
- package/scripts/agent-template/inspect.mjs +50 -11
- package/scripts/agent-template/shared/common.mjs +11 -6
- package/scripts/agent-template/shared/team-schema.json +6 -4
- package/scripts/agent-template/shared/template-contract.mjs +62 -11
- package/scripts/agent-template/shared/template-package.mjs +189 -21
- package/scripts/agent-template/shared/template-runtime.mjs +54 -6
- package/scripts/agent-template/shared/template.mjs +2 -2
- package/scripts/agent-template/team-pack.mjs +52 -14
- package/dist/cli/peer.js +0 -127
- package/dist/config/peer-operation-service.js +0 -132
- package/dist/config/peer-request-service.js +0 -532
- package/dist/core/command/connect-menu.js +0 -624
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { ownerResolver, OWNERSHIP_AUTHORIZATION_MAX_AGE_MS } from '../core/ownership/owner-resolver.js';
|
|
2
|
+
import { OUTPUT_EVENT } from './protocol.js';
|
|
3
|
+
import { OUTPUT_CARDS_EVENT } from './protocol.js';
|
|
4
|
+
import { WORKBENCH_EVENT } from '../workbench/protocol.js';
|
|
5
|
+
export const PRIVATE_PROJECTION_EVENTS = [OUTPUT_EVENT, OUTPUT_CARDS_EVENT, WORKBENCH_EVENT];
|
|
6
|
+
/** Fixed event shares the configured Bus. No pack, connection or switch is created. */
|
|
7
|
+
export function registerOutputEvent(state) {
|
|
8
|
+
const conflicts = state.enabledPacks.filter(pack => pack.register.some(item => PRIVATE_PROJECTION_EVENTS.some(event => event === item.event)));
|
|
9
|
+
for (const pack of conflicts)
|
|
10
|
+
state.invalidPacks.push({ id: pack.id, errors: ['Owner-private projection events are reserved native events'] });
|
|
11
|
+
const ids = new Set(conflicts.map(pack => pack.id));
|
|
12
|
+
state.enabledPacks = state.enabledPacks.filter(pack => !ids.has(pack.id));
|
|
13
|
+
state.catalog = state.catalog.filter(item => !PRIVATE_PROJECTION_EVENTS.some(event => event === item.event) && !ids.has(item.sourcePackId));
|
|
14
|
+
for (const event of PRIVATE_PROJECTION_EVENTS)
|
|
15
|
+
state.catalog.push({ event, ttl: 30, maxTtl: 60,
|
|
16
|
+
schemaVersion: 1, sourcePackId: event === WORKBENCH_EVENT ? 'builtin.workbench' : 'builtin.outputs' });
|
|
17
|
+
}
|
|
18
|
+
export function outputAllowlist(aid, result) {
|
|
19
|
+
const owner = ownerResolver.snapshot(aid);
|
|
20
|
+
const subscriber = owner.authorizationStatus === 'verified' && !owner.refreshFailure?.fallbackUsed
|
|
21
|
+
&& (owner.validUntil ?? 0) > Date.now() ? owner.ownerAid : undefined;
|
|
22
|
+
const allowlist = { ...result.allowlist };
|
|
23
|
+
// The SDK ORs wildcard ACLs with named ACLs. Expand them over the other
|
|
24
|
+
// registered events so a stale Owner cannot retain this private subscription.
|
|
25
|
+
const wildcard = allowlist['*'];
|
|
26
|
+
if (wildcard) {
|
|
27
|
+
for (const [event, raw] of Object.entries(allowlist)) {
|
|
28
|
+
if (event === '*' || PRIVATE_PROJECTION_EVENTS.some(privateEvent => privateEvent === event))
|
|
29
|
+
continue;
|
|
30
|
+
const entry = raw;
|
|
31
|
+
allowlist[event] = Object.fromEntries(['publish_aids', 'subscribe_aids'].map(key => [key,
|
|
32
|
+
[...new Set([...(Array.isArray(entry?.[key]) ? entry[key] : []),
|
|
33
|
+
...(Array.isArray(wildcard[key]) ? wildcard[key] : [])])],
|
|
34
|
+
]));
|
|
35
|
+
}
|
|
36
|
+
delete allowlist['*'];
|
|
37
|
+
}
|
|
38
|
+
for (const event of PRIVATE_PROJECTION_EVENTS)
|
|
39
|
+
allowlist[event] = { publish_aids: [aid], subscribe_aids: subscriber ? [subscriber] : [] };
|
|
40
|
+
return { ...result, allowlist };
|
|
41
|
+
}
|
|
42
|
+
export async function assertOutputEventRequest(aid, sender, request, service) {
|
|
43
|
+
const lease = request.op === 'renew' && typeof request.lease_id === 'string'
|
|
44
|
+
? service?.leases?.get(request.lease_id) : undefined;
|
|
45
|
+
const names = [request.event_name, ...(Array.isArray(request.events) ? request.events : []),
|
|
46
|
+
...(Array.isArray(request.scope) ? request.scope.map(item => item?.event_name) : []),
|
|
47
|
+
...(lease?.scope?.map(item => item.event_name) ?? [])];
|
|
48
|
+
if (!PRIVATE_PROJECTION_EVENTS.some(event => names.includes(event)))
|
|
49
|
+
return;
|
|
50
|
+
const scope = Array.isArray(request.scope) ? request.scope : lease?.scope;
|
|
51
|
+
const actions = scope?.map(item => item?.action)
|
|
52
|
+
?? request.actions;
|
|
53
|
+
const publisherOnly = Array.isArray(actions) && actions.length > 0 && actions.every(action => action === 'publish');
|
|
54
|
+
if (sender === aid && (request.op === 'publish' ||
|
|
55
|
+
(request.op === 'authorize' || request.op === 'renew') && publisherOnly))
|
|
56
|
+
return;
|
|
57
|
+
const owner = await ownerResolver.refresh(aid, { maxAgeMs: OWNERSHIP_AUTHORIZATION_MAX_AGE_MS,
|
|
58
|
+
source: 'outputs.events', allowTransient: false });
|
|
59
|
+
if (request.op !== 'publish' && owner.authorizationStatus === 'verified'
|
|
60
|
+
&& !owner.refreshFailure?.fallbackUsed && (owner.validUntil ?? 0) > Date.now() && owner.ownerAid === sender)
|
|
61
|
+
return;
|
|
62
|
+
throw Object.assign(new Error('Output events require the current protocol Owner'), { code: 'FORBIDDEN' });
|
|
63
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { parseDocument } from 'yaml';
|
|
4
|
+
export const OUTPUT_EVENT = 'team.outputs.changed';
|
|
5
|
+
export const OUTPUT_CARDS_EVENT = 'team.output-cards.changed';
|
|
6
|
+
export const OUTPUT_TYPES = ['snapshot', 'list', 'detail', 'changes'].map(action => `services.outputs.${action}`);
|
|
7
|
+
export const isOutputType = (type) => OUTPUT_TYPES.includes(type);
|
|
8
|
+
export const outputId = (relative) => crypto.createHash('sha256').update(relative).digest('hex').slice(0, 32);
|
|
9
|
+
export const outputVersion = (value) => crypto.createHash('sha256').update(value).digest('hex').slice(0, 24);
|
|
10
|
+
export function outputRequestSchema(type) {
|
|
11
|
+
const action = type.split('.').at(-1);
|
|
12
|
+
const properties = { protocolVersion: { const: 1 } };
|
|
13
|
+
const required = ['protocolVersion'];
|
|
14
|
+
if (action === 'snapshot')
|
|
15
|
+
Object.assign(properties, { knownRevision: { type: 'string', maxLength: 128 }, waitForIndex: { type: 'boolean' }, limit: { type: 'integer', minimum: 1, maximum: 20 } });
|
|
16
|
+
if (action === 'list')
|
|
17
|
+
Object.assign(properties, { kind: { enum: ['document', 'image', 'media', 'archive', 'file'] }, pageCursor: { type: 'string', maxLength: 512 }, limit: { type: 'integer', minimum: 1, maximum: 20 } });
|
|
18
|
+
if (action === 'detail') {
|
|
19
|
+
properties.id = { type: 'string', pattern: '^[a-f0-9]{32}$' };
|
|
20
|
+
required.push('id');
|
|
21
|
+
}
|
|
22
|
+
if (action === 'changes') {
|
|
23
|
+
properties.cursor = { type: 'string', maxLength: 128 };
|
|
24
|
+
required.push('cursor');
|
|
25
|
+
}
|
|
26
|
+
return { type: 'object', additionalProperties: false, required: ['type', 'request_id', 'data'], properties: {
|
|
27
|
+
type: { const: type }, request_id: { type: 'string', minLength: 1, maxLength: 128 },
|
|
28
|
+
data: { type: 'object', additionalProperties: false, required, properties },
|
|
29
|
+
} };
|
|
30
|
+
}
|
|
31
|
+
/** Schema for the data field of every successful outputs.*.result. */
|
|
32
|
+
export function outputResponseSchema() {
|
|
33
|
+
const hex = (length) => ({ type: 'string', pattern: `^[a-f0-9]{${length}}$` });
|
|
34
|
+
return {
|
|
35
|
+
type: 'object', additionalProperties: false,
|
|
36
|
+
required: ['protocol', 'protocolVersion', 'sourceAid', 'space', 'revision', 'cursor', 'generatedAt',
|
|
37
|
+
'coverage', 'indexState', 'truncated', 'notifications', 'items', 'nextCursor'],
|
|
38
|
+
properties: {
|
|
39
|
+
protocol: { const: 'evol.outputs' }, protocolVersion: { const: 1 },
|
|
40
|
+
sourceAid: { type: 'string', minLength: 3, maxLength: 256 }, space: { const: 'agent-output' },
|
|
41
|
+
revision: hex(24), cursor: { type: 'string', pattern: '^[a-f0-9]{24}\\.\\d+$', maxLength: 128 },
|
|
42
|
+
generatedAt: { type: 'integer', minimum: 0 }, coverage: { enum: ['complete', 'partial'] },
|
|
43
|
+
indexState: { enum: ['ready', 'building'] }, truncated: { type: 'boolean' },
|
|
44
|
+
notifications: { anyOf: [{ type: 'null' }, { type: 'object', additionalProperties: false,
|
|
45
|
+
required: ['busAid', 'event'], properties: {
|
|
46
|
+
busAid: { type: 'string' }, event: { const: OUTPUT_EVENT },
|
|
47
|
+
} }] },
|
|
48
|
+
items: { type: 'array', maxItems: 20, items: { type: 'object', additionalProperties: false,
|
|
49
|
+
required: ['id', 'version', 'title', 'kind', 'modifiedAt', 'size', 'summary', 'openRef'], properties: {
|
|
50
|
+
id: hex(32), version: hex(24), title: { type: 'string', maxLength: 256 },
|
|
51
|
+
kind: { enum: ['document', 'image', 'media', 'archive', 'file'] },
|
|
52
|
+
modifiedAt: { type: 'integer', minimum: 0 }, size: { type: 'integer', minimum: 0 },
|
|
53
|
+
summary: { type: 'string', maxLength: 1024 },
|
|
54
|
+
openRef: { type: 'object', additionalProperties: false, required: ['path'], properties: {
|
|
55
|
+
path: { type: 'string', maxLength: 2048, pattern: '^output/[^\\\\:\\u0000-\\u001f\\u007f]+$' },
|
|
56
|
+
} },
|
|
57
|
+
} } },
|
|
58
|
+
nextCursor: { anyOf: [{ type: 'null' }, { type: 'string', maxLength: 512 }] },
|
|
59
|
+
reset: { type: 'boolean' }, notModified: { type: 'boolean' },
|
|
60
|
+
deletes: { type: 'array', maxItems: 100, uniqueItems: true, items: hex(32) },
|
|
61
|
+
},
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
export function outputKind(relative) {
|
|
65
|
+
const ext = path.posix.extname(relative).toLowerCase();
|
|
66
|
+
if (['.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg', '.heic'].includes(ext))
|
|
67
|
+
return 'image';
|
|
68
|
+
if (['.mp4', '.webm', '.mov', '.mp3', '.wav', '.m4a', '.ogg'].includes(ext))
|
|
69
|
+
return 'media';
|
|
70
|
+
if (['.zip', '.7z', '.tar', '.gz'].includes(ext))
|
|
71
|
+
return 'archive';
|
|
72
|
+
if (['.md', '.markdown', '.txt', '.pdf', '.html', '.docx', '.xlsx', '.csv', '.json'].includes(ext))
|
|
73
|
+
return 'document';
|
|
74
|
+
return 'file';
|
|
75
|
+
}
|
|
76
|
+
export function outputItem(item, signature) {
|
|
77
|
+
let title = item.name;
|
|
78
|
+
let summary = '';
|
|
79
|
+
const source = item.previewSource ?? '';
|
|
80
|
+
const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/.exec(source);
|
|
81
|
+
if (match) {
|
|
82
|
+
try {
|
|
83
|
+
const doc = parseDocument(match[1], { uniqueKeys: true });
|
|
84
|
+
const fields = doc.toJS({ maxAliasCount: 0 });
|
|
85
|
+
if (!doc.errors.length && fields && typeof fields === 'object') {
|
|
86
|
+
if (typeof fields.title === 'string')
|
|
87
|
+
title = fields.title.slice(0, 200);
|
|
88
|
+
if (typeof fields.summary === 'string')
|
|
89
|
+
summary = fields.summary.slice(0, 768);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
catch { /* legacy documents still have a bounded body */ }
|
|
93
|
+
if (title === item.name)
|
|
94
|
+
title = /^#\s+(.+)$/m.exec(match[2])?.[1]?.slice(0, 200) ?? title;
|
|
95
|
+
if (!summary)
|
|
96
|
+
summary = match[2].replace(/^#+\s+.*/m, '').replace(/[`*_>#]/g, '').trim().slice(0, 768);
|
|
97
|
+
}
|
|
98
|
+
return {
|
|
99
|
+
id: outputId(item.path), version: outputVersion(signature),
|
|
100
|
+
title, kind: outputKind(item.path), modifiedAt: item.mtime, size: item.size, summary,
|
|
101
|
+
openRef: { path: item.path },
|
|
102
|
+
};
|
|
103
|
+
}
|