@tano.page/protocol 0.0.0-stage → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,61 @@
1
+ import { parsePluginJson, pluginKey, pluginRecord, pluginText, type PluginJson } from './extensions';
2
+
3
+ export interface PluginAutomationJobInput {
4
+ pluginId: string;
5
+ automationId: string;
6
+ integrity: string;
7
+ label: string;
8
+ enabled: boolean;
9
+ /** null means manual/Webhook only. The server skips missed intervals after downtime. */
10
+ intervalMinutes: number | null;
11
+ payload: PluginJson;
12
+ version?: string;
13
+ /** Optional compare-and-authorize precondition over canonical portable plugin rule JSON. */
14
+ expectedRuleHash?: string;
15
+ }
16
+ export interface PluginAutomationJob extends Omit<PluginAutomationJobInput, 'version' | 'expectedRuleHash'> {
17
+ id: string;
18
+ version: string;
19
+ authorizedBy: string;
20
+ needsAuthorization: boolean;
21
+ nextAt: string | null;
22
+ webhookConfigured: boolean;
23
+ }
24
+ export type PluginAutomationRunStatus = 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelled' | 'uncertain' | 'expired';
25
+ export interface PluginAutomationRun {
26
+ id: string;
27
+ jobId: string;
28
+ trigger: 'manual' | 'schedule' | 'webhook';
29
+ status: PluginAutomationRunStatus;
30
+ createdAt: string;
31
+ scheduledAt: string;
32
+ startedAt: string | null;
33
+ finishedAt: string | null;
34
+ errorCode: string | null;
35
+ result: PluginJson;
36
+ }
37
+ /** Host administration only; a running plugin cannot authorize or schedule itself. */
38
+ export interface PluginAutomationProvider {
39
+ webhook?: {
40
+ url(workspaceId: string, jobId: string): string;
41
+ rotate(workspaceId: string, jobId: string, version: string, signal: AbortSignal): Promise<{ job: PluginAutomationJob; token: string }>;
42
+ revoke(workspaceId: string, jobId: string, version: string, signal: AbortSignal): Promise<PluginAutomationJob>;
43
+ };
44
+ list(workspaceId: string, signal: AbortSignal): Promise<PluginAutomationJob[]>;
45
+ save(workspaceId: string, jobId: string, input: PluginAutomationJobInput, signal: AbortSignal): Promise<PluginAutomationJob>;
46
+ remove(workspaceId: string, jobId: string, version: string, signal: AbortSignal): Promise<void>;
47
+ run(workspaceId: string, jobId: string, version: string, key: string, signal: AbortSignal): Promise<{ id: string }>;
48
+ runs(workspaceId: string, jobId: string, signal: AbortSignal): Promise<PluginAutomationRun[]>;
49
+ cancel(workspaceId: string, jobId: string, runId: string, signal: AbortSignal): Promise<void>;
50
+ }
51
+ export function parsePluginAutomationJob(value: unknown): PluginAutomationJobInput {
52
+ if (!pluginRecord(value) || Object.keys(value).some(key => !['pluginId', 'automationId', 'integrity', 'label', 'enabled', 'intervalMinutes', 'payload', 'version', 'expectedRuleHash'].includes(key)) ||
53
+ typeof value.pluginId !== 'string' || !/^[a-z][a-z0-9-]{0,39}$/.test(value.pluginId) || !pluginKey(value.automationId) ||
54
+ typeof value.integrity !== 'string' || !/^[a-f0-9]{64}$/.test(value.integrity) || !pluginText(value.label, 80) || typeof value.enabled !== 'boolean' ||
55
+ value.intervalMinutes !== null && (!Number.isInteger(value.intervalMinutes) || Number(value.intervalMinutes) < 15 || Number(value.intervalMinutes) > 43200) ||
56
+ value.version !== undefined && (typeof value.version !== 'string' || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value.version)) ||
57
+ value.expectedRuleHash !== undefined && (typeof value.expectedRuleHash !== 'string' || !/^[a-f0-9]{64}$/.test(value.expectedRuleHash))) throw new Error('自动化任务设置无效');
58
+ return { pluginId: value.pluginId, automationId: value.automationId, integrity: value.integrity, label: value.label, enabled: value.enabled,
59
+ intervalMinutes: value.intervalMinutes as number | null, payload: parsePluginJson(value.payload ?? null, 16 * 1024),
60
+ ...(value.version ? { version: value.version as string } : {}), ...(value.expectedRuleHash ? { expectedRuleHash: value.expectedRuleHash as string } : {}) };
61
+ }
@@ -0,0 +1,96 @@
1
+ import { canonicalPluginJson, parsePluginManifest, pluginPackageLimit, pluginRecord, pluginText, type PluginManifest } from './extensions';
2
+
3
+ export const pluginCatalogLimit = 4 * 1024 * 1024;
4
+ export interface PluginPublisher { id: string; name: string; homepage: string; pluginIds: string[] }
5
+ export interface PluginCatalogRelease {
6
+ publisher: string;
7
+ manifest: PluginManifest;
8
+ integrity: string;
9
+ bytes: number;
10
+ publishedAt: string;
11
+ source: string;
12
+ license: string;
13
+ notes: string;
14
+ status: 'published' | 'withdrawn';
15
+ reason?: string;
16
+ }
17
+ /** A curated, data-only index. The configured catalog operator owns publisher assignments. */
18
+ export interface PluginReleaseCatalog {
19
+ catalogVersion: 1;
20
+ name: string;
21
+ updatedAt: string;
22
+ publishers: PluginPublisher[];
23
+ releases: PluginCatalogRelease[];
24
+ }
25
+ export function pluginCatalogHttps(value: unknown): string {
26
+ if (!pluginText(value, 2048)) throw new Error('插件目录地址无效');
27
+ const url = new URL(value);
28
+ if (url.protocol !== 'https:' || url.username || url.password || url.hash) throw new Error('插件目录地址必须为无凭据的 HTTPS 地址');
29
+ return url.href;
30
+ }
31
+ const identifier = (value: unknown): value is string => typeof value === 'string' && /^[a-z][a-z0-9-]{0,39}$/.test(value);
32
+ const date = (value: unknown): value is string => typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value) && Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
33
+ function keys(value: unknown, allowed: string[]): asserts value is Record<string, unknown> {
34
+ if (!pluginRecord(value) || Object.keys(value).some(key => !allowed.includes(key))) throw new Error('插件目录包含不支持的字段');
35
+ }
36
+ export function parsePluginCatalog(content: string): PluginReleaseCatalog {
37
+ if (new TextEncoder().encode(content).length > pluginCatalogLimit) throw new Error('插件目录不能超过 4 MiB');
38
+ const value = JSON.parse(content);
39
+ keys(value, ['catalogVersion', 'name', 'updatedAt', 'publishers', 'releases']);
40
+ if (value.catalogVersion !== 1 || !pluginText(value.name, 100) || !date(value.updatedAt) ||
41
+ !Array.isArray(value.publishers) || value.publishers.length > 1000 || !Array.isArray(value.releases) || value.releases.length > 1000)
42
+ throw new Error('插件目录格式或容量无效');
43
+ const owners = new Map<string, string>();
44
+ const publisherIds = new Set<string>();
45
+ const publishers = value.publishers.map((item): PluginPublisher => {
46
+ keys(item, ['id', 'name', 'homepage', 'pluginIds']);
47
+ if (!identifier(item.id) || publisherIds.has(item.id) || !pluginText(item.name, 100) || !Array.isArray(item.pluginIds) || item.pluginIds.length > 1000) throw new Error('插件发布者无效或重复');
48
+ publisherIds.add(item.id);
49
+ const pluginIds = item.pluginIds.map(id => {
50
+ if (!identifier(id) || owners.has(id)) throw new Error('插件 ID 必须分配给唯一发布者');
51
+ owners.set(id, item.id as string); return id;
52
+ });
53
+ return { id: item.id, name: item.name, homepage: pluginCatalogHttps(item.homepage), pluginIds };
54
+ });
55
+ const versions = new Set<string>();
56
+ const releases = value.releases.map((item): PluginCatalogRelease => {
57
+ keys(item, ['publisher', 'manifest', 'integrity', 'bytes', 'publishedAt', 'source', 'license', 'notes', 'status', 'reason']);
58
+ const manifest = parsePluginManifest(item.manifest);
59
+ const key = `${manifest.id}@${manifest.version}`;
60
+ if (typeof item.publisher !== 'string' || !publisherIds.has(item.publisher) || owners.get(manifest.id) !== item.publisher || versions.has(key)) throw new Error('插件发布者不匹配或版本重复');
61
+ if (!/^(0|[1-9]\d{0,19})\.(0|[1-9]\d{0,19})\.(0|[1-9]\d{0,19})$/.test(manifest.version)) throw new Error('目录版本必须为无前导零的数字三段版本号');
62
+ versions.add(key);
63
+ if (typeof item.integrity !== 'string' || !/^[a-f0-9]{64}$/.test(item.integrity) ||
64
+ !Number.isSafeInteger(item.bytes) || Number(item.bytes) < 1 || Number(item.bytes) > pluginPackageLimit || !date(item.publishedAt) ||
65
+ !pluginText(item.license, 100) || typeof item.notes !== 'string' || item.notes.length > 4000 || /[\u0000-\u0008\u000b\u000c\u000e-\u001f]/.test(item.notes) ||
66
+ !['published', 'withdrawn'].includes(String(item.status)) || (item.status === 'withdrawn' ? !pluginText(item.reason, 500) : item.reason !== undefined))
67
+ throw new Error('插件发布版本无效');
68
+ return { publisher: item.publisher as string, manifest, integrity: item.integrity, bytes: Number(item.bytes), publishedAt: item.publishedAt,
69
+ source: pluginCatalogHttps(item.source), license: item.license, notes: item.notes, status: item.status as PluginCatalogRelease['status'],
70
+ ...(item.status === 'withdrawn' ? { reason: item.reason as string } : {}) };
71
+ });
72
+ return { catalogVersion: 1, name: value.name, updatedAt: value.updatedAt, publishers, releases };
73
+ }
74
+ /** Published identities and bytes are immutable. Withdrawal is permanent and retains the audit trail. */
75
+ export function assertPluginCatalogTransition(previous: PluginReleaseCatalog, next: PluginReleaseCatalog) {
76
+ if (next.updatedAt < previous.updatedAt) throw new Error('目录更新时间不能倒退');
77
+ for (const publisher of previous.publishers) {
78
+ const current = next.publishers.find(item => item.id === publisher.id);
79
+ if (!current || publisher.pluginIds.some(id => !current.pluginIds.includes(id))) throw new Error('不能移除发布者或转移已分配的插件 ID');
80
+ }
81
+ for (const release of previous.releases) {
82
+ const current = next.releases.find(item => item.manifest.id === release.manifest.id && item.manifest.version === release.manifest.version);
83
+ if (!current) throw new Error('已发布版本只能撤回,不能从目录删除');
84
+ const immutable = ({ status: _status, reason: _reason, ...value }: PluginCatalogRelease) => canonicalPluginJson(value);
85
+ if (immutable(release) !== immutable(current)) throw new Error('已发布版本不可覆盖,请增加版本号');
86
+ if (release.status === 'withdrawn' && current.status !== 'withdrawn') throw new Error('已撤回版本不可重新上架,请发布新版本');
87
+ }
88
+ }
89
+ /** Numeric triplets without Number precision loss, including older manifests with leading zeros. */
90
+ export function comparePluginVersions(left: string, right: string): number {
91
+ for (let i = 0; i < 3; i++) {
92
+ const a = BigInt(left.split('.')[i]!), b = BigInt(right.split('.')[i]!);
93
+ if (a !== b) return a > b ? 1 : -1;
94
+ }
95
+ return 0;
96
+ }
@@ -0,0 +1,84 @@
1
+ import { parsePluginJson, pluginRecord, pluginText, type PluginJson } from './extensions';
2
+
3
+ export const pluginConnectionMethods = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] as const;
4
+ export type PluginConnectionMethod = typeof pluginConnectionMethods[number];
5
+ export type PluginConnectionAuthentication = 'bearer' | 'x-api-key' | 'api-key' | 'private-token';
6
+ export interface PluginConnectionInput {
7
+ pluginId: string;
8
+ origin: string;
9
+ integrity: string;
10
+ methods: PluginConnectionMethod[];
11
+ pathPrefix: string;
12
+ authentication: PluginConnectionAuthentication;
13
+ /** Omit only when renewing/updating an existing connection without changing its authentication kind. */
14
+ secret?: string;
15
+ /** Optimistic concurrency token. Omit when creating a connection. */
16
+ version?: string;
17
+ }
18
+ export interface PluginConnection extends Omit<PluginConnectionInput, 'secret' | 'version'> {
19
+ version: string;
20
+ updatedAt: string;
21
+ hasSecret: true;
22
+ /** Host metadata only. Tokens are never exposed to the plugin SDK. */
23
+ oauth?: { providerId: string };
24
+ }
25
+ export interface PluginOAuthProvider { id: string; label: string; origin: string; scopes: string[] }
26
+ export interface PluginOAuthInput extends Omit<PluginConnectionInput, 'secret' | 'authentication'> { providerId: string }
27
+ export interface PluginOAuthFlow { id: string; authorizationUrl: string; expiresAt: string }
28
+ export interface PluginOAuthStatus { status: 'pending' | 'exchanging' | 'completed' | 'cancelled' | 'failed' | 'expired' }
29
+ /** Account connection UI only; deliberately absent from the plugin SDK. */
30
+ export interface PluginOAuthHost {
31
+ /** Shown while opening an external login page. Defaults to the online account requirement. */
32
+ readonly loginHint?: string;
33
+ providers(workspaceId: string, signal: AbortSignal): Promise<PluginOAuthProvider[]>;
34
+ start(workspaceId: string, input: PluginOAuthInput, signal: AbortSignal): Promise<PluginOAuthFlow>;
35
+ status(workspaceId: string, flowId: string, signal: AbortSignal): Promise<PluginOAuthStatus>;
36
+ cancel(workspaceId: string, flowId: string, signal: AbortSignal): Promise<void>;
37
+ }
38
+ export interface PluginConnectionRequest { path: string; method?: PluginConnectionMethod; body?: PluginJson }
39
+ export interface PluginConnectionResponse { status: number; body: string; contentType: 'application/json' | 'text/plain' }
40
+ export interface PluginConnectionContext { workspaceId: string; pluginId: string; integrity: string; signal: AbortSignal }
41
+ /** API keys enter save(); OAuth tokens stay in the host. Metadata and SDK results contain no credential handle. */
42
+ export interface PluginConnectionProvider {
43
+ readonly storageLabel: string;
44
+ readonly oauth?: PluginOAuthHost;
45
+ list(workspaceId: string, signal: AbortSignal): Promise<PluginConnection[]>;
46
+ save(workspaceId: string, input: PluginConnectionInput, signal: AbortSignal): Promise<PluginConnection>;
47
+ remove(workspaceId: string, pluginId: string, origin: string, version: string, signal: AbortSignal): Promise<void>;
48
+ request(context: PluginConnectionContext, origin: string, request: PluginConnectionRequest): Promise<PluginConnectionResponse>;
49
+ }
50
+ export function pluginConnectionOrigin(value: unknown): string {
51
+ if (!pluginText(value, 250)) throw new Error('连接来源无效');
52
+ const url = new URL(value);
53
+ if (url.protocol !== 'https:' || url.username || url.password || url.origin !== value) throw new Error('连接来源必须为不含路径或凭据的 HTTPS 来源');
54
+ return value;
55
+ }
56
+ function connectionPath(value: unknown): string {
57
+ if (!pluginText(value, 2048) || !value.startsWith('/') || value.startsWith('//') || /[\\#\s]/.test(value)) throw new Error('连接请求必须使用相对来源的绝对路径');
58
+ const url = new URL(value, 'https://connection.invalid');
59
+ if (/%(?:0[0-9a-f]|1[0-9a-f]|7f|25|2e|2f|5c)/i.test(url.pathname)) throw new Error('连接路径不能包含编码的控制字符、路径分隔符或跳转');
60
+ return url.pathname + url.search;
61
+ }
62
+ export function parsePluginConnectionRequest(value: unknown): Required<Pick<PluginConnectionRequest, 'path' | 'method'>> & Pick<PluginConnectionRequest, 'body'> {
63
+ if (!pluginRecord(value) || Object.keys(value).some(key => !['path', 'method', 'body'].includes(key))) throw new Error('连接请求格式无效');
64
+ const method = value.method ?? 'GET';
65
+ if (!pluginConnectionMethods.includes(method as PluginConnectionMethod)) throw new Error('连接请求方法无效');
66
+ if (method === 'GET' && value.body !== undefined) throw new Error('GET 请求不能携带正文');
67
+ return { path: connectionPath(value.path), method: method as PluginConnectionMethod,
68
+ ...(value.body !== undefined ? { body: parsePluginJson(value.body, 64 * 1024) } : {}) };
69
+ }
70
+ export function parsePluginConnectionInput(value: unknown): PluginConnectionInput {
71
+ if (!pluginRecord(value) || Object.keys(value).some(key => !['pluginId', 'origin', 'integrity', 'methods', 'pathPrefix', 'authentication', 'secret', 'version'].includes(key))) throw new Error('连接设置格式无效');
72
+ if (typeof value.pluginId !== 'string' || !/^[a-z][a-z0-9-]{0,39}$/.test(value.pluginId) || typeof value.integrity !== 'string' || !/^[a-f0-9]{64}$/.test(value.integrity) ||
73
+ !Array.isArray(value.methods) || !value.methods.length || value.methods.length > 5 || value.methods.some(method => !pluginConnectionMethods.includes(method)) || new Set(value.methods).size !== value.methods.length ||
74
+ !['bearer', 'x-api-key', 'api-key', 'private-token'].includes(String(value.authentication)) ||
75
+ value.version !== undefined && (typeof value.version !== 'string' || !/^[a-f0-9-]{36}$/.test(value.version))) throw new Error('连接设置无效');
76
+ const pathPrefix = connectionPath(value.pathPrefix);
77
+ if (pathPrefix !== value.pathPrefix || pathPrefix.includes('?') || !pathPrefix.endsWith('/')) throw new Error('连接路径范围必须以 / 结尾且不能包含查询或路径跳转');
78
+ if (value.secret !== undefined && (typeof value.secret !== 'string' || !/^[\x21-\x7e]{8,4096}$/.test(value.secret))) throw new Error('密钥必须为 8 至 4096 个可打印 ASCII 字符,不含空格');
79
+ return { pluginId: value.pluginId, origin: pluginConnectionOrigin(value.origin), integrity: value.integrity, methods: value.methods as PluginConnectionMethod[], pathPrefix,
80
+ authentication: value.authentication as PluginConnectionAuthentication, ...(value.secret !== undefined ? { secret: value.secret as string } : {}), ...(value.version ? { version: value.version as string } : {}) };
81
+ }
82
+ export function assertPluginConnectionRequest(connection: PluginConnectionInput, request: ReturnType<typeof parsePluginConnectionRequest>) {
83
+ if (!connection.methods.includes(request.method) || !new URL(request.path, connection.origin).pathname.startsWith(connection.pathPrefix)) throw new Error('此连接未授权请求的方法或路径');
84
+ }
package/src/plugins.ts ADDED
@@ -0,0 +1,184 @@
1
+ import { ObjectTypeRegistry, coreObjectTypes, validObjectType } from './object-types';
2
+ import type { ObjectField } from './object-types';
3
+ import type { RelationTypeDefinition } from './relations';
4
+
5
+ export interface ObjectPluginManifest {
6
+ manifestVersion: 1;
7
+ id: string;
8
+ name: string;
9
+ version: string;
10
+ description: string;
11
+ objectTypes: { type: string; label: string; fields: ObjectField[] }[];
12
+ relationTypes: RelationTypeDefinition[];
13
+ }
14
+ /** Data-only manifests: no script, network, renderer, or filesystem execution. */
15
+ export function parseObjectPlugin(content: string): ObjectPluginManifest {
16
+ if (content.length > 256 * 1024) throw new Error('插件清单不能超过 256 KB');
17
+ const value = JSON.parse(content);
18
+ const keys = (object: unknown, allowed: string[]) => {
19
+ if (
20
+ !object ||
21
+ typeof object !== 'object' ||
22
+ Array.isArray(object) ||
23
+ Object.keys(object).some((key) => !allowed.includes(key))
24
+ )
25
+ throw new Error('插件清单包含不支持的字段或可执行扩展');
26
+ };
27
+ const label = (text: unknown, limit = 80): text is string =>
28
+ typeof text === 'string' &&
29
+ !!text.trim() &&
30
+ text.length <= limit &&
31
+ !/[\u0000-\u001f]/.test(text);
32
+ keys(value, [
33
+ 'manifestVersion',
34
+ 'id',
35
+ 'name',
36
+ 'version',
37
+ 'description',
38
+ 'objectTypes',
39
+ 'relationTypes',
40
+ ]);
41
+ if (
42
+ value.manifestVersion !== 1 ||
43
+ typeof value.id !== 'string' ||
44
+ !/^[a-z][a-z0-9-]{0,39}$/.test(value.id) ||
45
+ !label(value.name) ||
46
+ typeof value.version !== 'string' ||
47
+ !/^\d+\.\d+\.\d+$/.test(value.version) ||
48
+ typeof value.description !== 'string' ||
49
+ value.description.length > 2000 ||
50
+ !Array.isArray(value.objectTypes) ||
51
+ value.objectTypes.length > 50 ||
52
+ !Array.isArray(value.relationTypes ?? []) ||
53
+ (value.relationTypes?.length ?? 0) > 100
54
+ )
55
+ throw new Error('插件清单的名称、版本或类型列表无效');
56
+ const registry = new ObjectTypeRegistry();
57
+ for (const definition of value.objectTypes) {
58
+ keys(definition, ['type', 'label', 'fields']);
59
+ if (
60
+ !label(definition.label) ||
61
+ !Array.isArray(definition.fields ?? []) ||
62
+ (definition.fields?.length ?? 0) > 50
63
+ )
64
+ throw new Error('插件对象字段无效');
65
+ for (const field of definition.fields ?? []) {
66
+ keys(field, ['key', 'label', 'type', 'required']);
67
+ if (
68
+ typeof field.key !== 'string' ||
69
+ !label(field.label) ||
70
+ (field.required !== undefined && typeof field.required !== 'boolean')
71
+ )
72
+ throw new Error('插件属性字段无效');
73
+ }
74
+ registry.registerObjectType({ ...definition, plugin: value.id });
75
+ }
76
+ const available = new Set([
77
+ ...coreObjectTypes.map((type) => type.type),
78
+ ...value.objectTypes.map((type: { type: string }) => type.type),
79
+ '*',
80
+ ]);
81
+ const relationIds = new Set<string>();
82
+ const relations: RelationTypeDefinition[] = [];
83
+ for (const definition of value.relationTypes ?? []) {
84
+ keys(definition, ['type', 'label', 'sourceTypes', 'targetTypes', 'level', 'plugin']);
85
+ if (
86
+ !validObjectType(definition.type) ||
87
+ !definition.type.startsWith(`${value.id}.`) ||
88
+ relationIds.has(definition.type) ||
89
+ !label(definition.label) ||
90
+ [definition.sourceTypes, definition.targetTypes].some(
91
+ (types) =>
92
+ !Array.isArray(types) ||
93
+ !types.length ||
94
+ types.some((type: unknown) => !available.has(type)),
95
+ )
96
+ )
97
+ throw new Error('插件关系定义或端点类型无效');
98
+ relationIds.add(definition.type);
99
+ relations.push({ ...definition, level: 2, plugin: value.id });
100
+ }
101
+ return {
102
+ ...value,
103
+ objectTypes: value.objectTypes.map((type: { fields?: ObjectField[] }) => ({
104
+ ...type,
105
+ fields: type.fields ?? [],
106
+ })),
107
+ relationTypes: relations,
108
+ };
109
+ }
110
+
111
+ export const bundledObjectPlugins: readonly ObjectPluginManifest[] = [
112
+ {
113
+ manifestVersion: 1,
114
+ id: 'research',
115
+ name: '研究工作台',
116
+ version: '1.0.0',
117
+ description: '管理论文、数据集和实验,连接论文使用的数据与实验。',
118
+ objectTypes: [
119
+ {
120
+ type: 'research.paper',
121
+ label: '论文',
122
+ fields: [
123
+ { key: 'year', label: '年份', type: 'number' },
124
+ { key: 'doi', label: 'DOI', type: 'text' },
125
+ ],
126
+ },
127
+ {
128
+ type: 'research.dataset',
129
+ label: '数据集',
130
+ fields: [{ key: 'url', label: '来源链接', type: 'text' }],
131
+ },
132
+ {
133
+ type: 'research.experiment',
134
+ label: '实验',
135
+ fields: [{ key: 'status', label: '进度', type: 'text' }],
136
+ },
137
+ ],
138
+ relationTypes: [
139
+ {
140
+ type: 'research.uses',
141
+ label: '使用数据集',
142
+ sourceTypes: ['research.paper', 'research.experiment'],
143
+ targetTypes: ['research.dataset'],
144
+ level: 2,
145
+ plugin: 'research',
146
+ },
147
+ {
148
+ type: 'research.validates',
149
+ label: '验证论文',
150
+ sourceTypes: ['research.experiment'],
151
+ targetTypes: ['research.paper'],
152
+ level: 2,
153
+ plugin: 'research',
154
+ },
155
+ ],
156
+ },
157
+ {
158
+ manifestVersion: 1,
159
+ id: 'reading',
160
+ name: '阅读书架',
161
+ version: '1.0.0',
162
+ description: '记录书籍与阅读笔记,将书籍关联到工作区文档。',
163
+ objectTypes: [
164
+ {
165
+ type: 'reading.book',
166
+ label: '书籍',
167
+ fields: [
168
+ { key: 'author', label: '作者', type: 'text' },
169
+ { key: 'isbn', label: 'ISBN', type: 'text' },
170
+ ],
171
+ },
172
+ ],
173
+ relationTypes: [
174
+ {
175
+ type: 'reading.notes',
176
+ label: '阅读笔记',
177
+ sourceTypes: ['reading.book'],
178
+ targetTypes: ['document'],
179
+ level: 2,
180
+ plugin: 'reading',
181
+ },
182
+ ],
183
+ },
184
+ ];
@@ -0,0 +1,47 @@
1
+ import { validatePath } from './paths';
2
+
3
+ /** Markdown references are relative to the document, never to the process cwd. */
4
+ export function resolveWorkspaceReference(documentPath: string, reference: string): string | null {
5
+ try {
6
+ const raw = decodeURIComponent(reference.split(/[?#]/, 1)[0]!);
7
+ if (
8
+ !raw ||
9
+ raw.startsWith('/') ||
10
+ raw.includes('\\') ||
11
+ raw.includes(':') ||
12
+ /[\u0000-\u001f]/.test(raw)
13
+ )
14
+ return null;
15
+ const parts = documentPath.split('/').slice(0, -1);
16
+ for (const part of raw.split('/')) {
17
+ if (part === '.' || part === '') continue;
18
+ if (part === '..') {
19
+ if (!parts.length) return null;
20
+ parts.pop();
21
+ } else parts.push(part);
22
+ }
23
+ const path = parts.join('/');
24
+ return validatePath(path) ? null : path;
25
+ } catch {
26
+ return null;
27
+ }
28
+ }
29
+
30
+ export function relativeWorkspaceReference(documentPath: string, targetPath: string): string {
31
+ const source = documentPath.split('/').slice(0, -1),
32
+ target = targetPath.split('/');
33
+ while (source.length && target.length && source[0] === target[0]) {
34
+ source.shift();
35
+ target.shift();
36
+ }
37
+ return [...source.map(() => '..'), ...target.map(encodeURIComponent)].join('/');
38
+ }
39
+
40
+ export function safeRemoteImage(reference: string): string | null {
41
+ try {
42
+ const url = new URL(reference);
43
+ return url.protocol === 'https:' && !url.username && !url.password ? url.href : null;
44
+ } catch {
45
+ return null;
46
+ }
47
+ }
@@ -0,0 +1,136 @@
1
+ import { isShortId } from './short-id';
2
+ import { objectTypeRegistry, validObjectType } from './object-types';
3
+ import type { ReferenceIdentity } from './objects';
4
+
5
+ export interface RelationTypeDefinition {
6
+ type: string;
7
+ label: string;
8
+ sourceTypes: readonly string[];
9
+ targetTypes: readonly string[];
10
+ level: 2;
11
+ plugin?: string;
12
+ }
13
+ export const coreRelationTypes: readonly RelationTypeDefinition[] = [
14
+ { type: 'member', label: '成员', sourceTypes: ['person'], targetTypes: ['project'], level: 2 },
15
+ { type: 'contains', label: '包含', sourceTypes: ['project'], targetTypes: ['task', 'experiment', 'document', 'asset'], level: 2 },
16
+ { type: 'related', label: '关联', sourceTypes: ['*'], targetTypes: ['*'], level: 2 },
17
+ { type: 'assigned', label: '负责', sourceTypes: ['person'], targetTypes: ['event', 'task', 'project', 'experiment'], level: 2 },
18
+ { type: 'authored', label: '撰写', sourceTypes: ['person'], targetTypes: ['document'], level: 2 },
19
+ { type: 'attends', label: '参加', sourceTypes: ['person'], targetTypes: ['event'], level: 2 },
20
+ { type: 'attachment', label: '附有资产', sourceTypes: ['*'], targetTypes: ['asset'], level: 2 },
21
+ ];
22
+ export interface WorkspaceRelation {
23
+ id: string;
24
+ type: string;
25
+ source: ReferenceIdentity;
26
+ target: ReferenceIdentity;
27
+ [key: string]: unknown;
28
+ }
29
+ export interface RelationFile {
30
+ version: 1;
31
+ relations: WorkspaceRelation[];
32
+ [key: string]: unknown;
33
+ }
34
+ export { workspaceRelationPath as relationPath } from './workspace-paths';
35
+ export const referenceKey = (value: ReferenceIdentity) => `${value.type}/${value.id}`;
36
+ export const relationKey = (value: Pick<WorkspaceRelation, 'source' | 'type' | 'target'>) =>
37
+ `${referenceKey(value.source)}:${value.type}:${referenceKey(value.target)}`;
38
+ export const acceptsRelationType = (types: readonly string[], type: string) =>
39
+ types.includes('*') || types.includes(type);
40
+
41
+ /** Validate the envelope without requiring plugins or endpoints to be available. */
42
+ export function parseRelations(content: string): RelationFile {
43
+ const file = JSON.parse(content);
44
+ if (
45
+ !file ||
46
+ file.version !== 1 ||
47
+ !Array.isArray(file.relations) ||
48
+ file.relations.length > 50000
49
+ )
50
+ throw new Error('关系文件格式无效');
51
+ const ids = new Set<string>();
52
+ const identity = (value: ReferenceIdentity) =>
53
+ value && validObjectType(value.type) && isShortId(value.id);
54
+ for (const row of file.relations) {
55
+ if (
56
+ !row ||
57
+ !isShortId(row.id) ||
58
+ ids.has(row.id) ||
59
+ !validObjectType(row.type) ||
60
+ !identity(row.source) ||
61
+ !identity(row.target)
62
+ )
63
+ throw new Error('关系 ID、类型或端点无效或重复');
64
+ ids.add(row.id);
65
+ }
66
+ return file;
67
+ }
68
+ export function validateRelation(
69
+ row: WorkspaceRelation,
70
+ definitions: readonly RelationTypeDefinition[],
71
+ ) {
72
+ const definition = definitions.find((item) => item.type === row.type);
73
+ if (!definition) throw new Error('关系类型未启用,请先启用对应插件');
74
+ if ([row.source, row.target].some((endpoint) => objectTypeRegistry.get(endpoint.type)?.retired))
75
+ throw new Error('项目对象已停用,不能新增关系;已有关系仍保留');
76
+ if (
77
+ !acceptsRelationType(definition.sourceTypes, row.source.type) ||
78
+ !acceptsRelationType(definition.targetTypes, row.target.type)
79
+ )
80
+ throw new Error('此关系不支持所选的来源或目标类型');
81
+ if (referenceKey(row.source) === referenceKey(row.target))
82
+ throw new Error('来源和目标不能是同一对象');
83
+ }
84
+
85
+ /** Derived, rebuildable graph. Names and paths never participate in identity. */
86
+ export class RelationIndex {
87
+ private outgoing = new Map<string, WorkspaceRelation[]>();
88
+ private incoming = new Map<string, WorkspaceRelation[]>();
89
+ constructor(rows: readonly WorkspaceRelation[]) {
90
+ for (const row of rows) {
91
+ for (const [index, key] of [
92
+ [this.outgoing, referenceKey(row.source)],
93
+ [this.incoming, referenceKey(row.target)],
94
+ ] as const) {
95
+ const entries = index.get(key) ?? [];
96
+ entries.push(row);
97
+ index.set(key, entries);
98
+ }
99
+ }
100
+ }
101
+ connections(identity: ReferenceIdentity, direction: 'outgoing' | 'incoming' | 'both' = 'both') {
102
+ const key = referenceKey(identity);
103
+ return [
104
+ ...new Set([
105
+ ...(direction !== 'incoming' ? (this.outgoing.get(key) ?? []) : []),
106
+ ...(direction !== 'outgoing' ? (this.incoming.get(key) ?? []) : []),
107
+ ]),
108
+ ];
109
+ }
110
+ traverse(
111
+ start: ReferenceIdentity,
112
+ depth = 1,
113
+ direction: 'outgoing' | 'incoming' | 'both' = 'outgoing',
114
+ ) {
115
+ const visited = new Map([[referenceKey(start), start]]);
116
+ let frontier = [start];
117
+ for (
118
+ let step = 0;
119
+ step < Math.min(Math.max(Math.floor(depth), 0), 100) && frontier.length;
120
+ step++
121
+ ) {
122
+ const next: ReferenceIdentity[] = [];
123
+ for (const node of frontier)
124
+ for (const row of this.connections(node, direction)) {
125
+ const other = referenceKey(row.source) === referenceKey(node) ? row.target : row.source;
126
+ if (!visited.has(referenceKey(other))) {
127
+ visited.set(referenceKey(other), other);
128
+ next.push(other);
129
+ }
130
+ }
131
+ frontier = next;
132
+ }
133
+ visited.delete(referenceKey(start));
134
+ return [...visited.values()];
135
+ }
136
+ }
@@ -0,0 +1,14 @@
1
+ /** Reference IDs are six lowercase hexadecimal digits; workspace/session IDs are separate. */
2
+ export const shortIdPattern = '^[0-9a-f]{6}$';
3
+ export const isShortId = (value: unknown): value is string =>
4
+ typeof value === 'string' && /^[0-9a-f]{6}$/.test(value);
5
+
6
+ /** The caller must atomically claim the result in its persistent workspace namespace. */
7
+ export function newShortId(occupied: ReadonlySet<string> = new Set()): string {
8
+ for (let attempt = 0; attempt < 256; attempt++) {
9
+ const bytes = crypto.getRandomValues(new Uint8Array(3));
10
+ const id = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
11
+ if (!occupied.has(id)) return id;
12
+ }
13
+ throw new Error('无法分配未占用的短 ID,请稍后重试');
14
+ }