@morlay/dsh-upload 0.0.0-stage → 0.2.0-alpha.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 morlay
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 CHANGED
@@ -1,3 +1,15 @@
1
- # Temporary Holding Version
1
+ # @morlay/dsh-upload
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 浏览器文件上传的宿主面:上游 `FileUploads`(`fileUploads` 服务)的适配行。
4
+
5
+ ## 用法
6
+
7
+ - 导出:`FileUploadStore` 契约(`registerAgentResolver` / `resolve` / `bindPrompt` / `retirePrompt`)与行 `FileUploadStoreDefault`。
8
+ - 装配函数:`provideUpload()`(`./server`)。行的 `deps`:`AgentDirectory` / `AttachmentStore` / `CommandRegistry` / `Connection`。
9
+ - 本包不拥有装配清单,也不登记谁消费这一行(上层装配面负责)。
10
+
11
+ ## 设计
12
+
13
+ 上游 `FileUploads` 已经是完整服务(HTTP 上传路由、命令回执解析器、会话事件观察都在它自己的构造里),本包只做行,不重新实现。契约面的语义照上游:解析器是**单槽**,重复登记直接抛错。
14
+
15
+ 包内子域怎么分、契约与行各放哪,见[包内子域拆分与注册抽象](../.agents/designs/20261028-包内子域拆分与注册抽象.md)。
@@ -0,0 +1,7 @@
1
+ import "./file-upload-store.contract-iiZPCuot.mjs";
2
+ import { Injectable } from "@morlay/zephyr";
3
+ import { t as __decorate } from "./decorate-g56z_1VW.mjs";
4
+ // src/contract/file-upload.contract.ts
5
+ let FileUpload = class FileUpload {};
6
+ FileUpload = __decorate([Injectable({ name: "fileUpload" })], FileUpload);
7
+ export { FileUpload as t };
@@ -0,0 +1,8 @@
1
+ // \0@oxc-project+runtime@0.160.0/helpers/esm/decorate.js
2
+ function __decorate(decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ }
8
+ export { __decorate as t };
@@ -0,0 +1,17 @@
1
+ import { EncodedFileUploadRequest, FileUploadValue } from "@deepseek-ai/dsh-client-file-upload/types";
2
+ /**
3
+ * `fileUploads` 组:一次编码上传。
4
+ *
5
+ * wire 上是**两个**命名参数——`agent`(descriptor 里是 lookup,wire 上放会话身份)与 `request`
6
+ * (`{ data, name? }`,`data` 是 base64)。契约按位置声明这两项,宿主侧 `registerRemoteGroup`
7
+ * 就按 `parameters` 的声明顺序逐个传参。应答是**裸值**(与上游 `@Remote` 同协议,失败即异常)。
8
+ */
9
+ export declare class FileUploadsEndpoint {
10
+ /**
11
+ * 上传一段编码后的字节,落成内容寻址的附件。
12
+ * @param _agent - 会话身份(上游按它查 agent)。
13
+ * @param _request - 编码后的文件内容与可选文件名。
14
+ * @returns 暂存回执与落盘的附件引用。
15
+ */
16
+ upload(_agent: string, _request: EncodedFileUploadRequest): Promise<FileUploadValue>;
17
+ }
@@ -0,0 +1,17 @@
1
+ import { RemoteGroup, RemoteMethod } from "@morlay/zephyr-app/remote";
2
+ import { t as __decorate } from "./decorate-g56z_1VW.mjs";
3
+ // src/endpoint/file-uploads.group.ts
4
+ let FileUploadsEndpoint = class FileUploadsEndpoint {
5
+ /**
6
+ * 上传一段编码后的字节,落成内容寻址的附件。
7
+ * @param _agent - 会话身份(上游按它查 agent)。
8
+ * @param _request - 编码后的文件内容与可选文件名。
9
+ * @returns 暂存回执与落盘的附件引用。
10
+ */
11
+ async upload(_agent, _request) {
12
+ throw new Error("fileUploads/upload:契约类未实现(宿主侧要在子类里实现它)");
13
+ }
14
+ };
15
+ __decorate([RemoteMethod({ parameters: ["agent", "request"] })], FileUploadsEndpoint.prototype, "upload", null);
16
+ FileUploadsEndpoint = __decorate([RemoteGroup({ name: "fileUploads" })], FileUploadsEndpoint);
17
+ export { FileUploadsEndpoint };
@@ -0,0 +1,21 @@
1
+ import { FileUploads } from "@deepseek-ai/dsh-client-file-upload";
2
+ import { AssertCoveredStrict, AssertTrue } from "@morlay/zephyr-app/client";
3
+ declare abstract class FileUploadStore {
4
+ abstract readonly registerAgentResolver: FileUploads["registerAgentResolver"];
5
+ abstract readonly resolve: FileUploads["resolve"];
6
+ abstract readonly bindPrompt: FileUploads["bindPrompt"];
7
+ abstract readonly retirePrompt: FileUploads["retirePrompt"];
8
+ abstract readonly upload: FileUploads["upload"];
9
+ abstract readonly uploadStream: FileUploads["uploadStream"];
10
+ abstract readonly typertRemote: FileUploads["typertRemote"];
11
+ abstract readonly uploadImageStream: FileUploads["uploadImageStream"];
12
+ }
13
+ /**
14
+ * 覆盖守卫(严格):上游 `FileUploads` 的每个成员都要有同名、同签名的对应项。
15
+ *
16
+ * 为什么不是 `implements`:上游那份是 cordis `Service` **类**(带私有成员),`implements` 会报
17
+ * TS2720("Did you mean to extend … and inherit its members as a subclass?")。签名守卫在这里等价:
18
+ * 漏成员或签名对不上,编译期都会报出成员名(诊断的第二行)。
19
+ */
20
+ type FileUploadStoreCovered = AssertTrue<AssertCoveredStrict<FileUploads, FileUploadStore>>;
21
+ export { FileUploadStoreCovered as n, FileUploadStore as t };
@@ -0,0 +1,6 @@
1
+ import { Injectable } from "@morlay/zephyr";
2
+ import { t as __decorate } from "./decorate-g56z_1VW.mjs";
3
+ // src/contract/file-upload-store.contract.ts
4
+ let FileUploadStore = class FileUploadStore {};
5
+ FileUploadStore = __decorate([Injectable({ name: "fileUploads" })], FileUploadStore);
6
+ export { FileUploadStore as t };
@@ -0,0 +1,31 @@
1
+ import { EncodedFileUploadRequest, FileUploadValue } from "@deepseek-ai/dsh-client-file-upload/types";
2
+ import { Context, OnDispose } from "@morlay/zephyr";
3
+ import { FileUploadsEndpoint } from "./endpoint.mjs";
4
+ import { FileUploads } from "@deepseek-ai/dsh-client-file-upload";
5
+ import { t as FileUploadStore } from "./file-upload-store.contract-N7aeXOZT.mjs";
6
+ /** `fileUploads` 组的宿主实现。 */
7
+ declare class FileUploadEndpointRow extends FileUploadsEndpoint implements OnDispose {
8
+ private readonly handlers;
9
+ private readonly uploads;
10
+ private readonly agents;
11
+ private readonly disposers;
12
+ onInit(): void;
13
+ /**
14
+ * 一次编码上传:解析接收方 agent,交给上游 `upload`(它落附件并暂存回执)。
15
+ * @param agent - wire 上的会话身份。
16
+ * @param request - `{ data, name? }`(`data` 是 base64;校验在上游的 zod codec 里)。
17
+ * @returns 暂存回执与落盘的附件引用。
18
+ */
19
+ upload(agent: string, request: EncodedFileUploadRequest): Promise<FileUploadValue>;
20
+ onDispose(): void;
21
+ }
22
+ declare const FileUploadStoreDefault_base: import("@morlay/zephyr/compat").AdaptedClass<typeof FileUploadStore, typeof FileUploads>;
23
+ declare class FileUploadStoreDefault extends FileUploadStoreDefault_base {
24
+ private readonly agents;
25
+ private readonly attachments;
26
+ private readonly commands;
27
+ private readonly connection;
28
+ onInit(ctx: Context): Promise<void>;
29
+ }
30
+ declare const provideUpload: (...features: import("@morlay/zephyr").ProviderFeature[]) => readonly [typeof FileUploadStoreDefault, typeof FileUploadEndpointRow, import("@morlay/zephyr-app").RemoteDescriptorEntry];
31
+ export { FileUploadStoreDefault as n, FileUploadEndpointRow as r, provideUpload as t };
@@ -0,0 +1,8 @@
1
+ import "./file-upload-store.contract-N7aeXOZT.mjs";
2
+ import { FileUploadService } from "@deepseek-ai/dsh-client-file-upload/client";
3
+ /** `ctx.fileUpload`:按会话身份暂存上传的服务。 */
4
+ declare abstract class FileUpload implements FileUploadService {
5
+ abstract readonly upload: FileUploadService["upload"];
6
+ abstract readonly uploadImage: FileUploadService["uploadImage"];
7
+ }
8
+ export { FileUpload as t };
@@ -0,0 +1,4 @@
1
+ import { n as FileUploadStoreCovered, t as FileUploadStore } from "./file-upload-store.contract-N7aeXOZT.mjs";
2
+ import { t as FileUpload } from "./index-BkrpumTg.mjs";
3
+ import { n as FileUploadStoreDefault, r as FileUploadEndpointRow, t as provideUpload } from "./index--fEY9uYM.mjs";
4
+ export { FileUpload, FileUploadEndpointRow, FileUploadStore, FileUploadStoreCovered, FileUploadStoreDefault, provideUpload };
package/dist/index.mjs ADDED
@@ -0,0 +1,4 @@
1
+ import { t as FileUploadStore } from "./file-upload-store.contract-iiZPCuot.mjs";
2
+ import { t as FileUpload } from "./contract-ERdRhC-u.mjs";
3
+ import { n as FileUploadStoreDefault, r as FileUploadEndpointRow, t as provideUpload } from "./server-C8rcRP76.mjs";
4
+ export { FileUpload, FileUploadEndpointRow, FileUploadStore, FileUploadStoreDefault, provideUpload };
@@ -0,0 +1,60 @@
1
+ import { SessionId } from "@morlay/dsh-session/endpoint";
2
+ import { AgentDirectory } from "@morlay/dsh-agent";
3
+ import { Injectable, inject, provide } from "@morlay/zephyr";
4
+ import { Connection, RemoteHandlers, remoteDescriptor } from "@morlay/zephyr-app";
5
+ import { RemoteGroup, registerRemoteGroup } from "@morlay/zephyr-app/remote";
6
+ import { t as FileUploadStore } from "./file-upload-store.contract-iiZPCuot.mjs";
7
+ import { FileUploadsEndpoint } from "./endpoint.mjs";
8
+ import { t as __decorate } from "./decorate-g56z_1VW.mjs";
9
+ import { FileUploads } from "@deepseek-ai/dsh-client-file-upload";
10
+ import { AttachmentStore } from "@morlay/dsh-attachment";
11
+ import { CommandRegistry } from "@morlay/dsh-command";
12
+ import { fromCordis } from "@morlay/zephyr/compat";
13
+ // src/server/file-upload-endpoint.ts
14
+ let FileUploadEndpointRow = class FileUploadEndpointRow extends FileUploadsEndpoint {
15
+ handlers = inject(RemoteHandlers);
16
+ uploads = inject(FileUploadStore);
17
+ agents = inject(AgentDirectory);
18
+ disposers = [];
19
+ onInit() {
20
+ this.disposers.push(registerRemoteGroup(this.handlers, this));
21
+ }
22
+ /**
23
+ * 一次编码上传:解析接收方 agent,交给上游 `upload`(它落附件并暂存回执)。
24
+ * @param agent - wire 上的会话身份。
25
+ * @param request - `{ data, name? }`(`data` 是 base64;校验在上游的 zod codec 里)。
26
+ * @returns 暂存回执与落盘的附件引用。
27
+ */
28
+ async upload(agent, request) {
29
+ const found = this.agents.get(SessionId(agent));
30
+ if (found === void 0) throw new Error(`fileUploads/upload: 会话 "${agent}" 没有 agent`);
31
+ return await this.uploads.upload(found, request, new AbortController().signal);
32
+ }
33
+ onDispose() {
34
+ for (const dispose of this.disposers.splice(0)) dispose();
35
+ }
36
+ };
37
+ FileUploadEndpointRow = __decorate([RemoteGroup(), Injectable()], FileUploadEndpointRow);
38
+ // src/file-upload-store.service.ts
39
+ let FileUploadStoreDefault = class FileUploadStoreDefault extends fromCordis(FileUploadStore, FileUploads) {
40
+ agents = inject(AgentDirectory);
41
+ attachments = inject(AttachmentStore);
42
+ commands = inject(CommandRegistry);
43
+ connection = inject(Connection);
44
+ async onInit(ctx) {
45
+ await this.mount(ctx, void 0, {
46
+ agents: this.agents,
47
+ attachments: this.attachments,
48
+ commands: this.commands,
49
+ connection: this.connection
50
+ });
51
+ }
52
+ };
53
+ FileUploadStoreDefault = __decorate([Injectable()], FileUploadStoreDefault);
54
+ // src/server/upload.provide.ts
55
+ const provideUpload = provide([
56
+ FileUploadStoreDefault,
57
+ FileUploadEndpointRow,
58
+ remoteDescriptor(() => import("@deepseek-ai/dsh-client-file-upload/remote"))
59
+ ]);
60
+ export { FileUploadStoreDefault as n, FileUploadEndpointRow as r, provideUpload as t };
@@ -0,0 +1,2 @@
1
+ import { r as FileUploadEndpointRow, t as provideUpload } from "./index--fEY9uYM.mjs";
2
+ export { FileUploadEndpointRow, provideUpload };
@@ -0,0 +1 @@
1
+ export { r as FileUploadEndpointRow, t as provideUpload } from "./server-C8rcRP76.mjs";
package/dist/ui.d.mts ADDED
@@ -0,0 +1,14 @@
1
+ import { t as FileUpload } from "./index-BkrpumTg.mjs";
2
+ import { FileUploadRuntime as FileUploadRuntime$1 } from "@deepseek-ai/dsh-client-file-upload/src/client/runtime.ts";
3
+ import { Context, ProviderList } from "@morlay/zephyr";
4
+ declare const FileUploadRuntime_base: import("@morlay/zephyr/compat").AdaptedClass<typeof FileUpload, typeof FileUploadRuntime$1>;
5
+ export declare class FileUploadRuntime extends FileUploadRuntime_base {
6
+ private readonly remote;
7
+ onInit(ctx: Context): Promise<void>;
8
+ }
9
+ /**
10
+ * 附件上传的行清单。
11
+ * @returns provider 清单。
12
+ */
13
+ export declare function provideFileUploadUi(): ProviderList;
14
+ export { FileUpload };
package/dist/ui.mjs ADDED
@@ -0,0 +1,318 @@
1
+ import { t as FileUpload } from "./contract-ERdRhC-u.mjs";
2
+ import { Service } from "@deepseek-ai/cordis";
3
+ import { bytesToBase64 } from "@deepseek-ai/dsh-util-crypto";
4
+ import { RemoteError } from "@deepseek-ai/dsh-typert-protocol";
5
+ import { TYPERT_REMOTE } from "@deepseek-ai/dsh-client-file-upload/remote";
6
+ import { Injectable, inject, provide } from "@morlay/zephyr";
7
+ import { fromCordis } from "@morlay/zephyr/compat";
8
+ import { Remote } from "@morlay/zephyr-app/client";
9
+ import { t as __decorate } from "./decorate-g56z_1VW.mjs";
10
+ /**
11
+ * Browser-relative form of {@link FILE_UPLOAD_PATH}; see
12
+ * .agents/notes/implemented/architecture/2026-09-14-web-document-relative-app-routes.md.
13
+ */
14
+ const FILE_UPLOAD_ROUTE = "/api/session/uploadFileBinary".slice(1);
15
+ // ../../../vendor/deepseek-harness/packages/client/file-upload/src/client/runtime.ts
16
+ /** Background browser upload implementation for Blob and byte-stream bodies. */
17
+ /**
18
+ * Self-contained Worker body; its string form becomes the Blob Worker source.
19
+ * @param scope - Worker global used for requests and progress messages.
20
+ * @param createXhr - XMLHttpRequest factory used for Blob progress.
21
+ * @param doFetch - Fetch carrier used for one-shot ReadableStream bodies.
22
+ */
23
+ function fileUploadWorker(scope = self, createXhr = () => new XMLHttpRequest(), doFetch = (input, init) => fetch(input, init)) {
24
+ scope.onmessage = (event) => {
25
+ const request = event.data;
26
+ if (request.body instanceof Blob) {
27
+ const xhr = createXhr();
28
+ xhr.open("POST", request.url);
29
+ xhr.withCredentials = true;
30
+ for (const [name, value] of Object.entries(request.headers)) xhr.setRequestHeader(name, value);
31
+ xhr.upload.onprogress = (progress) => {
32
+ scope.postMessage({
33
+ kind: "progress",
34
+ loaded: progress.loaded,
35
+ ...progress.lengthComputable ? { total: progress.total } : {}
36
+ });
37
+ };
38
+ xhr.onload = () => {
39
+ scope.postMessage({
40
+ kind: "complete",
41
+ status: xhr.status,
42
+ body: xhr.responseText
43
+ });
44
+ };
45
+ xhr.onerror = () => {
46
+ scope.postMessage({
47
+ kind: "error",
48
+ message: "background upload transport failed"
49
+ });
50
+ };
51
+ xhr.send(request.body);
52
+ return;
53
+ }
54
+ if (!(request.body instanceof ReadableStream)) {
55
+ scope.postMessage({
56
+ kind: "error",
57
+ message: "background upload worker received an invalid body"
58
+ });
59
+ return;
60
+ }
61
+ const source = request.body;
62
+ (async () => {
63
+ const reader = source.getReader();
64
+ let loaded = 0;
65
+ const body = new ReadableStream({
66
+ async pull(controller) {
67
+ const item = await reader.read();
68
+ if (item.done) {
69
+ controller.close();
70
+ return;
71
+ }
72
+ if (!(item.value instanceof Uint8Array)) throw new TypeError("background upload stream produced a non-Uint8Array chunk");
73
+ loaded += item.value.byteLength;
74
+ scope.postMessage({
75
+ kind: "progress",
76
+ loaded
77
+ });
78
+ controller.enqueue(item.value);
79
+ },
80
+ async cancel(reason) {
81
+ await reader.cancel(reason);
82
+ }
83
+ });
84
+ const response = await doFetch(request.url, {
85
+ method: "POST",
86
+ headers: request.headers,
87
+ credentials: "include",
88
+ body,
89
+ duplex: "half"
90
+ });
91
+ scope.postMessage({
92
+ kind: "complete",
93
+ status: response.status,
94
+ body: await response.text()
95
+ });
96
+ })().catch((error) => {
97
+ scope.postMessage({
98
+ kind: "error",
99
+ message: error instanceof Error ? error.message : String(error)
100
+ });
101
+ });
102
+ };
103
+ }
104
+ /** Cordis service that owns one background carrier per upload operation. */
105
+ var FileUploadRuntime$1 = class extends Service {
106
+ transport;
107
+ /** @param ctx - providing Client context. */
108
+ constructor(ctx) {
109
+ super(ctx, "fileUpload");
110
+ const hook = globalThis.__DSH_FILE_UPLOAD__;
111
+ this.transport = hook === void 0 ? workerTransport() : customTransport(hook.fetch);
112
+ }
113
+ /**
114
+ * Post one body with the carrier selected before Cordis boot.
115
+ * @param request - target, body, cancellation, and progress observer.
116
+ * @returns the response status and text body.
117
+ */
118
+ post(request) {
119
+ return this.transport.post(request);
120
+ }
121
+ /**
122
+ * Store one file for a Session.
123
+ * @param sessionId - Session that owns the staged receipt.
124
+ * @param data - browser Blob, exact bytes, or a one-shot byte stream.
125
+ * @param name - optional display name.
126
+ * @param signal - optional cancellation for the active upload.
127
+ * @param onProgress - optional byte-progress observer for background bodies.
128
+ * @returns the staged receipt and durable file reference, or a business error.
129
+ */
130
+ async upload(sessionId, data, name, signal, onProgress) {
131
+ if (!(data instanceof Uint8Array)) {
132
+ const query = new URLSearchParams({ sessionId });
133
+ if (name !== void 0) query.set("name", name);
134
+ return parseUploadResult(await this.postRaw(query, data, signal, onProgress), fileUploadValue);
135
+ }
136
+ return this.ctx.remote.fileUploads.upload(sessionId, {
137
+ data: bytesToBase64(data),
138
+ ...name === void 0 ? {} : { name }
139
+ }, signal);
140
+ }
141
+ /**
142
+ * Store one prompt image for a Session.
143
+ * @param sessionId - Session that owns the staged receipt.
144
+ * @param data - browser image Blob.
145
+ * @param mediaType - declared image media type.
146
+ * @param name - optional display name.
147
+ * @param signal - optional cancellation for the active upload.
148
+ * @param onProgress - optional byte-progress observer.
149
+ * @returns the staged receipt and normalized image reference, or a business error.
150
+ */
151
+ async uploadImage(sessionId, data, mediaType, name, signal, onProgress) {
152
+ const query = new URLSearchParams({
153
+ sessionId,
154
+ mediaType
155
+ });
156
+ if (name !== void 0) query.set("name", name);
157
+ return parseUploadResult(await this.postRaw(query, data, signal, onProgress), imageUploadValue);
158
+ }
159
+ /** Post one raw body to the upload route; a non-200 status is a transport failure. */
160
+ async postRaw(query, body, signal, onProgress) {
161
+ const response = await this.post({
162
+ path: `${FILE_UPLOAD_ROUTE}?${query.toString()}`,
163
+ body,
164
+ headers: { "content-type": "application/octet-stream" },
165
+ ...signal === void 0 ? {} : { signal },
166
+ ...onProgress === void 0 ? {} : { onProgress }
167
+ });
168
+ if (response.status !== 200) throw new Error(`file upload transport failed with HTTP ${String(response.status)}`);
169
+ return response.body;
170
+ }
171
+ };
172
+ function customTransport(customFetch) {
173
+ return { async post(request) {
174
+ const init = {
175
+ method: "POST",
176
+ ...request.headers === void 0 ? {} : { headers: request.headers },
177
+ body: request.body,
178
+ ...request.body instanceof ReadableStream ? { duplex: "half" } : {},
179
+ ...request.signal === void 0 ? {} : { signal: request.signal }
180
+ };
181
+ const response = await customFetch(request.path, init);
182
+ return {
183
+ status: response.status,
184
+ body: await response.text()
185
+ };
186
+ } };
187
+ }
188
+ function workerTransport() {
189
+ return { post(request) {
190
+ if (typeof Worker !== "function") return Promise.reject(/* @__PURE__ */ new Error("background upload requires Web Worker support"));
191
+ const workerUrl = URL.createObjectURL(new Blob([`(${fileUploadWorker.toString()})()`], { type: "text/javascript" }));
192
+ const worker = new Worker(workerUrl, { name: "dsh-file-upload" });
193
+ URL.revokeObjectURL(workerUrl);
194
+ return new Promise((resolve, reject) => {
195
+ let settled = false;
196
+ const abort = () => {
197
+ settled = true;
198
+ worker.terminate();
199
+ request.signal?.removeEventListener("abort", abort);
200
+ reject(new DOMException("The operation was aborted.", "AbortError"));
201
+ };
202
+ const finish = (settle) => {
203
+ if (settled) return;
204
+ settled = true;
205
+ request.signal?.removeEventListener("abort", abort);
206
+ worker.terminate();
207
+ settle();
208
+ };
209
+ worker.onmessage = (event) => {
210
+ const output = event.data;
211
+ if (output.kind === "progress") request.onProgress?.({
212
+ loaded: output.loaded,
213
+ ...output.total === void 0 ? {} : { total: output.total }
214
+ });
215
+ else if (output.kind === "complete") finish(() => {
216
+ resolve({
217
+ status: output.status,
218
+ body: output.body
219
+ });
220
+ });
221
+ else finish(() => {
222
+ reject(new Error(output.message));
223
+ });
224
+ };
225
+ worker.onerror = (event) => {
226
+ finish(() => {
227
+ reject(new Error(event.message || "background upload worker failed"));
228
+ });
229
+ };
230
+ if (request.signal?.aborted === true) {
231
+ abort();
232
+ return;
233
+ }
234
+ request.signal?.addEventListener("abort", abort, { once: true });
235
+ const message = {
236
+ url: new URL(request.path, document.baseURI).href,
237
+ body: request.body,
238
+ headers: request.headers ?? {}
239
+ };
240
+ if (request.body instanceof ReadableStream) worker.postMessage(message, [request.body]);
241
+ else worker.postMessage(message);
242
+ });
243
+ } };
244
+ }
245
+ function parseUploadResult(body, parseValue) {
246
+ const value = JSON.parse(body);
247
+ if (!isRecord(value) || typeof value.ok !== "boolean") throw new TypeError("file upload transport returned an invalid result");
248
+ if (!value.ok) {
249
+ const error = value.error;
250
+ if (!isRecord(error) || typeof error.code !== "string" || typeof error.message !== "string" || !isRecord(error.details)) throw new TypeError("file upload transport returned an invalid failure");
251
+ return {
252
+ ok: false,
253
+ error: new RemoteError(error.code, error.message, error.details)
254
+ };
255
+ }
256
+ return {
257
+ ok: true,
258
+ value: parseValue(value.value)
259
+ };
260
+ }
261
+ function fileUploadValue(result) {
262
+ const file = isRecord(result) ? result.file : void 0;
263
+ if (!isRecord(result) || typeof result.receiptId !== "string" || !isRecord(file) || typeof file.attachmentId !== "string" || typeof file.name !== "string" || !isNonNegativeInteger(file.bytes)) throw new TypeError("file upload transport returned an invalid receipt");
264
+ return {
265
+ receiptId: result.receiptId,
266
+ file: {
267
+ attachmentId: file.attachmentId,
268
+ name: file.name,
269
+ bytes: file.bytes
270
+ }
271
+ };
272
+ }
273
+ function imageUploadValue(result) {
274
+ const image = isRecord(result) ? result.image : void 0;
275
+ if (!isRecord(result) || typeof result.receiptId !== "string" || !isRecord(image) || typeof image.attachmentId !== "string" || !isImageMediaType(image.mediaType) || !isNonNegativeInteger(image.bytes) || !isNonNegativeInteger(image.width) || !isNonNegativeInteger(image.height) || image.name !== void 0 && typeof image.name !== "string" || image.originalDimensions !== void 0 && !isDimensions(image.originalDimensions)) throw new TypeError("file upload transport returned an invalid image receipt");
276
+ return {
277
+ receiptId: result.receiptId,
278
+ image: {
279
+ attachmentId: image.attachmentId,
280
+ mediaType: image.mediaType,
281
+ bytes: image.bytes,
282
+ width: image.width,
283
+ height: image.height,
284
+ ...image.name === void 0 ? {} : { name: image.name },
285
+ ...image.originalDimensions === void 0 ? {} : { originalDimensions: image.originalDimensions }
286
+ }
287
+ };
288
+ }
289
+ function isNonNegativeInteger(value) {
290
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
291
+ }
292
+ function isImageMediaType(value) {
293
+ return value === "image/png" || value === "image/jpeg" || value === "image/webp" || value === "image/gif";
294
+ }
295
+ function isDimensions(value) {
296
+ return isRecord(value) && isNonNegativeInteger(value.width) && isNonNegativeInteger(value.height);
297
+ }
298
+ function isRecord(value) {
299
+ return typeof value === "object" && value !== null && !Array.isArray(value);
300
+ }
301
+ // src/ui/file-upload-runtime.ts
302
+ let FileUploadRuntime = class FileUploadRuntime extends fromCordis(FileUpload, FileUploadRuntime$1) {
303
+ remote = inject(Remote);
304
+ async onInit(ctx) {
305
+ await this.remote.$mount(TYPERT_REMOTE);
306
+ await this.mount(ctx, void 0, { remote: this.remote });
307
+ }
308
+ };
309
+ FileUploadRuntime = __decorate([Injectable()], FileUploadRuntime);
310
+ // src/ui/file-upload.provide.ts
311
+ /**
312
+ * 附件上传的行清单。
313
+ * @returns provider 清单。
314
+ */
315
+ function provideFileUploadUi() {
316
+ return provide([FileUploadRuntime])();
317
+ }
318
+ export { FileUpload, FileUploadRuntime, provideFileUploadUi };
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
2
  "name": "@morlay/dsh-upload",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.0-alpha.0",
