@morlay/dsh-desktop-host 0.0.1-alpha.2 → 0.0.1-alpha.4

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/lib/index.js CHANGED
@@ -1,10 +1,16 @@
1
+ import { DESKTOP_PIPE_CHUNK_BYTES, DESKTOP_STREAM_PATH, DesktopHostRequestDecoder, encodeDesktopResponseData, encodeDesktopResponseEnd, encodeDesktopResponseError, encodeDesktopResponseStart, isDesktopHostCommand } from "./wire.js";
1
2
  import { createRequire } from "node:module";
2
- import { delimiter, dirname, join } from "node:path";
3
+ import { once } from "node:events";
4
+ import { createReadStream, createWriteStream } from "node:fs";
5
+ import { dirname, join } from "node:path";
6
+ import { fileURLToPath } from "node:url";
3
7
  import { loadLayeredEnv, loadProfileDirectory } from "@deepseek-ai/dsh-app-boot";
4
8
  import { runProfile } from "@deepseek-ai/dsh/profile-boot";
5
9
  import { resolveDshHome } from "@deepseek-ai/dsh-home-paths";
6
10
  import { Context, Service } from "@deepseek-ai/cordis";
11
+ import z from "@deepseek-ai/schemastery";
7
12
  import { cp, lstat, mkdir, mkdtemp, readFile, rename, rm, stat } from "node:fs/promises";
13
+ import { Buffer as Buffer$1 } from "node:buffer";
8
14
  //#region \0rolldown/runtime.js
9
15
  var __defProp = Object.defineProperty;
