@dfy-plugins/resource-core 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 xiaoxiao44443
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,5 @@
1
+ # @dfy-plugins/resource-core
2
+
3
+ 普通 npm 公共库,不是 Harness 插件。提供版本化不透明资源引用、provider 所有权隔离、进程内资源注册表和纯文本降级。
4
+
5
+ `getProcessResourceRegistry()` 通过稳定的 `Symbol.for` ABI 共享注册表,因此独立发布或各自打包依赖的插件仍可在同一个 Harness 进程中交换短期资源,而不把字节放进 JSON。
package/lib/index.d.ts ADDED
@@ -0,0 +1,48 @@
1
+ /** Provider-neutral transient resource references shared by DFY DSH plugins. */
2
+ export declare const RESOURCE_PROTOCOL_VERSION: 1;
3
+ export declare const RESOURCE_REFERENCE_PREFIX = "dfyr1_";
4
+ export declare const PROCESS_RESOURCE_REGISTRY_SYMBOL_KEY = "@dfy-plugins/resource-core/process-registry/v1";
5
+ export interface ResourceReferenceV1 {
6
+ version: typeof RESOURCE_PROTOCOL_VERSION;
7
+ provider: string;
8
+ kind: string;
9
+ id: string;
10
+ }
11
+ export interface ResolvedResource {
12
+ kind: string;
13
+ data?: Uint8Array;
14
+ mediaType?: string;
15
+ bytes?: number;
16
+ name?: string;
17
+ metadata?: Readonly<Record<string, unknown>>;
18
+ }
19
+ export interface ResourceProvider {
20
+ readonly id: string;
21
+ resolve(reference: ResourceReferenceV1, signal?: AbortSignal): Promise<ResolvedResource | undefined>;
22
+ }
23
+ export interface ResourceTextFallback {
24
+ kind: string;
25
+ name?: string;
26
+ path?: string;
27
+ url?: string;
28
+ mediaType?: string;
29
+ bytes?: number;
30
+ }
31
+ export declare function encodeResourceReference(reference: ResourceReferenceV1): string;
32
+ export declare function decodeResourceReference(token: string): ResourceReferenceV1;
33
+ /** In-process broker. Providers retain ownership and authorization of their resources. */
34
+ export declare class ResourceRegistry {
35
+ #private;
36
+ readonly version: 1;
37
+ registerProvider(provider: ResourceProvider): () => void;
38
+ hasProvider(id: string): boolean;
39
+ listProviders(): string[];
40
+ resolve(token: string, expectedKind?: string, signal?: AbortSignal): Promise<ResolvedResource>;
41
+ }
42
+ /**
43
+ * Process-local singleton shared even when independently bundled plugins load
44
+ * different physical copies of this package. No resource data crosses JSON.
45
+ */
46
+ export declare function getProcessResourceRegistry(): ResourceRegistry;
47
+ /** Safe readable fallback for a consumer that cannot project the resource itself. */
48
+ export declare function renderResourceTextFallback(resource: ResourceTextFallback): string;
package/lib/index.js ADDED
@@ -0,0 +1,153 @@
1
+ /** Provider-neutral transient resource references shared by DFY DSH plugins. */
2
+ export const RESOURCE_PROTOCOL_VERSION = 1;
3
+ export const RESOURCE_REFERENCE_PREFIX = 'dfyr1_';
4
+ export const PROCESS_RESOURCE_REGISTRY_SYMBOL_KEY = '@dfy-plugins/resource-core/process-registry/v1';
5
+ const MAX_REFERENCE_LENGTH = 2048;
6
+ const PROVIDER_PATTERN = /^[a-z0-9](?:[a-z0-9._-]{0,62}[a-z0-9])?$/;
7
+ const KIND_PATTERN = /^[a-z0-9](?:[a-z0-9._-]{0,62}[a-z0-9])?$/;
8
+ const RESOURCE_ID_PATTERN = /^[A-Za-z0-9_-]{8,256}$/;
9
+ function validReferencePart(value, pattern) {
10
+ return typeof value === 'string' && pattern.test(value);
11
+ }
12
+ export function encodeResourceReference(reference) {
13
+ if (reference.version !== RESOURCE_PROTOCOL_VERSION
14
+ || !validReferencePart(reference.provider, PROVIDER_PATTERN)
15
+ || !validReferencePart(reference.kind, KIND_PATTERN)
16
+ || !validReferencePart(reference.id, RESOURCE_ID_PATTERN)) {
17
+ throw new Error('resource reference is invalid');
18
+ }
19
+ const encoded = Buffer.from(JSON.stringify({
20
+ v: reference.version,
21
+ p: reference.provider,
22
+ k: reference.kind,
23
+ i: reference.id,
24
+ }), 'utf8').toString('base64url');
25
+ return `${RESOURCE_REFERENCE_PREFIX}${encoded}`;
26
+ }
27
+ export function decodeResourceReference(token) {
28
+ const value = token.trim();
29
+ if (value.length <= RESOURCE_REFERENCE_PREFIX.length
30
+ || value.length > MAX_REFERENCE_LENGTH
31
+ || !value.startsWith(RESOURCE_REFERENCE_PREFIX)) {
32
+ throw new Error('resource reference is invalid');
33
+ }
34
+ const encoded = value.slice(RESOURCE_REFERENCE_PREFIX.length);
35
+ if (!/^[A-Za-z0-9_-]+$/.test(encoded))
36
+ throw new Error('resource reference is invalid');
37
+ let parsed;
38
+ try {
39
+ parsed = JSON.parse(Buffer.from(encoded, 'base64url').toString('utf8'));
40
+ }
41
+ catch {
42
+ throw new Error('resource reference is invalid');
43
+ }
44
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
45
+ throw new Error('resource reference is invalid');
46
+ }
47
+ const record = parsed;
48
+ if (record.v !== RESOURCE_PROTOCOL_VERSION
49
+ || !validReferencePart(record.p, PROVIDER_PATTERN)
50
+ || !validReferencePart(record.k, KIND_PATTERN)
51
+ || !validReferencePart(record.i, RESOURCE_ID_PATTERN)
52
+ || Object.keys(record).some((key) => !['v', 'p', 'k', 'i'].includes(key))) {
53
+ throw new Error('resource reference is invalid');
54
+ }
55
+ return {
56
+ version: RESOURCE_PROTOCOL_VERSION,
57
+ provider: record.p,
58
+ kind: record.k,
59
+ id: record.i,
60
+ };
61
+ }
62
+ function providerId(provider) {
63
+ if (!PROVIDER_PATTERN.test(provider.id))
64
+ throw new Error('resource provider id is invalid');
65
+ return provider.id;
66
+ }
67
+ /** In-process broker. Providers retain ownership and authorization of their resources. */
68
+ export class ResourceRegistry {
69
+ version = RESOURCE_PROTOCOL_VERSION;
70
+ #providers = new Map();
71
+ registerProvider(provider) {
72
+ const id = providerId(provider);
73
+ if (this.#providers.has(id))
74
+ throw new Error(`resource provider already registered: ${id}`);
75
+ this.#providers.set(id, provider);
76
+ return () => {
77
+ if (this.#providers.get(id) === provider)
78
+ this.#providers.delete(id);
79
+ };
80
+ }
81
+ hasProvider(id) {
82
+ return this.#providers.has(id);
83
+ }
84
+ listProviders() {
85
+ return [...this.#providers.keys()].sort();
86
+ }
87
+ async resolve(token, expectedKind, signal) {
88
+ signal?.throwIfAborted();
89
+ const reference = decodeResourceReference(token);
90
+ if (expectedKind !== undefined && reference.kind !== expectedKind) {
91
+ throw new Error(`resource kind mismatch: expected ${expectedKind}, received ${reference.kind}`);
92
+ }
93
+ const provider = this.#providers.get(reference.provider);
94
+ if (provider === undefined)
95
+ throw new Error(`resource provider is unavailable: ${reference.provider}`);
96
+ const resource = await provider.resolve(reference, signal);
97
+ signal?.throwIfAborted();
98
+ if (resource === undefined)
99
+ throw new Error('resource is unavailable or expired');
100
+ if (resource.kind !== reference.kind)
101
+ throw new Error('resource provider returned a mismatched kind');
102
+ if (resource.data !== undefined && resource.bytes !== undefined && resource.data.byteLength !== resource.bytes) {
103
+ throw new Error('resource provider returned inconsistent byte metadata');
104
+ }
105
+ return resource;
106
+ }
107
+ }
108
+ function isCompatibleRegistry(value) {
109
+ if (typeof value !== 'object' || value === null)
110
+ return false;
111
+ const registry = value;
112
+ return registry.version === RESOURCE_PROTOCOL_VERSION
113
+ && typeof registry.registerProvider === 'function'
114
+ && typeof registry.hasProvider === 'function'
115
+ && typeof registry.listProviders === 'function'
116
+ && typeof registry.resolve === 'function';
117
+ }
118
+ /**
119
+ * Process-local singleton shared even when independently bundled plugins load
120
+ * different physical copies of this package. No resource data crosses JSON.
121
+ */
122
+ export function getProcessResourceRegistry() {
123
+ const key = Symbol.for(PROCESS_RESOURCE_REGISTRY_SYMBOL_KEY);
124
+ const globals = globalThis;
125
+ const existing = globals[key];
126
+ if (existing !== undefined) {
127
+ if (!isCompatibleRegistry(existing))
128
+ throw new Error('process resource registry version conflict');
129
+ return existing;
130
+ }
131
+ const registry = new ResourceRegistry();
132
+ globals[key] = registry;
133
+ return registry;
134
+ }
135
+ function displayValue(value, limit) {
136
+ return value.replace(/[\u0000-\u001f\u007f]+/g, ' ').replace(/\s+/g, ' ').trim().slice(0, limit);
137
+ }
138
+ /** Safe readable fallback for a consumer that cannot project the resource itself. */
139
+ export function renderResourceTextFallback(resource) {
140
+ const kind = displayValue(resource.kind, 64) || 'resource';
141
+ const lines = [`Resource available (${kind}).`];
142
+ if (resource.name !== undefined)
143
+ lines.push(`Name: ${displayValue(resource.name, 255)}`);
144
+ if (resource.mediaType !== undefined)
145
+ lines.push(`Media type: ${displayValue(resource.mediaType, 127)}`);
146
+ if (resource.bytes !== undefined)
147
+ lines.push(`Bytes: ${String(resource.bytes)}`);
148
+ if (resource.path !== undefined)
149
+ lines.push(`Local path: ${displayValue(resource.path, 2048)}`);
150
+ if (resource.url !== undefined)
151
+ lines.push(`Source URL: ${displayValue(resource.url, 2048)}`);
152
+ return lines.join('\n');
153
+ }
@@ -0,0 +1,3 @@
1
+ export declare function sessionArtifactDirectory(persistence: unknown, header: unknown): string | undefined;
2
+ /** Resolve through the backend, including after a restart when no Agent is loaded. */
3
+ export declare function persistedSessionArtifactDirectory(persistence: unknown, sessionId: string, signal: AbortSignal): Promise<string | undefined>;
@@ -0,0 +1,26 @@
1
+ /** Compatibility boundary for DSH's legacy headers and handle-based persistence. */
2
+ import { dirname, isAbsolute } from 'node:path';
3
+ export function sessionArtifactDirectory(persistence, header) {
4
+ const backend = persistence;
5
+ const location = backend.locate?.(header);
6
+ return location !== undefined && isAbsolute(location.path) ? dirname(location.path) : undefined;
7
+ }
8
+ /** Resolve through the backend, including after a restart when no Agent is loaded. */
9
+ export async function persistedSessionArtifactDirectory(persistence, sessionId, signal) {
10
+ signal.throwIfAborted();
11
+ const backend = persistence;
12
+ let header;
13
+ if (typeof backend.stat === 'function') {
14
+ header = (await backend.stat(sessionId, { signal }))?.header;
15
+ }
16
+ else {
17
+ const entries = await backend.list(signal);
18
+ header = entries.map((entry) => {
19
+ if (entry !== null && typeof entry === 'object' && 'header' in entry)
20
+ return entry.header;
21
+ return entry;
22
+ }).find((entry) => entry !== null && typeof entry === 'object' && 'id' in entry && entry.id === sessionId);
23
+ }
24
+ signal.throwIfAborted();
25
+ return header === undefined ? undefined : sessionArtifactDirectory(backend, header);
26
+ }
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "@dfy-plugins/resource-core",
3
+ "version": "0.1.1",
4
+ "description": "Versioned resource references and provider registry shared by DFY DSH plugins.",
5
+ "type": "module",
6
+ "main": "lib/index.js",
7
+ "types": "lib/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./lib/index.d.ts",
11
+ "default": "./lib/index.js"
12
+ },
13
+ "./session-storage": {
14
+ "types": "./lib/session-storage.d.ts",
15
+ "default": "./lib/session-storage.js"
16
+ },
17
+ "./package.json": "./package.json"
18
+ },
19
+ "files": [
20
+ "lib"
21
+ ],
22
+ "publishConfig": {
23
+ "access": "public",
24
+ "registry": "https://registry.npmjs.org/"
25
+ },
26
+ "license": "MIT",
27
+ "devDependencies": {
28
+ "@types/node": "^24.0.0",
29
+ "typescript": "^5.5.0"
30
+ },
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "git+https://github.com/xiaoxiao44443/dfy-dsh-plugins.git",
34
+ "directory": "packages/resource-core"
35
+ },
36
+ "homepage": "https://github.com/xiaoxiao44443/dfy-dsh-plugins#readme",
37
+ "bugs": {
38
+ "url": "https://github.com/xiaoxiao44443/dfy-dsh-plugins/issues"
39
+ },
40
+ "keywords": [
41
+ "deepseek-harness"
42
+ ],
43
+ "scripts": {
44
+ "build": "tsc -p tsconfig.json",
45
+ "typecheck": "tsc -p tsconfig.json --noEmit",
46
+ "test": "tsc -p tsconfig.json && node --test"
47
+ }
48
+ }