4
+ "private": false,
5
+ "description": "附件上传面:先给宿主一个只登记解析器的最小实现,真正的上传与解析另排期。",
6
+ "files": [
7
+ "dist",
8
+ "src",
9
+ "!**/__tests__"
10
+ ],
11
+ "type": "module",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.mts",
15
+ "default": "./dist/index.mjs"
16
+ },
17
+ "./server": {
18
+ "types": "./dist/server.d.mts",
19
+ "default": "./dist/server.mjs"
20
+ },
21
+ "./endpoint": {
22
+ "types": "./dist/endpoint.d.mts",
23
+ "default": "./dist/endpoint.mjs"
24
+ },
25
+ "./ui": {
26
+ "types": "./dist/ui.d.mts",
27
+ "default": "./dist/ui.mjs"
28
+ },
29
+ "./package.json": "./package.json"
30
+ },
31
+ "dependencies": {
32
+ "@morlay/dsh-agent": "^0.2.0-alpha.0",
33
+ "@morlay/dsh-attachment": "^0.2.0-alpha.0",
34
+ "@morlay/dsh-command": "^0.2.0-alpha.0",
35
+ "@morlay/dsh-session": "^0.2.0-alpha.0",
36
+ "@morlay/zephyr": "^0.2.0-alpha.0",
37
+ "@morlay/zephyr-app": "^0.2.0-alpha.0"
38
+ },
39
+ "peerDependencies": {
40
+ "@deepseek-ai/dsh-client-file-upload": "^0.2.3-alpha.3"
41
+ },
42
+ "engines": {
43
+ "dsh": ">= 0.2.3-alpha.3 < 0.2.4"
44
+ },
45
+ "repository": {
46
+ "type": "git",
47
+ "url": "https://github.com/morlay/zephyr.git",
48
+ "directory": "packages/agent/dsh-upload"
49
+ },
50
+ "scripts": {}
6
51
  }