10
16
  var __exportAll = (all, no_symbols) => {
@@ -17,796 +23,6 @@ var __exportAll = (all, no_symbols) => {
17
23
  return target;
18
24
  };
19
25
  //#endregion
20
- //#region ../../../vendor/deepseek-harness/vendor/cosmokit/lib/index.js
21
- /** Return true when a value is `null` or `undefined`. */
22
- function isNullable(value) {
23
- return value === null || value === void 0;
24
- }
25
- /** Return true for non-array object values. */
26
- function isPlainObject(data) {
27
- return data && typeof data === "object" && !Array.isArray(data);
28
- }
29
- /** Filter object entries and return a new object. */
30
- function filterKeys(object, filter) {
31
- return Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)));
32
- }
33
- /** Map object values while preserving the original key set. */
34
- function mapValues(object, transform) {
35
- return Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));
36
- }
37
- /** Pick selected keys from an object, optionally including `undefined` values. */
38
- function pick(source, keys, forced) {
39
- if (!keys) return { ...source };
40
- const result = {};
41
- for (const key of keys) if (forced || source[key] !== void 0) result[key] = source[key];
42
- return result;
43
- }
44
- /** Test values using `instanceof` with a `toStringTag` fallback. */
45
- function is(type, value) {
46
- if (arguments.length === 1) return (value) => is(type, value);
47
- return type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;
48
- }
49
- function isArrayBufferLike(value) {
50
- return is("ArrayBuffer", value) || is("SharedArrayBuffer", value);
51
- }
52
- function isArrayBufferSource(value) {
53
- return isArrayBufferLike(value) || ArrayBuffer.isView(value);
54
- }
55
- /** Binary source detection and base64/hex conversion helpers. */
56
- var Binary;
57
- (function(Binary) {
58
- Binary.is = isArrayBufferLike;
59
- Binary.isSource = isArrayBufferSource;
60
- function fromSource(source) {
61
- if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
62
- else return source;
63
- }
64
- Binary.fromSource = fromSource;
65
- function toBase64(source) {
66
- source = fromSource(source);
67
- if (typeof Buffer !== "undefined") return Buffer.from(source).toString("base64");
68
- let binary = "";
69
- const bytes = new Uint8Array(source);
70
- for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
71
- return btoa(binary);
72
- }
73
- Binary.toBase64 = toBase64;
74
- function fromBase64(source) {
75
- if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "base64"));
76
- return Uint8Array.from(atob(source), (c) => c.charCodeAt(0));
77
- }
78
- Binary.fromBase64 = fromBase64;
79
- function toHex(source) {
80
- source = fromSource(source);
81
- if (typeof Buffer !== "undefined") return Buffer.from(source).toString("hex");
82
- return Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, "0")).join("");
83
- }
84
- Binary.toHex = toHex;
85
- function fromHex(source) {
86
- if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "hex"));
87
- const hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);
88
- const buffer = [];
89
- for (let i = 0; i < hex.length; i += 2) buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));
90
- return Uint8Array.from(buffer).buffer;
91
- }
92
- Binary.fromHex = fromHex;
93
- })(Binary || (Binary = {}));
94
- Binary.fromBase64;
95
- Binary.toBase64;
96
- Binary.fromHex;
97
- Binary.toHex;
98
- /** Deep-clone common JavaScript values while preserving prototypes and cycles. */
99
- function clone(source, refs = /* @__PURE__ */ new Map()) {
100
- if (!source || typeof source !== "object") return source;
101
- if (is("Date", source)) return new Date(source.valueOf());
102
- if (is("RegExp", source)) return new RegExp(source.source, source.flags);
103
- if (isArrayBufferLike(source)) return source.slice(0);
104
- if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
105
- const cached = refs.get(source);
106
- if (cached) return cached;
107
- if (Array.isArray(source)) {
108
- const result = [];
109
- refs.set(source, result);
110
- source.forEach((value, index) => {
111
- result[index] = Reflect.apply(clone, null, [value, refs]);
112
- });
113
- return result;
114
- }
115
- const result = Object.create(Object.getPrototypeOf(source));
116
- refs.set(source, result);
117
- for (const key of Reflect.ownKeys(source)) {
118
- const descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) };
119
- if ("value" in descriptor) descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs]);
120
- Reflect.defineProperty(result, key, descriptor);
121
- }
122
- return result;
123
- }
124
- /** Deeply compare arrays, dates, regexps, buffers, and plain object fields. */
125
- function deepEqual(a, b, strict) {
126
- if (a === b) return true;
127
- if (!strict && isNullable(a) && isNullable(b)) return true;
128
- if (typeof a !== typeof b) return false;
129
- if (typeof a !== "object") return false;
130
- if (!a || !b) return false;
131
- function check(test, then) {
132
- return test(a) ? test(b) ? then(a, b) : false : test(b) ? false : void 0;
133
- }
134
- return check(Array.isArray, (a, b) => a.length === b.length && a.every((item, index) => deepEqual(item, b[index]))) ?? check(is("Date"), (a, b) => a.valueOf() === b.valueOf()) ?? check(is("RegExp"), (a, b) => a.source === b.source && a.flags === b.flags) ?? check(isArrayBufferLike, (a, b) => {
135
- if (a.byteLength !== b.byteLength) return false;
136
- const viewA = new Uint8Array(a);
137
- const viewB = new Uint8Array(b);
138
- for (let i = 0; i < viewA.length; i++) if (viewA[i] !== viewB[i]) return false;
139
- return true;
140
- }) ?? Object.keys({
141
- ...a,
142
- ...b
143
- }).every((key) => deepEqual(a[key], b[key], strict));
144
- }
145
- /** Time constants plus parsing and formatting helpers. */
146
- var Time;
147
- (function(Time) {
148
- Time.millisecond = 1;
149
- Time.second = 1e3;
150
- Time.minute = Time.second * 60;
151
- Time.hour = Time.minute * 60;
152
- Time.day = Time.hour * 24;
153
- Time.week = Time.day * 7;
154
- let timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();
155
- function setTimezoneOffset(offset) {
156
- timezoneOffset = offset;
157
- }
158
- Time.setTimezoneOffset = setTimezoneOffset;
159
- function getTimezoneOffset() {
160
- return timezoneOffset;
161
- }
162
- Time.getTimezoneOffset = getTimezoneOffset;
163
- function getDateNumber(date = /* @__PURE__ */ new Date(), offset) {
164
- if (typeof date === "number") date = new Date(date);
165
- if (offset === void 0) offset = timezoneOffset;
166
- return Math.floor((date.valueOf() / Time.minute - offset) / 1440);
167
- }
168
- Time.getDateNumber = getDateNumber;
169
- function fromDateNumber(value, offset) {
170
- const date = new Date(value * Time.day);
171
- if (offset === void 0) offset = timezoneOffset;
172
- return new Date(+date + offset * Time.minute);
173
- }
174
- Time.fromDateNumber = fromDateNumber;
175
- const numeric = /\d+(?:\.\d+)?/.source;
176
- const timeRegExp = new RegExp(`^${[
177
- "w(?:eek(?:s)?)?",
178
- "d(?:ay(?:s)?)?",
179
- "h(?:our(?:s)?)?",
180
- "m(?:in(?:ute)?(?:s)?)?",
181
- "s(?:ec(?:ond)?(?:s)?)?"
182
- ].map((unit) => `(${numeric}${unit})?`).join("")}$`);
183
- function parseTime(source) {
184
- const capture = timeRegExp.exec(source);
185
- if (!capture) return 0;
186
- return (parseFloat(capture[1]) * Time.week || 0) + (parseFloat(capture[2]) * Time.day || 0) + (parseFloat(capture[3]) * Time.hour || 0) + (parseFloat(capture[4]) * Time.minute || 0) + (parseFloat(capture[5]) * Time.second || 0);
187
- }
188
- Time.parseTime = parseTime;
189
- function parseDate(date) {
190
- const parsed = parseTime(date);
191
- if (parsed) date = Date.now() + parsed;
192
- else if (/^\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date}`;
193
- else if (/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date}`;
194
- return date ? new Date(date) : /* @__PURE__ */ new Date();
195
- }
196
- Time.parseDate = parseDate;
197
- function format(ms) {
198
- const abs = Math.abs(ms);
199
- if (abs >= Time.day - Time.hour / 2) return Math.round(ms / Time.day) + "d";
200
- else if (abs >= Time.hour - Time.minute / 2) return Math.round(ms / Time.hour) + "h";
201
- else if (abs >= Time.minute - Time.second / 2) return Math.round(ms / Time.minute) + "m";
202
- else if (abs >= Time.second) return Math.round(ms / Time.second) + "s";
203
- return ms + "ms";
204
- }
205
- Time.format = format;
206
- function toDigits(source, length = 2) {
207
- return source.toString().padStart(length, "0");
208
- }
209
- Time.toDigits = toDigits;
210
- function template(template, time = /* @__PURE__ */ new Date()) {
211
- return template.replace("yyyy", time.getFullYear().toString()).replace("yy", time.getFullYear().toString().slice(2)).replace("MM", toDigits(time.getMonth() + 1)).replace("dd", toDigits(time.getDate())).replace("hh", toDigits(time.getHours())).replace("mm", toDigits(time.getMinutes())).replace("ss", toDigits(time.getSeconds())).replace("SSS", toDigits(time.getMilliseconds(), 3));
212
- }
213
- Time.template = template;
214
- })(Time || (Time = {}));
215
- //#endregion
216
- //#region ../../../vendor/deepseek-harness/vendor/schemastery/lib/index.mjs
217
- const kSchema = Symbol.for("schemastery");
218
- const kValidationError = Symbol.for("ValidationError");
219
- globalThis.__schemastery_index__ ??= 0;
220
- globalThis.__schemastery_refs__ = void 0;
221
- var ValidationError = class extends TypeError {
222
- options;
223
- name = "ValidationError";
224
- constructor(message, options) {
225
- let prefix = "$";
226
- for (const segment of options.path || []) if (typeof segment === "string") prefix += "." + segment;
227
- else if (typeof segment === "number") prefix += "[" + segment + "]";
228
- else if (typeof segment === "symbol") prefix += `[Symbol(${segment.toString()})]`;
229
- if (prefix.startsWith(".")) prefix = prefix.slice(1);
230
- super((prefix === "$" ? "" : `${prefix} `) + message);
231
- this.options = options;
232
- }
233
- static is(error) {
234
- return !!error?.[kValidationError];
235
- }
236
- };
237
- Object.defineProperty(ValidationError.prototype, kValidationError, { value: true });
238
- const Schema = function(options) {
239
- const schema = function(data, options = {}) {
240
- return Schema.resolve(data, schema, options)[0];
241
- };
242
- if (options.refs) {
243
- const refs = mapValues(options.refs, (options) => new Schema(options));
244
- const getRef = (uid) => refs[uid];
245
- for (const key in refs) {
246
- const options = refs[key];
247
- options.sKey = getRef(options.sKey);
248
- options.inner = getRef(options.inner);
249
- options.list = options.list && options.list.map(getRef);
250
- options.dict = options.dict && mapValues(options.dict, getRef);
251
- }
252
- return refs[options.uid];
253
- }
254
- Object.assign(schema, options);
255
- if (typeof schema.callback === "string") try {
256
- schema.callback = new Function("return " + schema.callback)();
257
- } catch {}
258
- Object.defineProperty(schema, "uid", { value: globalThis.__schemastery_index__++ });
259
- Object.setPrototypeOf(schema, Schema.prototype);
260
- schema.meta ||= {};
261
- schema.toString = schema.toString.bind(schema);
262
- return schema;
263
- };
264
- Schema.prototype = Object.create(Function.prototype);
265
- Schema.prototype[kSchema] = true;
266
- Object.defineProperty(Schema.prototype, "~standard", { get() {
267
- return {
268
- version: 1,
269
- vendor: "schemastery",
270
- validate: (value) => {
271
- try {
272
- return { value: Schema.resolve(value, this, {})[0] };
273
- } catch (error) {
274
- if (ValidationError.is(error)) return { issues: [{
275
- message: error.message,
276
- path: error.options.path
277
- }] };
278
- throw error;
279
- }
280
- }
281
- };
282
- } });
283
- Schema.ValidationError = ValidationError;
284
- Schema.prototype.toJSON = function toJSON() {
285
- if (globalThis.__schemastery_refs__) {
286
- globalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));
287
- return this.uid;
288
- }
289
- globalThis.__schemastery_refs__ = { [this.uid]: { ...this } };
290
- globalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));
291
- const result = {
292
- uid: this.uid,
293
- refs: globalThis.__schemastery_refs__
294
- };
295
- globalThis.__schemastery_refs__ = void 0;
296
- return result;
297
- };
298
- Schema.prototype.set = function set(key, value) {
299
- this.dict[key] = value;
300
- return this;
301
- };
302
- Schema.prototype.push = function push(value) {
303
- this.list.push(value);
304
- return this;
305
- };
306
- function mergeDesc(original, messages) {
307
- const result = typeof original === "string" ? { "": original } : { ...original };
308
- for (const locale in messages) {
309
- const value = messages[locale];
310
- if (value?.$description || value?.$desc) result[locale] = value.$description || value.$desc;
311
- else if (typeof value === "string") result[locale] = value;
312
- }
313
- return result;
314
- }
315
- function getInner(value) {
316
- return value?.$value ?? value?.$inner;
317
- }
318
- function extractKeys(data) {
319
- return filterKeys(data ?? {}, (key) => !key.startsWith("$"));
320
- }
321
- Schema.prototype.i18n = function i18n(messages) {
322
- const schema = Schema(this);
323
- const desc = mergeDesc(schema.meta.description, messages);
324
- if (Object.keys(desc).length) schema.meta.description = desc;
325
- if (schema.dict) schema.dict = mapValues(schema.dict, (inner, key) => {
326
- return inner.i18n(mapValues(messages, (data) => getInner(data)?.[key] ?? data?.[key]));
327
- });
328
- if (schema.list) schema.list = schema.list.map((inner, index) => {
329
- return inner.i18n(mapValues(messages, (data = {}) => {
330
- if (Array.isArray(getInner(data))) return getInner(data)[index];
331
- if (Array.isArray(data)) return data[index];
332
- return extractKeys(data);
333
- }));
334
- });
335
- if (schema.inner) schema.inner = schema.inner.i18n(mapValues(messages, (data) => {
336
- if (getInner(data)) return getInner(data);
337
- return extractKeys(data);
338
- }));
339
- if (schema.sKey) schema.sKey = schema.sKey.i18n(mapValues(messages, (data) => data?.$key));
340
- return schema;
341
- };
342
- Schema.prototype.extra = function extra(key, value) {
343
- const schema = Schema(this);
344
- schema.meta = {
345
- ...schema.meta,
346
- [key]: value
347
- };
348
- return schema;
349
- };
350
- for (const key of [
351
- "required",
352
- "disabled",
353
- "collapse",
354
- "hidden",
355
- "loose"
356
- ]) Object.assign(Schema.prototype, { [key](value = true) {
357
- const schema = Schema(this);
358
- schema.meta = {
359
- ...schema.meta,
360
- [key]: value
361
- };
362
- return schema;
363
- } });
364
- Schema.prototype.deprecated = function deprecated() {
365
- const schema = Schema(this);
366
- schema.meta.badges ||= [];
367
- schema.meta.badges.push({
368
- text: "deprecated",
369
- type: "danger"
370
- });
371
- return schema;
372
- };
373
- Schema.prototype.experimental = function experimental() {
374
- const schema = Schema(this);
375
- schema.meta.badges ||= [];
376
- schema.meta.badges.push({
377
- text: "experimental",
378
- type: "warning"
379
- });
380
- return schema;
381
- };
382
- Schema.prototype.pattern = function pattern(regexp) {
383
- const schema = Schema(this);
384
- const pattern = pick(regexp, ["source", "flags"]);
385
- schema.meta = {
386
- ...schema.meta,
387
- pattern
388
- };
389
- return schema;
390
- };
391
- Schema.prototype.simplify = function simplify(value) {
392
- if (deepEqual(value, this.meta.default, this.type === "dict")) return null;
393
- if (isNullable(value)) return value;
394
- if (this.type === "object" || this.type === "dict") {
395
- const result = {};
396
- for (const key in value) {
397
- const item = (this.type === "object" ? this.dict[key] : this.inner)?.simplify(value[key]);
398
- if (this.type === "dict" || !isNullable(item)) result[key] = item;
399
- }
400
- if (deepEqual(result, this.meta.default, this.type === "dict")) return null;
401
- return result;
402
- } else if (this.type === "array" || this.type === "tuple") {
403
- const result = [];
404
- value.forEach((value, index) => {
405
- const schema = this.type === "array" ? this.inner : this.list[index];
406
- const item = schema ? schema.simplify(value) : value;
407
- result.push(item);
408
- });
409
- return result;
410
- } else if (this.type === "intersect") {
411
- const result = {};
412
- for (const item of this.list) Object.assign(result, item.simplify(value));
413
- return result;
414
- } else if (this.type === "union") for (const schema of this.list) try {
415
- Schema.resolve(value, schema, {});
416
- return schema.simplify(value);
417
- } catch {}
418
- return value;
419
- };
420
- Schema.prototype.toString = function toString(inline) {
421
- return formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;
422
- };
423
- Schema.prototype.role = function role(role, extra) {
424
- const schema = Schema(this);
425
- schema.meta = {
426
- ...schema.meta,
427
- role,
428
- extra
429
- };
430
- return schema;
431
- };
432
- for (const key of [
433
- "default",
434
- "link",
435
- "comment",
436
- "description",
437
- "max",
438
- "min",
439
- "step"
440
- ]) Object.assign(Schema.prototype, { [key](value) {
441
- const schema = Schema(this);
442
- schema.meta = {
443
- ...schema.meta,
444
- [key]: value
445
- };
446
- return schema;
447
- } });
448
- const resolvers = {};
449
- Schema.extend = function extend(type, resolve) {
450
- resolvers[type] = resolve;
451
- };
452
- Schema.resolve = function resolve(data, schema, options = {}, strict = false) {
453
- if (!schema) return [data];
454
- if (options.ignore?.(data, schema)) return [data];
455
- if (isNullable(data) && schema.type !== "lazy") {
456
- if (schema.meta.required) throw new ValidationError(`missing required value`, options);
457
- let current = schema;
458
- let fallback = schema.meta.default;
459
- while (current?.type === "intersect" && isNullable(fallback)) {
460
- current = current.list[0];
461
- fallback = current?.meta.default;
462
- }
463
- if (isNullable(fallback)) return [data];
464
- data = clone(fallback);
465
- }
466
- const callback = resolvers[schema.type];
467
- if (!callback) throw new ValidationError(`unsupported type "${schema.type}"`, options);
468
- try {
469
- return callback(data, schema, options, strict);
470
- } catch (error) {
471
- if (!schema.meta.loose) throw error;
472
- return [schema.meta.default];
473
- }
474
- };
475
- Schema.from = function from(source) {
476
- if (isNullable(source)) return Schema.any();
477
- else if ([
478
- "string",
479
- "number",
480
- "boolean"
481
- ].includes(typeof source)) return Schema.const(source).required();
482
- else if (source[kSchema]) return source;
483
- else if (typeof source === "function") switch (source) {
484
- case String: return Schema.string().required();
485
- case Number: return Schema.number().required();
486
- case Boolean: return Schema.boolean().required();
487
- case Function: return Schema.function().required();
488
- default: return Schema.is(source).required();
489
- }
490
- else throw new TypeError(`cannot infer schema from ${source}`);
491
- };
492
- Schema.lazy = function lazy(builder) {
493
- const toJSON = () => {
494
- if (!schema.inner[kSchema]) {
495
- schema.inner = schema.builder();
496
- schema.inner.meta = {
497
- ...schema.meta,
498
- ...schema.inner.meta
499
- };
500
- }
501
- return schema.inner.toJSON();
502
- };
503
- const schema = new Schema({
504
- type: "lazy",
505
- builder,
506
- inner: { toJSON }
507
- });
508
- return schema;
509
- };
510
- Schema.natural = function natural() {
511
- return Schema.number().step(1).min(0);
512
- };
513
- Schema.percent = function percent() {
514
- return Schema.number().step(.01).min(0).max(1).role("slider");
515
- };
516
- Schema.date = function date() {
517
- return Schema.union([Schema.is(Date), Schema.transform(Schema.string().role("datetime"), (value, options) => {
518
- const date = new Date(value);
519
- if (isNaN(+date)) throw new ValidationError(`invalid date "${value}"`, options);
520
- return date;
521
- }, true)]);
522
- };
523
- Schema.regExp = function regExp(flag = "") {
524
- return Schema.union([Schema.is(RegExp), Schema.transform(Schema.string().role("regexp", { flag }), (value, options) => {
525
- try {
526
- return new RegExp(value, flag);
527
- } catch (e) {
528
- throw new ValidationError(e.message, options);
529
- }
530
- }, true)]);
531
- };
532
- Schema.arrayBuffer = function arrayBuffer(encoding) {
533
- return Schema.union([
534
- Schema.is(ArrayBuffer),
535
- Schema.is(SharedArrayBuffer),
536
- Schema.transform(Schema.any(), (value, options) => {
537
- if (Binary.isSource(value)) return Binary.fromSource(value);
538
- throw new ValidationError(`expected ArrayBufferSource but got ${value}`, options);
539
- }, true),
540
- ...encoding ? [Schema.transform(Schema.string(), (value, options) => {
541
- try {
542
- return encoding === "base64" ? Binary.fromBase64(value) : Binary.fromHex(value);
543
- } catch (e) {
544
- throw new ValidationError(e.message, options);
545
- }
546
- }, true)] : []
547
- ]);
548
- };
549
- Schema.extend("lazy", (data, schema, options, strict) => {
550
- if (!schema.inner[kSchema]) {
551
- schema.inner = schema.builder();
552
- schema.inner.meta = {
553
- ...schema.meta,
554
- ...schema.inner.meta
555
- };
556
- }
557
- return Schema.resolve(data, schema.inner, options, strict);
558
- });
559
- Schema.extend("any", (data) => {
560
- return [data];
561
- });
562
- Schema.extend("never", (data, _, options) => {
563
- throw new ValidationError(`expected nullable but got ${data}`, options);
564
- });
565
- Schema.extend("const", (data, { value }, options) => {
566
- if (deepEqual(data, value)) return [value];
567
- throw new ValidationError(`expected ${value} but got ${data}`, options);
568
- });
569
- function checkWithinRange(data, meta, description, options, skipMin = false) {
570
- const { max = Infinity, min = -Infinity } = meta;
571
- if (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);
572
- if (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);
573
- }
574
- Schema.extend("string", (data, { meta }, options) => {
575
- if (typeof data !== "string") throw new ValidationError(`expected string but got ${data}`, options);
576
- if (meta.pattern) {
577
- const regexp = new RegExp(meta.pattern.source, meta.pattern.flags);
578
- if (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);
579
- }
580
- checkWithinRange(data.length, meta, "string length", options);
581
- return [data];
582
- });
583
- function decimalShift(data, digits) {
584
- const str = data.toString();
585
- if (str.includes("e")) return data * Math.pow(10, digits);
586
- const index = str.indexOf(".");
587
- if (index === -1) return data * Math.pow(10, digits);
588
- const frac = str.slice(index + 1);
589
- const integer = str.slice(0, index);
590
- if (frac.length <= digits) return +(integer + frac.padEnd(digits, "0"));
591
- return +(integer + frac.slice(0, digits) + "." + frac.slice(digits));
592
- }
593
- function isMultipleOf(data, min, step) {
594
- step = Math.abs(step);
595
- if (!/^\d+\.\d+$/.test(step.toString())) return (data - min) % step === 0;
596
- const index = step.toString().indexOf(".");
597
- const digits = step.toString().slice(index + 1).length;
598
- return Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;
599
- }
600
- Schema.extend("number", (data, { meta }, options) => {
601
- if (typeof data !== "number") throw new ValidationError(`expected number but got ${data}`, options);
602
- checkWithinRange(data, meta, "number", options);
603
- const { step } = meta;
604
- if (step && !isMultipleOf(data, meta.min ?? 0, step)) throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);
605
- return [data];
606
- });
607
- Schema.extend("boolean", (data, _, options) => {
608
- if (typeof data === "boolean") return [data];
609
- throw new ValidationError(`expected boolean but got ${data}`, options);
610
- });
611
- Schema.extend("bitset", (data, { bits, meta }, options) => {
612
- let value = 0, keys = [];
613
- if (typeof data === "number") {
614
- value = data;
615
- for (const key in bits) if (data & bits[key]) keys.push(key);
616
- } else if (Array.isArray(data)) {
617
- keys = data;
618
- for (const key of keys) {
619
- if (typeof key !== "string") throw new ValidationError(`expected string but got ${key}`, options);
620
- if (key in bits) value |= bits[key];
621
- }
622
- } else throw new ValidationError(`expected number or array but got ${data}`, options);
623
- if (value === meta.default) return [value];
624
- return [value, keys];
625
- });
626
- Schema.extend("function", (data, _, options) => {
627
- if (typeof data === "function") return [data];
628
- throw new ValidationError(`expected function but got ${data}`, options);
629
- });
630
- Schema.extend("is", (data, { constructor }, options) => {
631
- if (typeof constructor === "function") {
632
- if (data instanceof constructor) return [data];
633
- throw new ValidationError(`expected ${constructor.name} but got ${data}`, options);
634
- } else {
635
- if (isNullable(data)) throw new ValidationError(`expected ${constructor} but got ${data}`, options);
636
- let prototype = Object.getPrototypeOf(data);
637
- while (prototype) {
638
- if (prototype.constructor?.name === constructor) return [data];
639
- prototype = Object.getPrototypeOf(prototype);
640
- }
641
- throw new ValidationError(`expected ${constructor} but got ${data}`, options);
642
- }
643
- });
644
- function property(data, key, schema, options) {
645
- try {
646
- const [value, adapted] = Schema.resolve(data[key], schema, {
647
- ...options,
648
- path: [...options.path || [], key]
649
- });
650
- if (adapted !== void 0) data[key] = adapted;
651
- return value;
652
- } catch (e) {
653
- if (!options?.autofix) throw e;
654
- delete data[key];
655
- return schema.meta.default;
656
- }
657
- }
658
- Schema.extend("array", (data, { inner, meta }, options) => {
659
- if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
660
- checkWithinRange(data.length, meta, "array length", options, !isNullable(inner.meta.default));
661
- return [data.map((_, index) => property(data, index, inner, options))];
662
- });
663
- Schema.extend("dict", (data, { inner, sKey }, options, strict) => {
664
- if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
665
- const result = {};
666
- for (const key in data) {
667
- let rKey;
668
- try {
669
- rKey = Schema.resolve(key, sKey, options)[0];
670
- } catch (error) {
671
- if (strict) continue;
672
- throw error;
673
- }
674
- result[rKey] = property(data, key, inner, options);
675
- data[rKey] = data[key];
676
- if (key !== rKey) delete data[key];
677
- }
678
- return [result];
679
- });
680
- Schema.extend("tuple", (data, { list }, options, strict) => {
681
- if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
682
- const result = list.map((inner, index) => property(data, index, inner, options));
683
- if (strict) return [result];
684
- result.push(...data.slice(list.length));
685
- return [result];
686
- });
687
- function merge(result, data) {
688
- for (const key in data) {
689
- if (key in result) continue;
690
- result[key] = data[key];
691
- }
692
- }
693
- Schema.extend("object", (data, { dict }, options, strict) => {
694
- if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
695
- const result = {};
696
- for (const key in dict) {
697
- const value = property(data, key, dict[key], options);
698
- if (!isNullable(value) || key in data) result[key] = value;
699
- }
700
- if (!strict) merge(result, data);
701
- return [result];
702
- });
703
- Schema.extend("union", (data, { list, toString }, options, strict) => {
704
- const messages = [];
705
- for (const inner of list) try {
706
- return Schema.resolve(data, inner, options, strict);
707
- } catch (error) {
708
- messages.push(error);
709
- }
710
- throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
711
- });
712
- Schema.extend("intersect", (data, { list, toString }, options, strict) => {
713
- if (!list.length) return [data];
714
- let result;
715
- for (const inner of list) {
716
- const value = Schema.resolve(data, inner, options, true)[0];
717
- if (isNullable(value)) continue;
718
- if (isNullable(result)) result = value;
719
- else if (typeof result !== typeof value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
720
- else if (typeof value === "object") merge(result ??= {}, value);
721
- else if (result !== value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
722
- }
723
- if (!strict && isPlainObject(data)) merge(result, data);
724
- return [result];
725
- });
726
- Schema.extend("transform", (data, { inner, callback, preserve }, options) => {
727
- const [result, adapted = data] = Schema.resolve(data, inner, options, true);
728
- if (preserve) return [callback(result)];
729
- else return [callback(result), callback(adapted)];
730
- });
731
- const formatters = {};
732
- function defineMethod(name, keys, format) {
733
- formatters[name] = format;
734
- Object.assign(Schema, { [name](...args) {
735
- const schema = new Schema({ type: name });
736
- keys.forEach((key, index) => {
737
- switch (key) {
738
- case "sKey":
739
- schema.sKey = args[index] ?? Schema.string();
740
- break;
741
- case "inner":
742
- schema.inner = Schema.from(args[index]);
743
- break;
744
- case "list":
745
- schema.list = args[index].map(Schema.from);
746
- break;
747
- case "dict":
748
- schema.dict = mapValues(args[index], Schema.from);
749
- break;
750
- case "bits":
751
- schema.bits = {};
752
- for (const key in args[index]) {
753
- if (typeof args[index][key] !== "number") continue;
754
- schema.bits[key] = args[index][key];
755
- }
756
- break;
757
- case "callback": {
758
- const callback = schema.callback = args[index];
759
- callback["toJSON"] ||= () => callback.toString();
760
- break;
761
- }
762
- case "constructor": {
763
- const constructor = schema.constructor = args[index];
764
- if (typeof constructor === "function") constructor["toJSON"] ||= () => constructor["name"];
765
- break;
766
- }
767
- default: schema[key] = args[index];
768
- }
769
- });
770
- if (name === "object" || name === "dict") schema.meta.default = {};
771
- else if (name === "array" || name === "tuple") schema.meta.default = [];
772
- else if (name === "bitset") schema.meta.default = 0;
773
- return schema;
774
- } });
775
- }
776
- defineMethod("is", ["constructor"], ({ constructor }) => {
777
- if (typeof constructor === "function") return constructor.name;
778
- else return constructor;
779
- });
780
- defineMethod("any", [], () => "any");
781
- defineMethod("never", [], () => "never");
782
- defineMethod("const", ["value"], ({ value }) => typeof value === "string" ? JSON.stringify(value) : value);
783
- defineMethod("string", [], () => "string");
784
- defineMethod("number", [], () => "number");
785
- defineMethod("boolean", [], () => "boolean");
786
- defineMethod("bitset", ["bits"], () => "bitset");
787
- defineMethod("function", [], () => "function");
788
- defineMethod("array", ["inner"], ({ inner }) => `${inner.toString(true)}[]`);
789
- defineMethod("dict", ["inner", "sKey"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);
790
- defineMethod("tuple", ["list"], ({ list }) => `[${list.map((inner) => inner.toString()).join(", ")}]`);
791
- defineMethod("object", ["dict"], ({ dict }) => {
792
- if (Object.keys(dict).length === 0) return "{}";
793
- return `{ ${Object.entries(dict).map(([key, inner]) => {
794
- return `${key}${inner.meta.required ? "" : "?"}: ${inner.toString()}`;
795
- }).join(", ")} }`;
796
- });
797
- defineMethod("union", ["list"], ({ list }, inline) => {
798
- const result = list.map(({ toString: format }) => format()).join(" | ");
799
- return inline ? `(${result})` : result;
800
- });
801
- defineMethod("intersect", ["list"], ({ list }) => {
802
- return `${list.map((inner) => inner.toString(true)).join(" & ")}`;
803
- });
804
- defineMethod("transform", [
805
- "inner",
806
- "callback",
807
- "preserve"
808
- ], ({ inner }, isInner) => inner.toString(isInner));
809
- //#endregion
810
26
  //#region ../../../vendor/deepseek-harness/packages/core/scope/lib/index.js
811
27
  /**
812
28
  * Shared insertion-ordered storage and effect ownership for scope-aware registries.
@@ -1566,22 +782,22 @@ const DEFAULT_RETRYABLE_CODES = Object.freeze([
1566
782
  "TIMEOUT",
1567
783
  "TRANSPORT"
1568
784
  ]);
1569
- const backoffSchema = Schema.object({
1570
- initialDelayMs: Schema.number().max(MAX_TIMER_DELAY_MS).default(DEFAULT_INITIAL_DELAY_MS),
1571
- maxDelayMs: Schema.number().max(MAX_TIMER_DELAY_MS).default(DEFAULT_MAX_DELAY_MS),
1572
- jitterRatio: Schema.number().min(0).max(1).default(DEFAULT_JITTER_RATIO)
785
+ const backoffSchema = z.object({
786
+ initialDelayMs: z.number().max(MAX_TIMER_DELAY_MS).default(DEFAULT_INITIAL_DELAY_MS),
787
+ maxDelayMs: z.number().max(MAX_TIMER_DELAY_MS).default(DEFAULT_MAX_DELAY_MS),
788
+ jitterRatio: z.number().min(0).max(1).default(DEFAULT_JITTER_RATIO)
1573
789
  });
1574
- const normalPolicySchema = Schema.object({
1575
- mode: Schema.const("normal").required(),
1576
- maxRetries: Schema.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(DEFAULT_MAX_RETRIES),
1577
- retryableCodes: Schema.array(Schema.string()).default([...DEFAULT_RETRYABLE_CODES]),
790
+ const normalPolicySchema = z.object({
791
+ mode: z.const("normal").required(),
792
+ maxRetries: z.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(DEFAULT_MAX_RETRIES),
793
+ retryableCodes: z.array(z.string()).default([...DEFAULT_RETRYABLE_CODES]),
1578
794
  backoff: backoffSchema
1579
795
  });
1580
- const alwaysPolicySchema = Schema.object({
1581
- mode: Schema.const("always").required(),
796
+ const alwaysPolicySchema = z.object({
797
+ mode: z.const("always").required(),
1582
798
  backoff: backoffSchema
1583
799
  });
1584
- Schema.union([normalPolicySchema, alwaysPolicySchema]);
800
+ z.union([normalPolicySchema, alwaysPolicySchema]);
1585
801
  const NORMAL_POLICY_KEYS = /* @__PURE__ */ new Set([
1586
802
  "mode",
1587
803
  "maxRetries",
@@ -1684,7 +900,7 @@ function normalizeLlmFailure(value) {
1684
900
  const carried = ownFailureSnapshot(error);
1685
901
  if (carried !== void 0 && carried.code === ownErrorCode(error)) return carried;
1686
902
  return Object.freeze({
1687
- message: errorMessage$1(error),
903
+ message: errorMessage$2(error),
1688
904
  code: harnessErrorCode(error)
1689
905
  });
1690
906
  }
@@ -1740,7 +956,7 @@ function failureSnapshot(value) {
1740
956
  }
1741
957
  }
1742
958
  /** Read an SDK error message without letting an accessor replace the primary failure. */
1743
- function errorMessage$1(error) {
959
+ function errorMessage$2(error) {
1744
960
  try {
1745
961
  const message = error.message;
1746
962
  if (typeof message === "string" && message.length > 0) return message;
@@ -5159,7 +4375,7 @@ var ToolOutputError = class extends HarnessError {
5159
4375
  };
5160
4376
  /** Convert one projector exception into the canonical invalid-output failure. */
5161
4377
  function projectionError(toolName, projector, error) {
5162
- return new ToolOutputError(toolName, [`output.${projector} failed: ${errorMessage(error)}`]);
4378
+ return new ToolOutputError(toolName, [`output.${projector} failed: ${errorMessage$1(error)}`]);
5163
4379
  }
5164
4380
  /** Snapshot one projector result before later durable-result materialization. */
5165
4381
  function snapshotProjection(toolName, projector, candidate) {
@@ -5180,7 +4396,7 @@ function snapshotToolValue(toolName, candidate) {
5180
4396
  return detached;
5181
4397
  } catch (error) {
5182
4398
  if (error instanceof ToolOutputError) throw error;
5183
- throw new ToolOutputError(toolName, [`value snapshot failed: ${errorMessage(error)}`]);
4399
+ throw new ToolOutputError(toolName, [`value snapshot failed: ${errorMessage$1(error)}`]);
5184
4400
  }
5185
4401
  }
5186
4402
  /**
@@ -5189,7 +4405,7 @@ function snapshotToolValue(toolName, candidate) {
5189
4405
  * property (e.g. `throw { message: 'denied' }`) use it too; everything else
5190
4406
  * is stringified.
5191
4407
  */
5192
- function errorMessage(error) {
4408
+ function errorMessage$1(error) {
5193
4409
  try {
5194
4410
  if (error instanceof Error) return error.message;
5195
4411
  if (typeof error === "object" && error !== null && "message" in error && typeof error.message === "string") return error.message;
@@ -5263,13 +4479,13 @@ function resolveMaxParallelSubCalls(value) {
5263
4479
  */
5264
4480
  var ToolRuntime = class extends Service {
5265
4481
  static inject = ["systemPrompt"];
5266
- static Config = Schema.object({
5267
- mode: Schema.union([
4482
+ static Config = z.object({
4483
+ mode: z.union([
5268
4484
  "native",
5269
4485
  "ptc",
5270
4486
  "both"
5271
4487
  ]).default("native"),
5272
- maxParallelSubCalls: Schema.natural().min(1).default(10)
4488
+ maxParallelSubCalls: z.natural().min(1).default(10)
5273
4489
  });
5274
4490
  /** Internal staged view consumed by `dsh-agent-loop`'s parallel scheduler. */
5275
4491
  [TOOL_RUNTIME_SCHEDULER] = {
@@ -5674,7 +4890,7 @@ var ToolRuntime = class extends Service {
5674
4890
  try {
5675
4891
  return await this.ctx.waterfall(scopeTarget(this, dispatch.agent), "tools/ptc-dispatch-log", dispatch, () => Promise.resolve(dispatch.content));
5676
4892
  } catch (error) {
5677
- this.ctx.logger.warn(`tools: ptc-dispatch-log listener failed for ${dispatch.name}: ${errorMessage(error)}; logging the original settled content`);
4893
+ this.ctx.logger.warn(`tools: ptc-dispatch-log listener failed for ${dispatch.name}: ${errorMessage$1(error)}; logging the original settled content`);
5678
4894
  return dispatch.content;
5679
4895
  }
5680
4896
  }
@@ -5999,7 +5215,7 @@ var ToolRuntime = class extends Service {
5999
5215
  Object.freeze(exec);
6000
5216
  const { name: toolName, callId } = exec;
6001
5217
  const reportFailure = (error) => {
6002
- this.ctx.logger.warn(`tool "${toolName}" (${callId}): tools/result observer failed: ${errorMessage(error)}`);
5218
+ this.ctx.logger.warn(`tool "${toolName}" (${callId}): tools/result observer failed: ${errorMessage$1(error)}`);
6003
5219
  };
6004
5220
  const callbacks = this.ctx.events.dispatch("emit", [
6005
5221
  scopeTarget(this, exec.agent),
@@ -6203,7 +5419,7 @@ function createExecutionToken() {
6203
5419
  }
6204
5420
  function toolErrorResult(error) {
6205
5421
  const info = errorInfo(error);
6206
- const message = errorMessage(error);
5422
+ const message = errorMessage$1(error);
6207
5423
  return {
6208
5424
  content: [{
6209
5425
  type: "text",
@@ -6511,170 +5727,443 @@ async function apply(ctx, config) {
6511
5727
  await ctx.plugin(workspace_dependencies_exports, config);
6512
5728
  }
6513
5729
  //#endregion
6514
- //#region ../../../vendor/deepseek-harness/apps/desktop-host/src/update-tasks.ts
5730
+ //#region src/layout-fallback.ts
6515
5731
  /**
6516
- * Register update admission on the owning Host context.
6517
- * @param ctx - Booted Desktop profile context; disposal removes the request listener.
6518
- * @returns Task inspector whose lock refuses new API requests, drains admitted requests, and rechecks work.
5732
+ * 给收起的侧边栏补一个 rail——只在本该完全隐藏、又没有别处入口时。
5733
+ * @param doc - 页面文档(注入形态下就是 `document`)。
6519
5734
  */
6520
- function installDesktopUpdateTaskControl(ctx) {
6521
- let locked = false;
6522
- let lockGeneration = 0;
6523
- let stopped = false;
6524
- ctx.effect(() => () => {
6525
- stopped = true;
5735
+ function applySidebarRailFallback(doc) {
5736
+ const sync = () => {
5737
+ if (doc.documentElement.dataset.platform !== "darwin") return;
5738
+ const frame = doc.querySelector("[data-sidebar-collapsed]");
5739
+ if (frame === null) return;
5740
+ if (doc.querySelector("[data-conversation-header-leading] button") !== null) return;
5741
+ const style = frame.getAttribute("style");
5742
+ if (style === null) return;
5743
+ const hidden = /grid-template-columns:\s*0px/u;
5744
+ if (!hidden.test(style)) return;
5745
+ frame.setAttribute("style", style.replace(hidden, "grid-template-columns: 56px"));
5746
+ };
5747
+ new MutationObserver(sync).observe(doc.documentElement, {
5748
+ subtree: true,
5749
+ childList: true,
5750
+ attributes: true,
5751
+ attributeFilter: [
5752
+ "style",
5753
+ "data-sidebar-collapsed",
5754
+ "data-platform"
5755
+ ]
6526
5756
  });
6527
- const pendingRequests = /* @__PURE__ */ new Set();
6528
- ctx.on("connection/request", async (_request, response, next) => {
6529
- if (locked) {
6530
- response.writeHead(503);
5757
+ sync();
5758
+ }
5759
+ /** 注入 index 的兜底行:函数源码即脚本,页面加载后立即可用。 */
5760
+ const DESKTOP_LAYOUT_FALLBACK_SCRIPT = `(${applySidebarRailFallback.toString()})(document)`;
5761
+ //#endregion
5762
+ //#region src/transport.ts
5763
+ /**
5764
+ * 桌面形态的传输接管:把 Web 应用的浏览器装配换成「宿主内直连」。
5765
+ *
5766
+ * 两件事:一是让 `connection` 的浏览器认证在桌面下直接放行(页面由壳独占,没有网络入口);
5767
+ * 二是把客户端的 transport 行注入 index,并注册它访问的 `/.dsh/remote-stream`(NDJSON)。
5768
+ */
5769
+ /** 注入 index 的 transport 行:声明页面拥有 Host,并给出 Gateway 流载体。 */
5770
+ const DESKTOP_TRANSPORT_SCRIPT = `globalThis.__DSH_TRANSPORT__={
5771
+ _desktop:true,
5772
+ ownsHost:true,
5773
+ async *openStream(endpoint,payload,signal){
5774
+ console.info('[dsh-desktop] openStream',endpoint)
5775
+ const carrier=globalThis.__DSH_DESKTOP_STREAM__
5776
+ if(carrier===undefined){
5777
+ console.error('[dsh-desktop] stream carrier missing for',endpoint)
5778
+ throw new Error('desktop stream carrier is unavailable')
5779
+ }
5780
+ const queue=[]
5781
+ let buffer=''
5782
+ let ended=false
5783
+ let failure
5784
+ let wake
5785
+ const notify=()=>{const pending=wake;wake=undefined;if(pending)pending()}
5786
+ const append=(text)=>{
5787
+ buffer+=text
5788
+ let at
5789
+ while((at=buffer.indexOf('\\n'))!==-1){
5790
+ const line=buffer.slice(0,at)
5791
+ buffer=buffer.slice(at+1)
5792
+ if(line!=='')queue.push(JSON.parse(line))
5793
+ }
5794
+ notify()
5795
+ }
5796
+ const cancel=carrier.open(endpoint,payload,{
5797
+ chunk(text){append(text)},
5798
+ end(){
5799
+ if(buffer!==''){queue.push(JSON.parse(buffer));buffer=''}
5800
+ ended=true
5801
+ notify()
5802
+ },
5803
+ fail(message){failure=new Error(message);ended=true;notify()},
5804
+ })
5805
+ const onAbort=()=>{cancel()}
5806
+ signal.addEventListener('abort',onAbort,{once:true})
5807
+ try{
5808
+ for(;;){
5809
+ while(queue.length>0)yield queue.shift()
5810
+ if(failure!==undefined)throw failure
5811
+ if(ended)return
5812
+ await new Promise(resolve=>{wake=resolve})
5813
+ }
5814
+ }finally{
5815
+ signal.removeEventListener('abort',onAbort)
5816
+ }
5817
+ }
5818
+ }
5819
+ console.info('[dsh-desktop] transport installed',Object.keys(globalThis.__DSH_TRANSPORT__))`;
5820
+ /**
5821
+ * 桌面形态下放行 `connection` 的两处浏览器认证:`requestRejection`(`/api` 路由与
5822
+ * 各插件 handler 的自查)与 `authorizeIndex`(`frontend-static` 的 index 渲染)。
5823
+ *
5824
+ * 页面由壳独占、没有网络入口,认证没有对象;这里直接改写服务实例的方法。
5825
+ */
5826
+ function takeOverDesktopAuthentication(ctx) {
5827
+ const connection = ctx.get("connection");
5828
+ if (connection === void 0) throw new Error("dsh desktop: the composition did not provide the connection service");
5829
+ if (typeof connection.requestRejection !== "function" || typeof connection.authorizeIndex !== "function") throw new Error("dsh desktop: the connection service no longer exposes requestRejection / authorizeIndex; desktop authentication takeover needs an update");
5830
+ connection.requestRejection = () => void 0;
5831
+ connection.authorizeIndex = () => true;
5832
+ }
5833
+ function isRecord(value) {
5834
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5835
+ }
5836
+ /** 读请求体;管道上若迟迟不结束就放弃剩余体(桌面流只有 `$events` 一种,payload 固定)。 */
5837
+ async function readJsonBody(request, timeoutMs = 500) {
5838
+ const chunks = [];
5839
+ let timer;
5840
+ await Promise.race([(async () => {
5841
+ for await (const chunk of request) chunks.push(Buffer$1.from(chunk));
5842
+ })(), new Promise((resolve) => {
5843
+ timer = setTimeout(resolve, timeoutMs);
5844
+ timer.unref();
5845
+ })]);
5846
+ if (timer !== void 0) clearTimeout(timer);
5847
+ request.destroy?.();
5848
+ return chunks.length === 0 ? void 0 : JSON.parse(Buffer$1.concat(chunks).toString("utf8"));
5849
+ }
5850
+ function reportStreamFailure(subject, detail) {
5851
+ console.error(`[dsh-desktop] ${subject}: ${errorText(detail)}`);
5852
+ }
5853
+ function errorText(value) {
5854
+ return value instanceof Error ? value.stack ?? value.message : String(value);
5855
+ }
5856
+ function streamHandler(ctx) {
5857
+ return async (request, response) => {
5858
+ if (request.method !== "POST") {
5859
+ response.writeHead(405);
6531
5860
  response.end();
6532
5861
  return;
6533
5862
  }
6534
- const finished = Promise.withResolvers();
6535
- pendingRequests.add(finished.promise);
5863
+ const gateway = ctx.get("typertGateway");
5864
+ if (gateway === void 0) {
5865
+ reportStreamFailure("stream failed", "typertGateway service is missing");
5866
+ response.writeHead(503);
5867
+ response.end("gateway unavailable");
5868
+ return;
5869
+ }
5870
+ let body;
6536
5871
  try {
6537
- await next();
6538
- } finally {
6539
- pendingRequests.delete(finished.promise);
6540
- finished.resolve();
5872
+ body = await readJsonBody(request);
5873
+ } catch (error) {
5874
+ reportStreamFailure("stream body is not JSON", error);
5875
+ response.writeHead(400);
5876
+ response.end("body is not JSON");
5877
+ return;
6541
5878
  }
6542
- });
6543
- return async (action) => {
6544
- if (stopped) throw new Error("desktop update: Host is stopping");
6545
- if (action === "unlock") {
6546
- locked = false;
6547
- lockGeneration++;
5879
+ const endpointFromQuery = new URL(request.url ?? "/", "http://127.0.0.1").searchParams.get("endpoint");
5880
+ if (!isRecord(body) && endpointFromQuery === null) {
5881
+ reportStreamFailure("empty stream request", String(request.url));
5882
+ response.writeHead(400);
5883
+ response.end("invalid stream request");
5884
+ return;
5885
+ }
5886
+ if (!isRecord(body)) body = {
5887
+ endpoint: endpointFromQuery,
5888
+ payload: { args: {} }
5889
+ };
5890
+ if (typeof body.endpoint !== "string") {
5891
+ reportStreamFailure("invalid stream request", JSON.stringify(body).slice(0, 200));
5892
+ response.writeHead(400);
5893
+ response.end("invalid stream request");
5894
+ return;
6548
5895
  }
6549
- const agents = ctx.get("agents");
6550
- const jobs = ctx.get("jobs");
6551
- if (agents === void 0 || jobs === void 0) throw new Error("desktop update: task services are unavailable");
6552
- if (action === "lock") {
6553
- locked = true;
6554
- const generation = ++lockGeneration;
6555
- await Promise.all(pendingRequests);
6556
- if (stopped) throw new Error("desktop update: Host is stopping");
6557
- if (generation !== lockGeneration) throw new Error("desktop update: admission lock was superseded");
5896
+ const abort = new AbortController();
5897
+ const cancel = () => {
5898
+ abort.abort();
5899
+ };
5900
+ request.once("aborted", cancel);
5901
+ response.once("close", cancel);
5902
+ try {
5903
+ console.error(`[dsh-desktop] stream opening ${body.endpoint}`);
5904
+ const values = await gateway.wireStream.open(body.endpoint, body.payload, abort.signal);
5905
+ console.error(`[dsh-desktop] stream opened ${body.endpoint}`);
5906
+ response.writeHead(200, {
5907
+ "content-type": "application/x-ndjson",
5908
+ "cache-control": "no-store"
5909
+ });
5910
+ for await (const value of values) response.write(`${JSON.stringify(value)}\n`);
5911
+ response.end();
5912
+ } catch (error) {
5913
+ reportStreamFailure(`stream ${body.endpoint} failed`, error);
5914
+ if (response.headersSent) {
5915
+ response.destroy(error instanceof Error ? error : new Error(String(error)));
5916
+ return;
5917
+ }
5918
+ response.writeHead(502);
5919
+ response.end(error instanceof Error ? error.message : String(error));
6558
5920
  }
6559
- const liveAgents = agents.list();
6560
- return liveAgents.some((agent) => agent.status === "running" || agent.inbox.nextTurn.length > 0 || agent.inbox.nextStep.length > 0) || [void 0, ...liveAgents].some((agent) => jobs.list(agent).some((job) => job.status === "running" || job.status === "stopping"));
6561
5921
  };
6562
5922
  }
5923
+ /** 注入 transport 行并注册 Gateway 流路由;随插件 fiber 一起撤销。 */
5924
+ function installDesktopTransport(ctx) {
5925
+ ctx.on("webserver/index-inject", (table) => {
5926
+ table.push({
5927
+ kind: "script",
5928
+ placement: "head",
5929
+ text: DESKTOP_TRANSPORT_SCRIPT
5930
+ });
5931
+ table.push({
5932
+ kind: "script",
5933
+ placement: "head",
5934
+ text: DESKTOP_LAYOUT_FALLBACK_SCRIPT
5935
+ });
5936
+ });
5937
+ ctx.effect(() => ctx.webServer.register({
5938
+ kind: "exact",
5939
+ path: DESKTOP_STREAM_PATH,
5940
+ handler: streamHandler(ctx)
5941
+ }), "dsh-desktop: remote stream route");
5942
+ }
6563
5943
  //#endregion
6564
5944
  //#region src/index.ts
6565
5945
  /**
6566
- * Launch the Desktop profile through the Web application and report its URL to Electron.
5946
+ * 桌面部署里的 host 进程入口:按 `desktop` profile 装配 Web 应用,并把请求经字节管道
5947
+ * (FD 3/4)交给宿主内的无端口 `webServer`。
6567
5948
  *
6568
- * Upstream `apps/desktop-host/src/index.ts` with three local adaptations: the Office composition comes
6569
- * from `./office.ts` (no office skills), `update-tasks` is imported straight from upstream, and
6570
- * `process.disconnect` is called optionally for this repository's type face. Every other line follows
6571
- * upstream so the argv / IPC contract stays theirs; `tsdown.config.ts` builds this to
6572
- * `lib/index.js`, the path `@morlay/dsh-desktopify` copies into a deployment (and starts in dev
6573
- * mode) — deployments therefore boot this composition instead of the upstream artifact.
5949
+ * argv:`[runtimeDir, projectDir, primaryRuntime, profileResolution, pnpmEntry?, nodeBin?]`;
5950
+ * IPC:`ready` / `fatal`,另收 `shutdown`。
6574
5951
  */
5952
+ const DESKTOP_PATCH = fileURLToPath(new URL("../config/desktop.cordis.patch.yml", import.meta.url));
5953
+ function errorMessage(error) {
5954
+ return error instanceof Error ? error.message : String(error);
5955
+ }
6575
5956
  async function main() {
6576
5957
  const runtimeDir = process.argv[2];
6577
5958
  const projectDir = process.argv[3];
5959
+ if (runtimeDir === void 0 || projectDir === void 0 || process.send === void 0) throw new Error("dsh desktop: expected runtime and profile directories, byte pipes, and a Node IPC channel");
5960
+ const primaryRuntime = process.argv[4] ?? join(runtimeDir, "..", "runtime", "primary-runtime");
5961
+ const profileResolution = process.argv[5] === "runtime" ? "runtime" : "link";
5962
+ const pnpmEntry = process.argv[6];
5963
+ const nodeBin = process.argv[7];
5964
+ const requestPipe = createReadStream("", {
5965
+ fd: 3,
5966
+ autoClose: false
5967
+ });
5968
+ const responsePipe = createWriteStream("", {
5969
+ fd: 4,
5970
+ autoClose: false
5971
+ });
5972
+ let responseTail = Promise.resolve();
5973
+ let closing = false;
5974
+ responsePipe.on("error", (error) => {
5975
+ if (!closing) {
5976
+ console.error(error);
5977
+ process.exitCode = 1;
5978
+ }
5979
+ });
5980
+ const writeResponse = (frame) => {
5981
+ if (closing || responsePipe.destroyed) return Promise.resolve();
5982
+ const write = responseTail.then(async () => {
5983
+ if (closing || responsePipe.destroyed) return;
5984
+ if (!responsePipe.write(frame)) await once(responsePipe, "drain");
5985
+ });
5986
+ responseTail = write.catch(() => void 0);
5987
+ return write;
5988
+ };
5989
+ const send = (event) => {
5990
+ if (process.send === void 0 || !process.connected) return;
5991
+ try {
5992
+ process.send(event);
5993
+ } catch (error) {
5994
+ if (error.code !== "ERR_IPC_CHANNEL_CLOSED") throw error;
5995
+ }
5996
+ };
6578
5997
  const installAnchor = join(runtimeDir, "node_modules", "@deepseek-ai", "dsh", "package.json");
6579
5998
  const profile = loadProfileDirectory("dsh", projectDir, installAnchor);
6580
5999
  const application = runProfile({
6581
6000
  environment: loadLayeredEnv("dsh"),
6582
6001
  profile: "desktop",
6583
- resolutionMode: process.argv[5] === "runtime" ? "runtime" : "link",
6002
+ resolutionMode: profileResolution,
6584
6003
  resolvedProfile: {
6585
6004
  profile,
6586
6005
  installAnchor
6587
6006
  },
6588
- patchFiles: [],
6589
- args: [
6590
- "--no-open",
6591
- "--port",
6592
- "19387"
6593
- ],
6594
- ...process.argv[6] === void 0 ? {} : { packageManager: {
6007
+ patchFiles: [DESKTOP_PATCH],
6008
+ args: ["--no-open"],
6009
+ ...pnpmEntry === void 0 ? {} : { packageManager: {
6595
6010
  command: process.execPath,
6596
- args: ["--expose-internals", process.argv[6]],
6011
+ args: ["--expose-internals", pnpmEntry],
6597
6012
  env: {
6598
6013
  ELECTRON_RUN_AS_NODE: "1",
6599
6014
  DSH_DESKTOP_NODE_EXECUTABLE: process.execPath,
6600
- PATH: `${process.argv[7] ?? ""}${delimiter}${process.env.PATH ?? ""}`
6015
+ PATH: `${nodeBin ?? ""}${nodeBin === void 0 ? "" : ":"}${process.env.PATH ?? ""}`
6601
6016
  }
6602
6017
  } }
6603
6018
  });
6019
+ const { ctx } = await application;
6020
+ takeOverDesktopAuthentication(ctx);
6021
+ installDesktopTransport(ctx);
6022
+ await ctx.plugin(office_exports, {
6023
+ source: primaryRuntime,
6024
+ root: join(resolveDshHome(), "dsh-runtimes", "dsh-primary-runtime")
6025
+ });
6026
+ const webServer = ctx.get("webServer");
6027
+ const pending = /* @__PURE__ */ new Map();
6028
+ const runs = /* @__PURE__ */ new Set();
6029
+ const decoder = new DesktopHostRequestDecoder();
6030
+ let lastStreamId = 0;
6604
6031
  let stopping;
6605
- const control = {};
6606
- const send = (message) => new Promise((resolve, reject) => {
6607
- if (!process.connected || process.send === void 0) {
6608
- resolve();
6032
+ const dispatch = async (streamId, request, entry) => {
6033
+ try {
6034
+ const response = await webServer.dispatch(request);
6035
+ await writeResponse(encodeDesktopResponseStart(streamId, {
6036
+ status: response.status,
6037
+ headers: [...response.headers.entries()],
6038
+ hasBody: response.body !== null
6039
+ }));
6040
+ if (response.body !== null) for await (const chunk of response.body) {
6041
+ const bytes = Buffer.from(chunk);
6042
+ for (let offset = 0; offset < bytes.byteLength; offset += DESKTOP_PIPE_CHUNK_BYTES) {
6043
+ if (!pending.has(streamId)) return;
6044
+ await writeResponse(encodeDesktopResponseData(streamId, bytes.subarray(offset, offset + DESKTOP_PIPE_CHUNK_BYTES)));
6045
+ }
6046
+ }
6047
+ await writeResponse(encodeDesktopResponseEnd(streamId));
6048
+ } catch (error) {
6049
+ if (!entry.abort.signal.aborted) await writeResponse(encodeDesktopResponseError(streamId, errorMessage(error))).catch(() => {});
6050
+ } finally {
6051
+ pending.delete(streamId);
6052
+ }
6053
+ };
6054
+ const handleFrame = (frame) => {
6055
+ if (frame.type === "start") {
6056
+ if (frame.streamId <= lastStreamId) throw new Error(`dsh desktop: request stream ${String(frame.streamId)} is not in order`);
6057
+ lastStreamId = frame.streamId;
6058
+ const entry = { abort: new AbortController() };
6059
+ const streamId = frame.streamId;
6060
+ const body = frame.hasBody ? new ReadableStream({
6061
+ start: (controller) => {
6062
+ entry.body = controller;
6063
+ },
6064
+ cancel: () => {
6065
+ entry.abort.abort();
6066
+ }
6067
+ }) : void 0;
6068
+ pending.set(streamId, entry);
6069
+ const request = new Request(frame.url, {
6070
+ method: frame.method,
6071
+ headers: frame.headers,
6072
+ signal: entry.abort.signal,
6073
+ ...body === void 0 ? {} : {
6074
+ body,
6075
+ duplex: "half"
6076
+ }
6077
+ });
6078
+ const run = dispatch(streamId, request, entry).catch((error) => {
6079
+ ctx.logger.warn(error instanceof Error ? error : new Error(errorMessage(error)));
6080
+ });
6081
+ runs.add(run);
6082
+ run.finally(() => runs.delete(run));
6609
6083
  return;
6610
6084
  }
6611
- process.send(message, (error) => {
6612
- if (error === null) resolve();
6613
- else reject(error);
6085
+ const entry = pending.get(frame.streamId);
6086
+ if (entry === void 0) return;
6087
+ switch (frame.type) {
6088
+ case "data":
6089
+ entry.body?.enqueue(frame.data);
6090
+ return;
6091
+ case "end":
6092
+ entry.body?.close();
6093
+ return;
6094
+ case "cancel":
6095
+ entry.abort.abort();
6096
+ return;
6097
+ default: return;
6098
+ }
6099
+ };
6100
+ const stop = (exitCode = 0) => {
6101
+ stopping ??= (async () => {
6102
+ closing = true;
6103
+ requestPipe.pause();
6104
+ requestPipe.destroy();
6105
+ for (const entry of pending.values()) entry.abort.abort();
6106
+ pending.clear();
6107
+ await (await application.catch(() => void 0))?.shutdown.shutdown(exitCode);
6108
+ await Promise.allSettled(runs);
6109
+ await responseTail.catch(() => void 0);
6110
+ if (!responsePipe.destroyed) responsePipe.destroy();
6111
+ if (process.connected) process.disconnect?.();
6112
+ process.exitCode = exitCode;
6113
+ })();
6114
+ return stopping;
6115
+ };
6116
+ requestPipe.on("data", (chunk) => {
6117
+ let frames;
6118
+ try {
6119
+ frames = decoder.push(chunk);
6120
+ for (const frame of frames) handleFrame(frame);
6121
+ } catch (error) {
6122
+ send({
6123
+ type: "fatal",
6124
+ message: errorMessage(error)
6125
+ });
6126
+ stop(1);
6127
+ }
6128
+ });
6129
+ requestPipe.once("error", (error) => {
6130
+ send({
6131
+ type: "fatal",
6132
+ message: errorMessage(error)
6614
6133
  });
6134
+ stop(1);
6615
6135
  });
6616
- const stop = () => stopping ??= (async () => {
6617
- await (await application.catch(() => void 0))?.shutdown.shutdown(0);
6618
- await send({ type: "shutdown-complete" });
6619
- if (process.connected) process.disconnect?.();
6620
- })();
6621
- process.on("message", (message) => {
6622
- if (typeof message !== "object" || message === null || !("type" in message)) return;
6623
- if (message.type === "shutdown") {
6624
- stop();
6625
- return;
6136
+ requestPipe.once("end", () => {
6137
+ try {
6138
+ decoder.finish();
6139
+ } catch (error) {
6140
+ send({
6141
+ type: "fatal",
6142
+ message: errorMessage(error)
6143
+ });
6144
+ stop(1);
6626
6145
  }
6627
- if (message.type !== "update-tasks" || !("requestId" in message) || !Number.isSafeInteger(message.requestId) || !("action" in message) || ![
6628
- "inspect",
6629
- "lock",
6630
- "unlock"
6631
- ].includes(String(message.action))) return;
6632
- (async () => {
6633
- try {
6634
- if (stopping !== void 0 || control.updateTasks === void 0) throw new Error("desktop update: Host is unavailable");
6635
- const active = await control.updateTasks(message.action);
6636
- await send({
6637
- type: "update-tasks",
6638
- requestId: message.requestId,
6639
- active
6640
- });
6641
- } catch (error) {
6642
- await send({
6643
- type: "update-tasks",
6644
- requestId: message.requestId,
6645
- active: true,
6646
- error: error instanceof Error ? error.message : String(error)
6647
- });
6648
- }
6649
- })().catch((error) => {
6650
- console.error(error);
6651
- });
6146
+ });
6147
+ process.on("message", (message) => {
6148
+ if (isDesktopHostCommand(message)) stop();
6652
6149
  });
6653
6150
  process.once("disconnect", () => {
6654
6151
  stop();
6655
6152
  });
6656
- const { ctx } = await application;
6657
- control.updateTasks = installDesktopUpdateTaskControl(ctx);
6658
- await ctx.plugin(office_exports, {
6659
- source: process.argv[4] ?? join(runtimeDir, "..", "runtime", "primary-runtime"),
6660
- root: join(resolveDshHome(), "dsh-runtimes", "dsh-primary-runtime")
6661
- });
6662
- const url = ctx.connection.authenticatedUrl(`http://127.0.0.1:${String(ctx.webServer.port)}`);
6663
- if (process.connected) process.send?.({
6153
+ const gateway = ctx.get("typertGateway");
6154
+ console.error(`[dsh-desktop] transport ready: webServer=${webServer.constructor.name} gateway=${gateway === void 0 ? "missing" : "present"} streamRoute=${DESKTOP_STREAM_PATH}`);
6155
+ send({
6664
6156
  type: "ready",
6665
- url,
6666
- injections: ctx.webServer.collectIndexInjections()
6667
- }, (error) => {
6668
- if (error !== null) console.error(error);
6157
+ protocolVersion: 1
6669
6158
  });
6670
6159
  }
6671
6160
  if (import.meta.main) main().catch((error) => {
6672
- const message = error instanceof Error ? error.message : String(error);
6673
- if (process.connected) process.send?.({
6161
+ const message = errorMessage(error);
6162
+ if (process.send !== void 0 && process.connected) process.send({
6674
6163
  type: "fatal",
6675
6164
  message
6676
- }, (error) => {
6677
- if (error !== null) console.error(error);
6165
+ }, (sendError) => {
6166
+ if (sendError !== null) console.error(sendError);
6678
6167
  });
6679
6168
  console.error(error);
6680
6169
  process.exitCode = 1;