@@ -0,0 +1,32 @@
1
+ // `fileUploads`:浏览器上传的宿主服务面(上游 `FileUploads` 经 `fromCordis` 接管)。
2
+ import type { FileUploads } from "@deepseek-ai/dsh-client-file-upload";
3
+ import { Injectable } from "@morlay/zephyr";
4
+ import type { AssertCoveredStrict, AssertTrue } from "@morlay/zephyr-app/client";
5
+
6
+ @Injectable({ name: "fileUploads" })
7
+ export abstract class FileUploadStore {
8
+ abstract readonly registerAgentResolver: FileUploads["registerAgentResolver"];
9
+
10
+ abstract readonly resolve: FileUploads["resolve"];
11
+
12
+ abstract readonly bindPrompt: FileUploads["bindPrompt"];
13
+
14
+ abstract readonly retirePrompt: FileUploads["retirePrompt"];
15
+
16
+ abstract readonly upload: FileUploads["upload"];
17
+
18
+ abstract readonly uploadStream: FileUploads["uploadStream"];
19
+
20
+ abstract readonly typertRemote: FileUploads["typertRemote"];
21
+
22
+ abstract readonly uploadImageStream: FileUploads["uploadImageStream"];
23
+ }
24
+
25
+ /**
26
+ * 覆盖守卫(严格):上游 `FileUploads` 的每个成员都要有同名、同签名的对应项。
27
+ *
28
+ * 为什么不是 `implements`:上游那份是 cordis `Service` **类**(带私有成员),`implements` 会报
29
+ * TS2720("Did you mean to extend … and inherit its members as a subclass?")。签名守卫在这里等价:
30
+ * 漏成员或签名对不上,编译期都会报出成员名(诊断的第二行)。
31
+ */
32
+ export type FileUploadStoreCovered = AssertTrue<AssertCoveredStrict<FileUploads, FileUploadStore>>;
@@ -0,0 +1,18 @@
1
+ // `ctx.fileUpload` 契约(浏览器侧):上游 `file-upload` client 半的上传服务面。
2
+ //
3
+ // 成员来自上游 `FileUploadService`:会话界面的输入区把它交给上游 `ConversationController` 的上传队列
4
+ // (粘贴/拖入的图片走 `uploadImage`,普通文件走 `upload`)。实现是 `FileUploadRuntime`
5
+ // (`fromCordis` 照装上游 client 半,契约面就是它发布的服务)。
6
+ //
7
+ // 契约类而不是值令牌:`inject(FileUpload)` 拿到的是**有方法的服务**,装配期缺提供者会当场报错
8
+ // (值令牌会被"上游 mount 期按名字发布"放过,坏在这一步是静默的——粘贴无反应正是这么来的)。
9
+ import type { FileUploadService } from "@deepseek-ai/dsh-client-file-upload/client";
10
+ import { Injectable } from "@morlay/zephyr";
11
+
12
+ /** `ctx.fileUpload`:按会话身份暂存上传的服务。 */
13
+ @Injectable({ name: "fileUpload" })
14
+ export abstract class FileUpload implements FileUploadService {
15
+ abstract readonly upload: FileUploadService["upload"];
16
+
17
+ abstract readonly uploadImage: FileUploadService["uploadImage"];
18
+ }
@@ -0,0 +1,3 @@
1
+ // upload 域的契约面(`@morlay/dsh-upload/contract`):进程内的端口,不涉及 remote。
2
+ export * from "./file-upload-store.contract.ts";
3
+ export * from "./file-upload.contract.ts";
@@ -0,0 +1,32 @@
1
+ // `fileUploads` 组的**两端共用面**:组名、方法名与那次上传的请求/应答形状
2
+ // (与上游 `client/file-upload` 的描述符一致)。
3
+ //
4
+ // 组名与方法名的家是下面契约类上的 `@RemoteGroup({ name })` / `@RemoteMethod()`:宿主侧
5
+ // (`server/file-upload-endpoint.ts`)继承它实现方法。客户端形态不在本仓:这一组的客户端面由上游
6
+ // `@deepseek-ai/dsh-client-file-upload#fileUploads` 的 `$mount` 面提供。
7
+ import type {
8
+ EncodedFileUploadRequest,
9
+ FileUploadValue,
10
+ } from "@deepseek-ai/dsh-client-file-upload/types";
11
+ import { RemoteGroup, RemoteMethod } from "@morlay/zephyr-app/remote";
12
+
13
+ /**
14
+ * `fileUploads` 组:一次编码上传。
15
+ *
16
+ * wire 上是**两个**命名参数——`agent`(descriptor 里是 lookup,wire 上放会话身份)与 `request`
17
+ * (`{ data, name? }`,`data` 是 base64)。契约按位置声明这两项,宿主侧 `registerRemoteGroup`
18
+ * 就按 `parameters` 的声明顺序逐个传参。应答是**裸值**(与上游 `@Remote` 同协议,失败即异常)。
19
+ */
20
+ @RemoteGroup({ name: "fileUploads" })
21
+ export class FileUploadsEndpoint {
22
+ /**
23
+ * 上传一段编码后的字节,落成内容寻址的附件。
24
+ * @param _agent - 会话身份(上游按它查 agent)。
25
+ * @param _request - 编码后的文件内容与可选文件名。
26
+ * @returns 暂存回执与落盘的附件引用。
27
+ */
28
+ @RemoteMethod({ parameters: ["agent", "request"] })
29
+ async upload(_agent: string, _request: EncodedFileUploadRequest): Promise<FileUploadValue> {
30
+ throw new Error("fileUploads/upload:契约类未实现(宿主侧要在子类里实现它)");
31
+ }
32
+ }
@@ -0,0 +1,2 @@
1
+ // upload 域的 **RPC 面**(`@morlay/dsh-upload/endpoint`):`fileUploads` 组的两端共用面。
2
+ export * from "./file-uploads.group.ts";
@@ -0,0 +1,30 @@
1
+ // `fileUploads` 的宿主行:上游 `FileUploads` 本身就是完整服务(`super(ctx, 'fileUploads')`、注册 HTTP
2
+ // 上传路由与命令回执解析器、观察会话事件),本包不重新实现,只把它接到我们已装的四个服务上。
3
+ import { FileUploads } from "@deepseek-ai/dsh-client-file-upload";
4
+ import { AgentDirectory } from "@morlay/dsh-agent";
5
+ import { AttachmentStore } from "@morlay/dsh-attachment";
6
+ import { CommandRegistry } from "@morlay/dsh-command";
7
+ import { Connection } from "@morlay/zephyr-app";
8
+ import { inject, Injectable, type Context } from "@morlay/zephyr";
9
+ import { fromCordis } from "@morlay/zephyr/compat";
10
+ import { FileUploadStore } from "./contract/file-upload-store.contract.ts";
11
+
12
+ @Injectable()
13
+ export class FileUploadStoreDefault extends fromCordis(FileUploadStore, FileUploads) {
14
+ private readonly agents = inject(AgentDirectory);
15
+
16
+ private readonly attachments = inject(AttachmentStore);
17
+
18
+ private readonly commands = inject(CommandRegistry);
19
+
20
+ private readonly connection = inject(Connection);
21
+
22
+ override async onInit(ctx: Context): Promise<void> {
23
+ await this.mount(ctx, undefined, {
24
+ agents: this.agents,
25
+ attachments: this.attachments,
26
+ commands: this.commands,
27
+ connection: this.connection,
28
+ });
29
+ }
30
+ }
package/src/index.ts ADDED
@@ -0,0 +1,4 @@
1
+ // upload 域的包根:契约 + 默认实现 + 装配模块(聚合 `./contract`)。
2
+ export * from "./contract/index.ts";
3
+ export * from "./server/index.ts";
4
+ export * from "./file-upload-store.service.ts";
@@ -0,0 +1,57 @@
1
+ // `fileUploads` 组的**宿主实现**(wire 端点):继承 `endpoint/` 的契约类,转发到上游 `FileUploads`。
2
+ //
3
+ // 上游 client(`ui-conversation` 的上传运行时)对 `Uint8Array` 走 **remote** 这条路:
4
+ // `remote.fileUploads.upload(sessionId, { data: base64, name? }, signal)`——descriptor 的第一个参数名是
5
+ // `agent`(lookup,wire 上放的是 `SessionId`),第二个是 `request`。
6
+ // 宿主这边落到上游 `FileUploads.upload(agent, request, signal)`:本包的 `FileUploadStoreDefault` 已经把
7
+ // 上游实例挂上来了,这里只做「会话 → agent」的解析与结果的转发。
8
+ //
9
+ // 组名与方法名都来自契约(`@RemoteGroup` / `@RemoteMethod`),这里不出现 `"fileUploads/upload"` 这种字符串。
10
+ import type {
11
+ EncodedFileUploadRequest,
12
+ FileUploadValue,
13
+ } from "@deepseek-ai/dsh-client-file-upload/types";
14
+ import { SessionId } from "@morlay/dsh-session/endpoint";
15
+ import { AgentDirectory } from "@morlay/dsh-agent";
16
+ import { inject, Injectable, type OnDispose } from "@morlay/zephyr";
17
+ import { RemoteHandlers } from "@morlay/zephyr-app";
18
+ import { RemoteGroup, registerRemoteGroup } from "@morlay/zephyr-app/remote";
19
+ import { FileUploadStore } from "../contract/file-upload-store.contract.ts";
20
+ import { FileUploadsEndpoint } from "../endpoint/index.ts";
21
+
22
+ /** `fileUploads` 组的宿主实现。 */
23
+ @RemoteGroup()
24
+ @Injectable()
25
+ export class FileUploadEndpointRow extends FileUploadsEndpoint implements OnDispose {
26
+ private readonly handlers = inject(RemoteHandlers);
27
+
28
+ private readonly uploads = inject(FileUploadStore);
29
+
30
+ private readonly agents = inject(AgentDirectory);
31
+
32
+ private readonly disposers: (() => void)[] = [];
33
+
34
+ onInit(): void {
35
+ this.disposers.push(registerRemoteGroup(this.handlers, this));
36
+ }
37
+
38
+ /**
39
+ * 一次编码上传:解析接收方 agent,交给上游 `upload`(它落附件并暂存回执)。
40
+ * @param agent - wire 上的会话身份。
41
+ * @param request - `{ data, name? }`(`data` 是 base64;校验在上游的 zod codec 里)。
42
+ * @returns 暂存回执与落盘的附件引用。
43
+ */
44
+ override async upload(
45
+ agent: string,
46
+ request: EncodedFileUploadRequest,
47
+ ): Promise<FileUploadValue> {
48
+ const found = this.agents.get(SessionId(agent));
49
+ if (found === undefined) throw new Error(`fileUploads/upload: 会话 "${agent}" 没有 agent`);
50
+ // 裸值协议(与上游 `@Remote` 一致):失败是异常,不再包 `{ ok, value }`。
51
+ return await this.uploads.upload(found, request, new AbortController().signal);
52
+ }
53
+
54
+ onDispose(): void {
55
+ for (const dispose of this.disposers.splice(0)) dispose();
56
+ }
57
+ }
@@ -0,0 +1,3 @@
1
+ // upload 的**宿主半**(`@morlay/dsh-upload/server`):wire 端点。
2
+ export { FileUploadEndpointRow } from "./file-upload-endpoint.ts";
3
+ export { provideUpload } from "./upload.provide.ts";
@@ -0,0 +1,10 @@
1
+ import { provide } from "@morlay/zephyr";
2
+ import { remoteDescriptor } from "@morlay/zephyr-app";
3
+ import { FileUploadStoreDefault } from "../file-upload-store.service.ts";
4
+ import { FileUploadEndpointRow } from "./file-upload-endpoint.ts";
5
+
6
+ export const provideUpload = provide([
7
+ FileUploadStoreDefault,
8
+ FileUploadEndpointRow,
9
+ remoteDescriptor(() => import("@deepseek-ai/dsh-client-file-upload/remote")),
10
+ ]);
@@ -0,0 +1,30 @@
1
+ // 附件上传运行时(`ctx.fileUpload`):上游 `file-upload` 的运行时是 cordis `Service` 子类,
2
+ // 构造里 `super(ctx, "fileUpload")` 把自己注册进 store。
3
+ //
4
+ // **为什么不用上游那个 `apply`**:它只做一件事——`ctx.plugin(FileUploadRuntime)`,那个子 fiber 挂在
5
+ // **本行**下面。而按名字读服务(`ctx.fileUpload` 的严格读)只认**祖先 fiber** 上的 provision 或根 ctx 上的
6
+ // 注册:会话界面的 `ConversationController` 里 `this.ctx` 是会话 scope ctx(`ClientSessions.createScope`
7
+ // 建的,链只到根),于是抛 `cannot get property "fileUpload" without inject`——真机上的现象正是
8
+ // 「粘贴图片 → chip 变红、没有上传请求」(实测栈落在 `pumpFileUploads`)。
9
+ //
10
+ // 所以按 `fromCordis` 的 **Service 分支**接(与 `WebTerminalsDefault` 用根 ctx 建 `ClientTerminals` 同一落点):
11
+ // 服务由根 fiber 拥有,兄弟行与更深的 fiber 都读得到;契约面(`FileUpload`)就是那个实例。
12
+ import { FileUploadRuntime as UpstreamFileUploadRuntime } from "@deepseek-ai/dsh-client-file-upload/src/client/runtime.ts";
13
+ import { TYPERT_REMOTE as FILE_UPLOAD_REMOTE } from "@deepseek-ai/dsh-client-file-upload/remote";
14
+ import { inject, Injectable, type Context } from "@morlay/zephyr";
15
+ import { fromCordis } from "@morlay/zephyr/compat";
16
+ import { Remote } from "@morlay/zephyr-app/client";
17
+ // 附件的行住在 upload 域(上游 `file-upload` 归这里);契约的消费方是会话界面的输入区,
18
+ // 令牌由本包的 ui 面导出(upload 域不反向依赖它)。
19
+ import { FileUpload } from "../contract/index.ts";
20
+
21
+ @Injectable()
22
+ export class FileUploadRuntime extends fromCordis(FileUpload, UpstreamFileUploadRuntime) {
23
+ private readonly remote = inject(Remote);
24
+
25
+ override async onInit(ctx: Context): Promise<void> {
26
+ await this.remote.$mount(FILE_UPLOAD_REMOTE);
27
+ // 上游构造里读 `ctx.remote`(`remote.fileUploads` 的字节上传走它):按 deps 交进去。
28
+ await this.mount(ctx, undefined, { remote: this.remote });
29
+ }
30
+ }
@@ -0,0 +1,14 @@
1
+ // upload 域的**浏览器半装配**:附件上传运行时。
2
+ //
3
+ // 这一行要 `remote`(挂 `FILE_UPLOAD_REMOTE` 描述符)与会话界面的输入区就位,装配面把它排在
4
+ // `provideSessionInputSlots()` 之后。
5
+ import { provide, type ProviderList } from "@morlay/zephyr";
6
+ import { FileUploadRuntime } from "./file-upload-runtime.ts";
7
+
8
+ /**
9
+ * 附件上传的行清单。
10
+ * @returns provider 清单。
11
+ */
12
+ export function provideFileUploadUi(): ProviderList {
13
+ return provide([FileUploadRuntime])();
14
+ }
@@ -0,0 +1,6 @@
1
+ // upload 域的**浏览器半**(`@morlay/dsh-upload/ui`):附件上传运行时(`ctx.fileUpload`)。
2
+ //
3
+ // 上游 `@deepseek-ai/dsh-client-file-upload` 的 client 半归本域;会话界面的输入区从这里取这一行装配。
4
+ export { FileUpload } from "../contract/index.ts";
5
+ export { FileUploadRuntime } from "./file-upload-runtime.ts";
6
+ export { provideFileUploadUi } from "./file-upload.provide.ts";