@dungsil/dsh-plugin-ui-forge-pulls 0.0.0-stage → 0.2.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/dist/index.js ADDED
@@ -0,0 +1,1922 @@
1
+ import { Session, SessionId } from "@deepseek-ai/dsh-session";
2
+ import { clientRequestSchema } from "@deepseek-ai/dsh-client-connection";
3
+ // ../../node_modules/.pnpm/@deepseek-ai+cosmokit@1.9.0/node_modules/@deepseek-ai/cosmokit/lib/index.js
4
+ /** Return true when a value is `null` or `undefined`. */
5
+ function isNullable(value) {
6
+ return value === null || value === void 0;
7
+ }
8
+ /** Return true for non-array object values. */
9
+ function isPlainObject(data) {
10
+ return data && typeof data === "object" && !Array.isArray(data);
11
+ }
12
+ /** Filter object entries and return a new object. */
13
+ function filterKeys(object, filter) {
14
+ return Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)));
15
+ }
16
+ /** Map object values while preserving the original key set. */
17
+ function mapValues(object, transform) {
18
+ return Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));
19
+ }
20
+ /** Pick selected keys from an object, optionally including `undefined` values. */
21
+ function pick(source, keys, forced) {
22
+ if (!keys) return { ...source };
23
+ const result = {};
24
+ for (const key of keys) if (forced || source[key] !== void 0) result[key] = source[key];
25
+ return result;
26
+ }
27
+ /** Shared config references used by schema validators and plugin runtimes. */
28
+ const write = Symbol.for("cosmokit.volatile.write");
29
+ function snapshot(value, ancestors = /* @__PURE__ */ new Set()) {
30
+ if (typeof value === "function") throw new TypeError("volatile config cannot contain functions");
31
+ if (value === null || typeof value !== "object") return value;
32
+ if (ancestors.has(value)) throw new TypeError("volatile config cannot contain cycles");
33
+ ancestors.add(value);
34
+ try {
35
+ if (Array.isArray(value)) return Object.freeze(value.map((item) => snapshot(item, ancestors)));
36
+ if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new TypeError("volatile config objects must be plain objects or arrays");
37
+ return Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, snapshot(item, ancestors)])));
38
+ } finally {
39
+ ancestors.delete(value);
40
+ }
41
+ }
42
+ /**
43
+ * Create a detached reference containing an immutable copy of the supplied data.
44
+ * @param value - validated config data; class instances and functions are unsupported.
45
+ * @returns a reference whose value is updated only by its owning runtime.
46
+ */
47
+ function createVolatile(value) {
48
+ let current = snapshot(value);
49
+ return Object.freeze({
50
+ get: () => current,
51
+ [write]: (value) => {
52
+ current = value;
53
+ }
54
+ });
55
+ }
56
+ /**
57
+ * Identify references across ESM/CJS copies of the shared library.
58
+ * @param value - a parsed config value.
59
+ * @returns whether the value implements the shared reference protocol.
60
+ */
61
+ function isVolatile(value) {
62
+ return typeof value === "object" && value !== null && write in value;
63
+ }
64
+ /** Test values using `instanceof` with a `toStringTag` fallback. */
65
+ function is(type, value) {
66
+ if (arguments.length === 1) return (value) => is(type, value);
67
+ return type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;
68
+ }
69
+ function isArrayBufferLike(value) {
70
+ return is("ArrayBuffer", value) || is("SharedArrayBuffer", value);
71
+ }
72
+ function isArrayBufferSource(value) {
73
+ return isArrayBufferLike(value) || ArrayBuffer.isView(value);
74
+ }
75
+ /** Binary source detection and base64/hex conversion helpers. */
76
+ var Binary;
77
+ (function(Binary) {
78
+ Binary.is = isArrayBufferLike;
79
+ Binary.isSource = isArrayBufferSource;
80
+ function fromSource(source) {
81
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
82
+ else return source;
83
+ }
84
+ Binary.fromSource = fromSource;
85
+ function toBase64(source) {
86
+ source = fromSource(source);
87
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("base64");
88
+ let binary = "";
89
+ const bytes = new Uint8Array(source);
90
+ for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
91
+ return btoa(binary);
92
+ }
93
+ Binary.toBase64 = toBase64;
94
+ function fromBase64(source) {
95
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "base64"));
96
+ return Uint8Array.from(atob(source), (c) => c.charCodeAt(0));
97
+ }
98
+ Binary.fromBase64 = fromBase64;
99
+ function toHex(source) {
100
+ source = fromSource(source);
101
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("hex");
102
+ return Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, "0")).join("");
103
+ }
104
+ Binary.toHex = toHex;
105
+ function fromHex(source) {
106
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "hex"));
107
+ const hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);
108
+ const buffer = [];
109
+ for (let i = 0; i < hex.length; i += 2) buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));
110
+ return Uint8Array.from(buffer).buffer;
111
+ }
112
+ Binary.fromHex = fromHex;
113
+ })(Binary || (Binary = {}));
114
+ Binary.fromBase64;
115
+ Binary.toBase64;
116
+ Binary.fromHex;
117
+ Binary.toHex;
118
+ /** Deep-clone common JavaScript values while preserving prototypes and cycles. */
119
+ function clone(source, refs = /* @__PURE__ */ new Map()) {
120
+ if (!source || typeof source !== "object") return source;
121
+ if (is("Date", source)) return new Date(source.valueOf());
122
+ if (is("RegExp", source)) return new RegExp(source.source, source.flags);
123
+ if (isArrayBufferLike(source)) return source.slice(0);
124
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
125
+ const cached = refs.get(source);
126
+ if (cached) return cached;
127
+ if (Array.isArray(source)) {
128
+ const result = [];
129
+ refs.set(source, result);
130
+ source.forEach((value, index) => {
131
+ result[index] = Reflect.apply(clone, null, [value, refs]);
132
+ });
133
+ return result;
134
+ }
135
+ const result = Object.create(Object.getPrototypeOf(source));
136
+ refs.set(source, result);
137
+ for (const key of Reflect.ownKeys(source)) {
138
+ const descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) };
139
+ if ("value" in descriptor) descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs]);
140
+ Reflect.defineProperty(result, key, descriptor);
141
+ }
142
+ return result;
143
+ }
144
+ /**
145
+ * Compare values recursively, treating two volatile references as equal regardless of value.
146
+ * Strict comparison distinguishes null/undefined, treats opaque objects by identity,
147
+ * compares URLs by normalized href, treats array holes as undefined, and considers distinct cyclic structures unequal.
148
+ * @param a - first value.
149
+ * @param b - second value.
150
+ * @param strict - whether to require strict data equality outside volatile references.
151
+ * @returns whether the values compare equal.
152
+ */
153
+ function deepEqual(a, b, strict) {
154
+ const ancestors = /* @__PURE__ */ new Set();
155
+ function compare(a, b) {
156
+ if (a === b) return true;
157
+ if (isVolatile(a) || isVolatile(b)) return isVolatile(a) && isVolatile(b);
158
+ if (!strict && isNullable(a) && isNullable(b)) return true;
159
+ if (typeof a !== typeof b || typeof a !== "object" || !a || !b) return false;
160
+ if (ancestors.has(a)) return false;
161
+ function check(test, then) {
162
+ return test(a) ? test(b) ? then(a, b) : false : test(b) ? false : void 0;
163
+ }
164
+ ancestors.add(a);
165
+ try {
166
+ return check(Array.isArray, (a, b) => {
167
+ if (a.length !== b.length) return false;
168
+ for (let index = 0; index < a.length; index++) if (!compare(a[index], b[index])) return false;
169
+ return true;
170
+ }) ?? check(is("Date"), (a, b) => a.valueOf() === b.valueOf()) ?? check(is("URL"), (a, b) => a.href === b.href) ?? check(is("RegExp"), (a, b) => a.source === b.source && a.flags === b.flags) ?? check(isArrayBufferLike, (a, b) => {
171
+ if (a.byteLength !== b.byteLength) return false;
172
+ const viewA = new Uint8Array(a);
173
+ const viewB = new Uint8Array(b);
174
+ for (let i = 0; i < viewA.length; i++) if (viewA[i] !== viewB[i]) return false;
175
+ return true;
176
+ }) ?? ((!strict || [a, b].every((value) => Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) && Object.keys({
177
+ ...a,
178
+ ...b
179
+ }).every((key) => compare(a[key], b[key])));
180
+ } finally {
181
+ ancestors.delete(a);
182
+ }
183
+ }
184
+ return compare(a, b);
185
+ }
186
+ /** Time constants plus parsing and formatting helpers. */
187
+ var Time;
188
+ (function(Time) {
189
+ Time.millisecond = 1;
190
+ Time.second = 1e3;
191
+ Time.minute = Time.second * 60;
192
+ Time.hour = Time.minute * 60;
193
+ Time.day = Time.hour * 24;
194
+ Time.week = Time.day * 7;
195
+ let timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();
196
+ function setTimezoneOffset(offset) {
197
+ timezoneOffset = offset;
198
+ }
199
+ Time.setTimezoneOffset = setTimezoneOffset;
200
+ function getTimezoneOffset() {
201
+ return timezoneOffset;
202
+ }
203
+ Time.getTimezoneOffset = getTimezoneOffset;
204
+ function getDateNumber(date = /* @__PURE__ */ new Date(), offset) {
205
+ if (typeof date === "number") date = new Date(date);
206
+ if (offset === void 0) offset = timezoneOffset;
207
+ return Math.floor((date.valueOf() / Time.minute - offset) / 1440);
208
+ }
209
+ Time.getDateNumber = getDateNumber;
210
+ function fromDateNumber(value, offset) {
211
+ const date = new Date(value * Time.day);
212
+ if (offset === void 0) offset = timezoneOffset;
213
+ return new Date(+date + offset * Time.minute);
214
+ }
215
+ Time.fromDateNumber = fromDateNumber;
216
+ const numeric = /\d+(?:\.\d+)?/.source;
217
+ const timeRegExp = new RegExp(`^${[
218
+ "w(?:eek(?:s)?)?",
219
+ "d(?:ay(?:s)?)?",
220
+ "h(?:our(?:s)?)?",
221
+ "m(?:in(?:ute)?(?:s)?)?",
222
+ "s(?:ec(?:ond)?(?:s)?)?"
223
+ ].map((unit) => `(${numeric}${unit})?`).join("")}$`);
224
+ function parseTime(source) {
225
+ const capture = timeRegExp.exec(source);
226
+ if (!capture) return 0;
227
+ 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);
228
+ }
229
+ Time.parseTime = parseTime;
230
+ function parseDate(date) {
231
+ const parsed = parseTime(date);
232
+ if (parsed) date = Date.now() + parsed;
233
+ else if (/^\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date}`;
234
+ else if (/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date}`;
235
+ return date ? new Date(date) : /* @__PURE__ */ new Date();
236
+ }
237
+ Time.parseDate = parseDate;
238
+ function format(ms) {
239
+ const abs = Math.abs(ms);
240
+ if (abs >= Time.day - Time.hour / 2) return Math.round(ms / Time.day) + "d";
241
+ else if (abs >= Time.hour - Time.minute / 2) return Math.round(ms / Time.hour) + "h";
242
+ else if (abs >= Time.minute - Time.second / 2) return Math.round(ms / Time.minute) + "m";
243
+ else if (abs >= Time.second) return Math.round(ms / Time.second) + "s";
244
+ return ms + "ms";
245
+ }
246
+ Time.format = format;
247
+ function toDigits(source, length = 2) {
248
+ return source.toString().padStart(length, "0");
249
+ }
250
+ Time.toDigits = toDigits;
251
+ function template(template, time = /* @__PURE__ */ new Date()) {
252
+ 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));
253
+ }
254
+ Time.template = template;
255
+ })(Time || (Time = {}));
256
+ // ../../node_modules/.pnpm/@deepseek-ai+schemastery@3.19.0/node_modules/@deepseek-ai/schemastery/lib/index.mjs
257
+ const kSchema = Symbol.for("schemastery");
258
+ const kValidationError = Symbol.for("ValidationError");
259
+ globalThis.__schemastery_index__ ??= 0;
260
+ globalThis.__schemastery_refs__ = void 0;
261
+ var ValidationError = class extends TypeError {
262
+ options;
263
+ name = "ValidationError";
264
+ constructor(message, options) {
265
+ let prefix = "$";
266
+ for (const segment of options.path || []) if (typeof segment === "string") prefix += "." + segment;
267
+ else if (typeof segment === "number") prefix += "[" + segment + "]";
268
+ else if (typeof segment === "symbol") prefix += `[Symbol(${segment.toString()})]`;
269
+ if (prefix.startsWith(".")) prefix = prefix.slice(1);
270
+ super((prefix === "$" ? "" : `${prefix} `) + message);
271
+ this.options = options;
272
+ }
273
+ static is(error) {
274
+ return !!error?.[kValidationError];
275
+ }
276
+ };
277
+ Object.defineProperty(ValidationError.prototype, kValidationError, { value: true });
278
+ const Schema = function(options) {
279
+ const schema = function(data, options = {}) {
280
+ return Schema.resolve(data, schema, options)[0];
281
+ };
282
+ if (options.refs) {
283
+ const refs = mapValues(options.refs, (options) => new Schema(options));
284
+ const getRef = (uid) => refs[uid];
285
+ for (const key in refs) {
286
+ const options = refs[key];
287
+ options.sKey = getRef(options.sKey);
288
+ options.inner = getRef(options.inner);
289
+ options.list = options.list && options.list.map(getRef);
290
+ options.dict = options.dict && mapValues(options.dict, getRef);
291
+ }
292
+ return refs[options.uid];
293
+ }
294
+ Object.assign(schema, options);
295
+ if (typeof schema.callback === "string") try {
296
+ schema.callback = new Function("return " + schema.callback)();
297
+ } catch {}
298
+ Object.defineProperty(schema, "uid", { value: globalThis.__schemastery_index__++ });
299
+ Object.setPrototypeOf(schema, Schema.prototype);
300
+ schema.meta ||= {};
301
+ schema.toString = schema.toString.bind(schema);
302
+ return schema;
303
+ };
304
+ Schema.prototype = Object.create(Function.prototype);
305
+ Schema.prototype[kSchema] = true;
306
+ Object.defineProperty(Schema.prototype, "~standard", { get() {
307
+ return {
308
+ version: 1,
309
+ vendor: "schemastery",
310
+ validate: (value) => {
311
+ try {
312
+ return { value: Schema.resolve(value, this, {})[0] };
313
+ } catch (error) {
314
+ if (ValidationError.is(error)) return { issues: [{
315
+ message: error.message,
316
+ path: error.options.path
317
+ }] };
318
+ throw error;
319
+ }
320
+ }
321
+ };
322
+ } });
323
+ Schema.ValidationError = ValidationError;
324
+ Schema.prototype.toJSON = function toJSON() {
325
+ if (globalThis.__schemastery_refs__) {
326
+ globalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));
327
+ return this.uid;
328
+ }
329
+ globalThis.__schemastery_refs__ = { [this.uid]: { ...this } };
330
+ globalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));
331
+ const result = {
332
+ uid: this.uid,
333
+ refs: globalThis.__schemastery_refs__
334
+ };
335
+ globalThis.__schemastery_refs__ = void 0;
336
+ return result;
337
+ };
338
+ Schema.prototype.set = function set(key, value) {
339
+ this.dict[key] = value;
340
+ return this;
341
+ };
342
+ Schema.prototype.push = function push(value) {
343
+ this.list.push(value);
344
+ return this;
345
+ };
346
+ function mergeDesc(original, messages) {
347
+ const result = typeof original === "string" ? { "": original } : { ...original };
348
+ for (const locale in messages) {
349
+ const value = messages[locale];
350
+ if (value?.$description || value?.$desc) result[locale] = value.$description || value.$desc;
351
+ else if (typeof value === "string") result[locale] = value;
352
+ }
353
+ return result;
354
+ }
355
+ function getInner(value) {
356
+ return value?.$value ?? value?.$inner;
357
+ }
358
+ function extractKeys(data) {
359
+ return filterKeys(data ?? {}, (key) => !key.startsWith("$"));
360
+ }
361
+ Schema.prototype.i18n = function i18n(messages) {
362
+ const schema = Schema(this);
363
+ const desc = mergeDesc(schema.meta.description, messages);
364
+ if (Object.keys(desc).length) schema.meta.description = desc;
365
+ if (schema.dict) schema.dict = mapValues(schema.dict, (inner, key) => {
366
+ return inner.i18n(mapValues(messages, (data) => getInner(data)?.[key] ?? data?.[key]));
367
+ });
368
+ if (schema.list) schema.list = schema.list.map((inner, index) => {
369
+ return inner.i18n(mapValues(messages, (data = {}) => {
370
+ if (Array.isArray(getInner(data))) return getInner(data)[index];
371
+ if (Array.isArray(data)) return data[index];
372
+ return extractKeys(data);
373
+ }));
374
+ });
375
+ if (schema.inner) schema.inner = schema.inner.i18n(mapValues(messages, (data) => {
376
+ if (getInner(data)) return getInner(data);
377
+ return extractKeys(data);
378
+ }));
379
+ if (schema.sKey) schema.sKey = schema.sKey.i18n(mapValues(messages, (data) => data?.$key));
380
+ return schema;
381
+ };
382
+ Schema.prototype.extra = function extra(key, value) {
383
+ const schema = Schema(this);
384
+ schema.meta = {
385
+ ...schema.meta,
386
+ [key]: value
387
+ };
388
+ return schema;
389
+ };
390
+ for (const key of [
391
+ "required",
392
+ "disabled",
393
+ "collapse",
394
+ "hidden",
395
+ "loose"
396
+ ]) Object.assign(Schema.prototype, { [key](value = true) {
397
+ const schema = Schema(this);
398
+ schema.meta = {
399
+ ...schema.meta,
400
+ [key]: value
401
+ };
402
+ return schema;
403
+ } });
404
+ Schema.prototype.deprecated = function deprecated() {
405
+ const schema = Schema(this);
406
+ schema.meta.badges ||= [];
407
+ schema.meta.badges.push({
408
+ text: "deprecated",
409
+ type: "danger"
410
+ });
411
+ return schema;
412
+ };
413
+ Schema.prototype.experimental = function experimental() {
414
+ const schema = Schema(this);
415
+ schema.meta.badges ||= [];
416
+ schema.meta.badges.push({
417
+ text: "experimental",
418
+ type: "warning"
419
+ });
420
+ return schema;
421
+ };
422
+ Schema.prototype.pattern = function pattern(regexp) {
423
+ const schema = Schema(this);
424
+ const pattern = pick(regexp, ["source", "flags"]);
425
+ schema.meta = {
426
+ ...schema.meta,
427
+ pattern
428
+ };
429
+ return schema;
430
+ };
431
+ Schema.prototype.simplify = function simplify(value) {
432
+ if (isVolatile(value)) value = value.get();
433
+ if (deepEqual(value, this.meta.default, this.type === "dict")) return null;
434
+ if (isNullable(value)) return value;
435
+ if (this.type === "object" || this.type === "dict") {
436
+ const result = {};
437
+ for (const key in value) {
438
+ const item = (this.type === "object" ? this.dict[key] : this.inner)?.simplify(value[key]);
439
+ if (this.type === "dict" || !isNullable(item)) result[key] = item;
440
+ }
441
+ if (deepEqual(result, this.meta.default, this.type === "dict")) return null;
442
+ return result;
443
+ } else if (this.type === "array" || this.type === "tuple") {
444
+ const result = [];
445
+ value.forEach((value, index) => {
446
+ const schema = this.type === "array" ? this.inner : this.list[index];
447
+ const item = schema ? schema.simplify(value) : value;
448
+ result.push(item);
449
+ });
450
+ return result;
451
+ } else if (this.type === "intersect") {
452
+ const result = {};
453
+ for (const item of this.list) Object.assign(result, item.simplify(value));
454
+ return result;
455
+ } else if (this.type === "union") for (const schema of this.list) try {
456
+ Schema.resolve(value, schema, {});
457
+ return schema.simplify(value);
458
+ } catch {}
459
+ return value;
460
+ };
461
+ Schema.prototype.toString = function toString(inline) {
462
+ return formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;
463
+ };
464
+ Schema.prototype.role = function role(role, extra) {
465
+ const schema = Schema(this);
466
+ schema.meta = {
467
+ ...schema.meta,
468
+ role,
469
+ extra
470
+ };
471
+ return schema;
472
+ };
473
+ for (const key of [
474
+ "default",
475
+ "link",
476
+ "comment",
477
+ "description",
478
+ "max",
479
+ "min",
480
+ "step"
481
+ ]) Object.assign(Schema.prototype, { [key](value) {
482
+ const schema = Schema(this);
483
+ schema.meta = {
484
+ ...schema.meta,
485
+ [key]: value
486
+ };
487
+ return schema;
488
+ } });
489
+ Schema.prototype.volatile = function volatile() {
490
+ if (this.meta.volatile) throw new TypeError("volatile schema is already wrapped");
491
+ return this.extra("volatile", true);
492
+ };
493
+ const resolvers = {};
494
+ const checkedVolatile = Symbol("checked-volatile-schema");
495
+ function validateVolatileSchema(schema, path = [], blocked = false, seen = /* @__PURE__ */ new Map()) {
496
+ const states = seen.get(schema) ?? /* @__PURE__ */ new Set();
497
+ if (states.has(blocked)) return;
498
+ states.add(blocked);
499
+ seen.set(schema, states);
500
+ if (schema.meta?.volatile && blocked) throw new ValidationError("volatile fields require a fixed object path without an enclosing volatile field", { path });
501
+ const nested = blocked || !!schema.meta?.volatile;
502
+ if (schema.dict) for (const [key, child] of Object.entries(schema.dict)) validateVolatileSchema(child, [...path, key], nested, seen);
503
+ if (schema.sKey) validateVolatileSchema(schema.sKey, [...path, "<key>"], true, seen);
504
+ if (schema.inner && (schema.type !== "lazy" || schema.inner[kSchema])) validateVolatileSchema(schema.inner, [...path, "*"], true, seen);
505
+ if (schema.list) for (let index = 0; index < schema.list.length; index++) validateVolatileSchema(schema.list[index], [...path, String(index)], true, seen);
506
+ }
507
+ Schema.extend = function extend(type, resolve) {
508
+ resolvers[type] = resolve;
509
+ };
510
+ Schema.resolve = function resolve(data, schema, options = {}, strict = false) {
511
+ if (!schema) return [data];
512
+ if (!options[checkedVolatile]) {
513
+ validateVolatileSchema(schema, options.path);
514
+ options = {
515
+ ...options,
516
+ [checkedVolatile]: true
517
+ };
518
+ }
519
+ if (schema.meta?.volatile) {
520
+ const inner = Schema(schema);
521
+ inner.meta = {
522
+ ...schema.meta,
523
+ volatile: false
524
+ };
525
+ const [value, adapted] = Schema.resolve(data, inner, options, strict);
526
+ try {
527
+ return [createVolatile(value), adapted];
528
+ } catch (error) {
529
+ throw new ValidationError(error instanceof Error ? error.message : String(error), options);
530
+ }
531
+ }
532
+ if (options.ignore?.(data, schema)) return [data];
533
+ if (isNullable(data) && schema.type !== "lazy") {
534
+ if (schema.meta.required) throw new ValidationError(`missing required value`, options);
535
+ let current = schema;
536
+ let fallback = schema.meta.default;
537
+ while (current?.type === "intersect" && isNullable(fallback)) {
538
+ current = current.list[0];
539
+ fallback = current?.meta.default;
540
+ }
541
+ if (isNullable(fallback)) return [data];
542
+ data = clone(fallback);
543
+ }
544
+ const callback = resolvers[schema.type];
545
+ if (!callback) throw new ValidationError(`unsupported type "${schema.type}"`, options);
546
+ try {
547
+ return callback(data, schema, options, strict);
548
+ } catch (error) {
549
+ if (!schema.meta.loose) throw error;
550
+ return [schema.meta.default];
551
+ }
552
+ };
553
+ Schema.from = function from(source) {
554
+ if (isNullable(source)) return Schema.any();
555
+ else if ([
556
+ "string",
557
+ "number",
558
+ "boolean"
559
+ ].includes(typeof source)) return Schema.const(source).required();
560
+ else if (source[kSchema]) return source;
561
+ else if (typeof source === "function") switch (source) {
562
+ case String: return Schema.string().required();
563
+ case Number: return Schema.number().required();
564
+ case Boolean: return Schema.boolean().required();
565
+ case Function: return Schema.function().required();
566
+ default: return Schema.is(source).required();
567
+ }
568
+ else throw new TypeError(`cannot infer schema from ${source}`);
569
+ };
570
+ Schema.lazy = function lazy(builder) {
571
+ const toJSON = () => {
572
+ if (!schema.inner[kSchema]) {
573
+ schema.inner = schema.builder();
574
+ schema.inner.meta = {
575
+ ...schema.meta,
576
+ ...schema.inner.meta
577
+ };
578
+ }
579
+ return schema.inner.toJSON();
580
+ };
581
+ const schema = new Schema({
582
+ type: "lazy",
583
+ builder,
584
+ inner: { toJSON }
585
+ });
586
+ return schema;
587
+ };
588
+ Schema.natural = function natural() {
589
+ return Schema.number().step(1).min(0);
590
+ };
591
+ Schema.percent = function percent() {
592
+ return Schema.number().step(.01).min(0).max(1).role("slider");
593
+ };
594
+ Schema.date = function date() {
595
+ return Schema.union([Schema.is(Date), Schema.transform(Schema.string().role("datetime"), (value, options) => {
596
+ const date = new Date(value);
597
+ if (isNaN(+date)) throw new ValidationError(`invalid date "${value}"`, options);
598
+ return date;
599
+ }, true)]);
600
+ };
601
+ Schema.regExp = function regExp(flag = "") {
602
+ return Schema.union([Schema.is(RegExp), Schema.transform(Schema.string().role("regexp", { flag }), (value, options) => {
603
+ try {
604
+ return new RegExp(value, flag);
605
+ } catch (e) {
606
+ throw new ValidationError(e.message, options);
607
+ }
608
+ }, true)]);
609
+ };
610
+ Schema.arrayBuffer = function arrayBuffer(encoding) {
611
+ return Schema.union([
612
+ Schema.is(ArrayBuffer),
613
+ Schema.is(SharedArrayBuffer),
614
+ Schema.transform(Schema.any(), (value, options) => {
615
+ if (Binary.isSource(value)) return Binary.fromSource(value);
616
+ throw new ValidationError(`expected ArrayBufferSource but got ${value}`, options);
617
+ }, true),
618
+ ...encoding ? [Schema.transform(Schema.string(), (value, options) => {
619
+ try {
620
+ return encoding === "base64" ? Binary.fromBase64(value) : Binary.fromHex(value);
621
+ } catch (e) {
622
+ throw new ValidationError(e.message, options);
623
+ }
624
+ }, true)] : []
625
+ ]);
626
+ };
627
+ Schema.extend("lazy", (data, schema, options, strict) => {
628
+ if (!schema.inner[kSchema]) {
629
+ schema.inner = schema.builder();
630
+ schema.inner.meta = {
631
+ ...schema.meta,
632
+ ...schema.inner.meta
633
+ };
634
+ validateVolatileSchema(schema.inner, options.path, true);
635
+ }
636
+ return Schema.resolve(data, schema.inner, options, strict);
637
+ });
638
+ Schema.extend("any", (data) => {
639
+ return [data];
640
+ });
641
+ Schema.extend("never", (data, _, options) => {
642
+ throw new ValidationError(`expected nullable but got ${data}`, options);
643
+ });
644
+ Schema.extend("const", (data, { value }, options) => {
645
+ if (deepEqual(data, value)) return [value];
646
+ throw new ValidationError(`expected ${value} but got ${data}`, options);
647
+ });
648
+ function checkWithinRange(data, meta, description, options, skipMin = false) {
649
+ const { max = Infinity, min = -Infinity } = meta;
650
+ if (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);
651
+ if (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);
652
+ }
653
+ Schema.extend("string", (data, { meta }, options) => {
654
+ if (typeof data !== "string") throw new ValidationError(`expected string but got ${data}`, options);
655
+ if (meta.pattern) {
656
+ const regexp = new RegExp(meta.pattern.source, meta.pattern.flags);
657
+ if (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);
658
+ }
659
+ checkWithinRange(data.length, meta, "string length", options);
660
+ return [data];
661
+ });
662
+ function decimalShift(data, digits) {
663
+ const str = data.toString();
664
+ if (str.includes("e")) return data * Math.pow(10, digits);
665
+ const index = str.indexOf(".");
666
+ if (index === -1) return data * Math.pow(10, digits);
667
+ const frac = str.slice(index + 1);
668
+ const integer = str.slice(0, index);
669
+ if (frac.length <= digits) return +(integer + frac.padEnd(digits, "0"));
670
+ return +(integer + frac.slice(0, digits) + "." + frac.slice(digits));
671
+ }
672
+ function isMultipleOf(data, min, step) {
673
+ step = Math.abs(step);
674
+ if (!/^\d+\.\d+$/.test(step.toString())) return (data - min) % step === 0;
675
+ const index = step.toString().indexOf(".");
676
+ const digits = step.toString().slice(index + 1).length;
677
+ return Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;
678
+ }
679
+ Schema.extend("number", (data, { meta }, options) => {
680
+ if (typeof data !== "number") throw new ValidationError(`expected number but got ${data}`, options);
681
+ checkWithinRange(data, meta, "number", options);
682
+ const { step } = meta;
683
+ if (step && !isMultipleOf(data, meta.min ?? 0, step)) throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);
684
+ return [data];
685
+ });
686
+ Schema.extend("boolean", (data, _, options) => {
687
+ if (typeof data === "boolean") return [data];
688
+ throw new ValidationError(`expected boolean but got ${data}`, options);
689
+ });
690
+ Schema.extend("bitset", (data, { bits, meta }, options) => {
691
+ let value = 0, keys = [];
692
+ if (typeof data === "number") {
693
+ value = data;
694
+ for (const key in bits) if (data & bits[key]) keys.push(key);
695
+ } else if (Array.isArray(data)) {
696
+ keys = data;
697
+ for (const key of keys) {
698
+ if (typeof key !== "string") throw new ValidationError(`expected string but got ${key}`, options);
699
+ if (key in bits) value |= bits[key];
700
+ }
701
+ } else throw new ValidationError(`expected number or array but got ${data}`, options);
702
+ if (value === meta.default) return [value];
703
+ return [value, keys];
704
+ });
705
+ Schema.extend("function", (data, _, options) => {
706
+ if (typeof data === "function") return [data];
707
+ throw new ValidationError(`expected function but got ${data}`, options);
708
+ });
709
+ Schema.extend("is", (data, { constructor }, options) => {
710
+ if (typeof constructor === "function") {
711
+ if (data instanceof constructor) return [data];
712
+ throw new ValidationError(`expected ${constructor.name} but got ${data}`, options);
713
+ } else {
714
+ if (isNullable(data)) throw new ValidationError(`expected ${constructor} but got ${data}`, options);
715
+ let prototype = Object.getPrototypeOf(data);
716
+ while (prototype) {
717
+ if (prototype.constructor?.name === constructor) return [data];
718
+ prototype = Object.getPrototypeOf(prototype);
719
+ }
720
+ throw new ValidationError(`expected ${constructor} but got ${data}`, options);
721
+ }
722
+ });
723
+ function property(data, key, schema, options) {
724
+ try {
725
+ const [value, adapted] = Schema.resolve(data[key], schema, {
726
+ ...options,
727
+ path: [...options.path || [], key]
728
+ });
729
+ if (adapted !== void 0) data[key] = adapted;
730
+ return value;
731
+ } catch (e) {
732
+ if (!options?.autofix) throw e;
733
+ delete data[key];
734
+ return schema.meta.volatile ? createVolatile(schema.meta.default) : schema.meta.default;
735
+ }
736
+ }
737
+ Schema.extend("array", (data, { inner, meta }, options) => {
738
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
739
+ checkWithinRange(data.length, meta, "array length", options, !isNullable(inner.meta.default));
740
+ return [data.map((_, index) => property(data, index, inner, options))];
741
+ });
742
+ Schema.extend("dict", (data, { inner, sKey }, options, strict) => {
743
+ if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
744
+ const result = {};
745
+ for (const key in data) {
746
+ let rKey;
747
+ try {
748
+ rKey = Schema.resolve(key, sKey, options)[0];
749
+ } catch (error) {
750
+ if (strict) continue;
751
+ throw error;
752
+ }
753
+ result[rKey] = property(data, key, inner, options);
754
+ data[rKey] = data[key];
755
+ if (key !== rKey) delete data[key];
756
+ }
757
+ return [result];
758
+ });
759
+ Schema.extend("tuple", (data, { list }, options, strict) => {
760
+ if (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);
761
+ const result = list.map((inner, index) => property(data, index, inner, options));
762
+ if (strict) return [result];
763
+ result.push(...data.slice(list.length));
764
+ return [result];
765
+ });
766
+ function merge(result, data) {
767
+ for (const key in data) {
768
+ if (key in result) continue;
769
+ result[key] = data[key];
770
+ }
771
+ }
772
+ Schema.extend("object", (data, { dict }, options, strict) => {
773
+ if (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);
774
+ const result = {};
775
+ for (const key in dict) {
776
+ const value = property(data, key, dict[key], options);
777
+ if (!isNullable(value) || key in data) result[key] = value;
778
+ }
779
+ if (!strict) merge(result, data);
780
+ return [result];
781
+ });
782
+ Schema.extend("union", (data, { list, toString }, options, strict) => {
783
+ const messages = [];
784
+ for (const inner of list) try {
785
+ return Schema.resolve(data, inner, options, strict);
786
+ } catch (error) {
787
+ messages.push(error);
788
+ }
789
+ throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
790
+ });
791
+ Schema.extend("intersect", (data, { list, toString }, options, strict) => {
792
+ if (!list.length) return [data];
793
+ let result;
794
+ for (const inner of list) {
795
+ const value = Schema.resolve(data, inner, options, true)[0];
796
+ if (isNullable(value)) continue;
797
+ if (isNullable(result)) result = value;
798
+ else if (typeof result !== typeof value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
799
+ else if (typeof value === "object") merge(result ??= {}, value);
800
+ else if (result !== value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);
801
+ }
802
+ if (!strict && isPlainObject(data)) merge(result, data);
803
+ return [result];
804
+ });
805
+ Schema.extend("transform", (data, { inner, callback, preserve }, options) => {
806
+ const [result, adapted = data] = Schema.resolve(data, inner, options, true);
807
+ if (preserve) return [callback(result)];
808
+ else return [callback(result), callback(adapted)];
809
+ });
810
+ const formatters = {};
811
+ function defineMethod(name, keys, format) {
812
+ formatters[name] = format;
813
+ Object.assign(Schema, { [name](...args) {
814
+ const schema = new Schema({ type: name });
815
+ keys.forEach((key, index) => {
816
+ switch (key) {
817
+ case "sKey":
818
+ schema.sKey = args[index] ?? Schema.string();
819
+ break;
820
+ case "inner":
821
+ schema.inner = Schema.from(args[index]);
822
+ break;
823
+ case "list":
824
+ schema.list = args[index].map(Schema.from);
825
+ break;
826
+ case "dict":
827
+ schema.dict = mapValues(args[index], Schema.from);
828
+ break;
829
+ case "bits":
830
+ schema.bits = {};
831
+ for (const key in args[index]) {
832
+ if (typeof args[index][key] !== "number") continue;
833
+ schema.bits[key] = args[index][key];
834
+ }
835
+ break;
836
+ case "callback": {
837
+ const callback = schema.callback = args[index];
838
+ callback["toJSON"] ||= () => callback.toString();
839
+ break;
840
+ }
841
+ case "constructor": {
842
+ const constructor = schema.constructor = args[index];
843
+ if (typeof constructor === "function") constructor["toJSON"] ||= () => constructor["name"];
844
+ break;
845
+ }
846
+ default: schema[key] = args[index];
847
+ }
848
+ });
849
+ if (name === "object" || name === "dict") schema.meta.default = {};
850
+ else if (name === "array" || name === "tuple") schema.meta.default = [];
851
+ else if (name === "bitset") schema.meta.default = 0;
852
+ return schema;
853
+ } });
854
+ }
855
+ defineMethod("is", ["constructor"], ({ constructor }) => {
856
+ if (typeof constructor === "function") return constructor.name;
857
+ else return constructor;
858
+ });
859
+ defineMethod("any", [], () => "any");
860
+ defineMethod("never", [], () => "never");
861
+ defineMethod("const", ["value"], ({ value }) => typeof value === "string" ? JSON.stringify(value) : value);
862
+ defineMethod("string", [], () => "string");
863
+ defineMethod("number", [], () => "number");
864
+ defineMethod("boolean", [], () => "boolean");
865
+ defineMethod("bitset", ["bits"], () => "bitset");
866
+ defineMethod("function", [], () => "function");
867
+ defineMethod("array", ["inner"], ({ inner }) => `${inner.toString(true)}[]`);
868
+ defineMethod("dict", ["inner", "sKey"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);
869
+ defineMethod("tuple", ["list"], ({ list }) => `[${list.map((inner) => inner.toString()).join(", ")}]`);
870
+ defineMethod("object", ["dict"], ({ dict }) => {
871
+ if (Object.keys(dict).length === 0) return "{}";
872
+ return `{ ${Object.entries(dict).map(([key, inner]) => {
873
+ return `${key}${inner.meta.required ? "" : "?"}: ${inner.toString()}`;
874
+ }).join(", ")} }`;
875
+ });
876
+ defineMethod("union", ["list"], ({ list }, inline) => {
877
+ const result = list.map(({ toString: format }) => format()).join(" | ");
878
+ return inline ? `(${result})` : result;
879
+ });
880
+ defineMethod("intersect", ["list"], ({ list }) => {
881
+ return `${list.map((inner) => inner.toString(true)).join(" & ")}`;
882
+ });
883
+ defineMethod("transform", [
884
+ "inner",
885
+ "callback",
886
+ "preserve"
887
+ ], ({ inner }, isInner) => inner.toString(isInner));
888
+ // ../../tools/plugin-server/src/git-env.ts
889
+ /**
890
+ * Environment entries that redirect git or a forge CLI to a repository other
891
+ * than the session working directory. Each entry must arrive unset so an
892
+ * inherited value cannot escape the session cwd.
893
+ */
894
+ const repositoryEnvKeys = [
895
+ "GIT_DIR",
896
+ "GIT_WORK_TREE",
897
+ "GIT_COMMON_DIR",
898
+ "GIT_INDEX_FILE",
899
+ "GIT_OBJECT_DIRECTORY",
900
+ "GIT_ALTERNATE_OBJECT_DIRECTORIES",
901
+ "GIT_CONFIG",
902
+ "GIT_CONFIG_PARAMETERS",
903
+ "GIT_CEILING_DIRECTORIES",
904
+ "GIT_PREFIX",
905
+ "GIT_SHALLOW_FILE",
906
+ "GIT_GRAFT_FILE",
907
+ "GIT_REPLACE_REF_BASE",
908
+ "GIT_ATTR_SOURCE"
909
+ ];
910
+ /**
911
+ * Hardened environment for spawning git or a forge CLI from a session cwd.
912
+ * Config injection and terminal prompts are disabled, lazy fetch is off, and
913
+ * output stays in the C locale so parsers can match stable English messages.
914
+ * `extra` adds tool-specific entries, including bare keys set to undefined to
915
+ * scrub inherited values.
916
+ */
917
+ function gitProcessEnvironment(extra = {}) {
918
+ return {
919
+ ...Object.fromEntries(repositoryEnvKeys.map((key) => [key, void 0])),
920
+ GIT_CONFIG_COUNT: "0",
921
+ GIT_TERMINAL_PROMPT: "0",
922
+ GIT_OPTIONAL_LOCKS: "0",
923
+ GIT_NO_LAZY_FETCH: "1",
924
+ LC_ALL: "C",
925
+ ...extra
926
+ };
927
+ }
928
+ // ../../tools/plugin-server/src/rpc.ts
929
+ /**
930
+ * Parse a Connection fetch request against one exact method. Returns null for
931
+ * anything the envelope rejects, so the caller answers 400; payload validation
932
+ * stays with the endpoint owner.
933
+ */
934
+ async function parseRpcRequest(request, method) {
935
+ let parsed;
936
+ try {
937
+ parsed = clientRequestSchema.safeParse(await request.json());
938
+ } catch {
939
+ return null;
940
+ }
941
+ if (!parsed.success || parsed.data.method !== method) return null;
942
+ return {
943
+ rpcId: parsed.data.rpcId,
944
+ payload: parsed.data.payload
945
+ };
946
+ }
947
+ /**
948
+ * Reply to a parsed request with the server-response envelope. Cache-control
949
+ * keeps proxies and caches from reusing one RPC result for another request.
950
+ */
951
+ function rpcResponse(rpcId, result) {
952
+ return Response.json({
953
+ type: "server-response",
954
+ rpcId,
955
+ result
956
+ }, { headers: { "Cache-Control": "no-store" } });
957
+ }
958
+ // src/inspect-session.ts
959
+ async function inspectSession(ctx, id, signal) {
960
+ signal.throwIfAborted();
961
+ const live = ctx.get("agents")?.get(id);
962
+ if (live) return live.session;
963
+ const handle = await ctx.sessionPersistence.open(id, "read", { signal });
964
+ try {
965
+ const { events } = await handle.read(void 0, void 0, { signal });
966
+ signal.throwIfAborted();
967
+ return Session.create(id, events, handle.header, handle.inheritedEventCount);
968
+ } finally {
969
+ await handle.close();
970
+ }
971
+ }
972
+ // src/github-merge.ts
973
+ const checksQuery = `query($owner: String!, $name: String!, $number: Int!) {
974
+ repository(owner: $owner, name: $name) { pullRequest(number: $number) {
975
+ headRefOid commits(last: 1) { nodes { commit { oid statusCheckRollup {
976
+ state contexts(first: 100) { pageInfo { hasNextPage } nodes {
977
+ __typename ... on CheckRun { status conclusion } ... on StatusContext { state }
978
+ } }
979
+ } } } }
980
+ } }
981
+ }`;
982
+ function completeChecks(value, sha) {
983
+ const pr = value?.data?.repository?.pullRequest;
984
+ if (value?.errors || pr?.headRefOid !== sha || !Array.isArray(pr?.commits?.nodes) || pr.commits.nodes.length !== 1) return false;
985
+ const commit = pr.commits.nodes[0]?.commit;
986
+ if (!commit || commit.oid !== sha || !Object.hasOwn(commit, "statusCheckRollup")) return false;
987
+ const rollup = commit.statusCheckRollup;
988
+ if (rollup === null) return true;
989
+ if (rollup?.state !== "SUCCESS") return false;
990
+ const contexts = rollup.contexts;
991
+ if (contexts?.pageInfo?.hasNextPage !== false || !Array.isArray(contexts.nodes) || contexts.nodes.length === 0) return false;
992
+ return contexts.nodes.every((check) => ["CheckRun", "StatusContext"].includes(check?.__typename));
993
+ }
994
+ function mergeMethods(snapshot, item) {
995
+ if (!snapshot || snapshot.url !== item.url || snapshot.ref.repository.forge !== "github" || snapshot.ref.number !== item.number || snapshot.headSha !== item.headSha || snapshot.headBranch !== item.source || snapshot.baseBranch !== item.target || snapshot.state !== "open" || snapshot.draft !== false || snapshot.mergeReady !== true || snapshot.mergeability !== "mergeable" || snapshot.checksTruncated !== false || !["none", "success"].includes(snapshot.checksRollup) || !["none", "approved"].includes(snapshot.reviewDecision) || !Array.isArray(snapshot.checks) || !snapshot.checks.every((check) => [
996
+ "success",
997
+ "neutral",
998
+ "skipped"
999
+ ].includes(check.state)) || !Array.isArray(snapshot.mergeMethods)) return [];
1000
+ return snapshot.mergeMethods.filter((method) => [
1001
+ "merge",
1002
+ "squash",
1003
+ "rebase"
1004
+ ].includes(method));
1005
+ }
1006
+ // ../../tools/async/src/index.ts
1007
+ function createTaskQueue({ concurrency, maxPending }) {
1008
+ if (!Number.isSafeInteger(concurrency) || concurrency < 1 || !Number.isSafeInteger(maxPending) || maxPending < 0) throw new RangeError("Invalid task queue limits");
1009
+ let active = 0;
1010
+ const pending = /* @__PURE__ */ new Set();
1011
+ const drain = () => {
1012
+ while (active < concurrency && pending.size) pending.values().next().value.start();
1013
+ };
1014
+ return (signal, task) => {
1015
+ if (signal.aborted) return Promise.reject(signal.reason);
1016
+ if (active >= concurrency && pending.size >= maxPending) return Promise.reject(/* @__PURE__ */ new Error("busy"));
1017
+ return new Promise((resolve, reject) => {
1018
+ const entry = {
1019
+ start() {
1020
+ pending.delete(entry);
1021
+ signal.removeEventListener("abort", entry.cancel);
1022
+ active++;
1023
+ (async () => {
1024
+ try {
1025
+ signal.throwIfAborted();
1026
+ resolve(await task());
1027
+ } catch (error) {
1028
+ reject(error);
1029
+ } finally {
1030
+ active--;
1031
+ drain();
1032
+ }
1033
+ })();
1034
+ },
1035
+ cancel() {
1036
+ pending.delete(entry);
1037
+ signal.removeEventListener("abort", entry.cancel);
1038
+ reject(signal.reason);
1039
+ }
1040
+ };
1041
+ pending.add(entry);
1042
+ signal.addEventListener("abort", entry.cancel, { once: true });
1043
+ drain();
1044
+ });
1045
+ };
1046
+ }
1047
+ // src/read-queue.ts
1048
+ const queues = /* @__PURE__ */ new WeakMap();
1049
+ function readQueue(provider) {
1050
+ let queue = queues.get(provider);
1051
+ if (!queue) {
1052
+ queue = createTaskQueue({
1053
+ concurrency: 2,
1054
+ maxPending: 128
1055
+ });
1056
+ queues.set(provider, queue);
1057
+ }
1058
+ return queue;
1059
+ }
1060
+ // src/changes.ts
1061
+ /** Keep both the subprocess output and the rendered snapshot bounded. */
1062
+ const MAX_FILES = 100;
1063
+ const MAX_DIFF_BYTES = 1e6;
1064
+ function path(value) {
1065
+ if (typeof value !== "string" || !value || value.length > 4096 || value.includes("\0")) throw new Error("invalid_response");
1066
+ return value;
1067
+ }
1068
+ function diff(value) {
1069
+ if (typeof value !== "string" || new TextEncoder().encode(value).length > MAX_DIFF_BYTES || value.includes("\0")) throw new Error("invalid_response");
1070
+ return value;
1071
+ }
1072
+ /** A failed or capped read is never interpreted as an empty change set. */
1073
+ async function readChanges(input) {
1074
+ try {
1075
+ if (input.provider === "github") {
1076
+ const result = await input.github();
1077
+ if (!Array.isArray(result.files) || result.files.length > MAX_FILES || result.changedFiles !== result.files.length) throw new Error("invalid_response");
1078
+ const files = result.files.map((file) => ({ path: path(file?.path) }));
1079
+ const patch = diff(result.diff);
1080
+ if (files.length && !patch) throw new Error("invalid_response");
1081
+ return {
1082
+ files,
1083
+ diff: patch,
1084
+ complete: true
1085
+ };
1086
+ }
1087
+ if (input.provider === "gitlab") {
1088
+ const result = await input.gitlab();
1089
+ if (!result || result.overflow !== false || !Array.isArray(result.changes) || result.changes.length > MAX_FILES) throw new Error("invalid_response");
1090
+ return {
1091
+ files: result.changes.map((file) => ({ path: path(file?.new_path) })),
1092
+ diff: diff(result.changes.map((file) => {
1093
+ const patch = diff(file?.diff);
1094
+ if (file?.collapsed || file?.too_large) throw new Error("invalid_response");
1095
+ const oldPath = path(file?.old_path);
1096
+ const newPath = path(file?.new_path);
1097
+ const modeChanged = typeof file?.a_mode === "string" && /^[0-7]{6}$/.test(file.a_mode) && typeof file?.b_mode === "string" && /^[0-7]{6}$/.test(file.b_mode) && file.a_mode !== file.b_mode;
1098
+ const metadataOnly = file?.renamed_file === true && oldPath !== newPath || file?.new_file === true || file?.deleted_file === true || modeChanged;
1099
+ if (!patch && !metadataOnly) throw new Error("invalid_response");
1100
+ return `diff --git a/${oldPath} b/${newPath}\n${!patch ? [
1101
+ file.renamed_file === true ? `rename from ${oldPath}\nrename to ${newPath}` : "",
1102
+ file.new_file === true ? "new file" : "",
1103
+ file.deleted_file === true ? "deleted file" : "",
1104
+ modeChanged ? `old mode ${file.a_mode}\nnew mode ${file.b_mode}` : ""
1105
+ ].filter(Boolean).join("\n") + "\n" : ""}${patch}`;
1106
+ }).join("\n")),
1107
+ complete: true
1108
+ };
1109
+ }
1110
+ const result = await input.forge();
1111
+ if (!Array.isArray(result.files) || result.files.length > MAX_FILES || result.changedFiles !== result.files.length) throw new Error("invalid_response");
1112
+ const files = result.files.map((file) => ({ path: path(file?.filename) }));
1113
+ const patch = diff(result.diff);
1114
+ if (files.length && !patch) throw new Error("invalid_response");
1115
+ return {
1116
+ files,
1117
+ diff: patch,
1118
+ complete: true
1119
+ };
1120
+ } catch {
1121
+ return {
1122
+ files: [],
1123
+ diff: "",
1124
+ complete: false
1125
+ };
1126
+ }
1127
+ }
1128
+ // src/protocol.ts
1129
+ const channel = "/api";
1130
+ const method = "dungsil-forge-pulls/pull-requests/list";
1131
+ const actionMethod = "dungsil-forge-pulls/pull-requests/action";
1132
+ // src/pull-requests.ts
1133
+ const name = "dungsil-forge-pulls";
1134
+ const inject = [
1135
+ "forge",
1136
+ "forgeSession",
1137
+ "connection",
1138
+ "sessionController",
1139
+ "sessionPersistence",
1140
+ "workingDirectory",
1141
+ "subprocess",
1142
+ "sandbox",
1143
+ "sandboxPolicy"
1144
+ ];
1145
+ const Config = Schema.object({ provider: Schema.union([
1146
+ "auto",
1147
+ "github",
1148
+ "gitlab",
1149
+ "gitea",
1150
+ "forgejo"
1151
+ ]).default("auto") });
1152
+ function safeUrl(value) {
1153
+ if (typeof value !== "string") throw new Error("invalid_response");
1154
+ if (!value) return "";
1155
+ const url = new URL(value);
1156
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) throw new Error("invalid_response");
1157
+ return value;
1158
+ }
1159
+ function lookupUrl(value) {
1160
+ try {
1161
+ if (typeof value !== "string" || !value || value.length > 4096 || value.includes("\\") || value.split("").some((character) => character <= " " || character === "")) throw new Error();
1162
+ const url = new URL(value);
1163
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.pathname !== value.match(/^https?:\/\/[^@/?#]+([^?#]*)/)?.[1]) throw new Error();
1164
+ url.search = "";
1165
+ url.hash = "";
1166
+ return url;
1167
+ } catch {
1168
+ throw new Error("unsupported");
1169
+ }
1170
+ }
1171
+ function string(value) {
1172
+ if (typeof value !== "string") throw new Error("invalid_response");
1173
+ return value;
1174
+ }
1175
+ function actionInput(value) {
1176
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("invalid_payload");
1177
+ const input = value;
1178
+ if (Object.keys(input).some((key) => ![
1179
+ "sessionId",
1180
+ "requestUrl",
1181
+ "headSha",
1182
+ "action",
1183
+ "body",
1184
+ "strategy",
1185
+ "branch",
1186
+ "target"
1187
+ ].includes(key)) || typeof input.sessionId !== "string" || !input.sessionId || input.sessionId.length > 256 || typeof input.requestUrl !== "string" || input.requestUrl.length > 4096 || !safeUrl(input.requestUrl) || typeof input.headSha !== "string" || !/^[a-fA-F0-9]{40,64}$/.test(input.headSha) || ![
1188
+ "comment",
1189
+ "approve",
1190
+ "request_changes",
1191
+ "merge"
1192
+ ].includes(input.action) || (input.action === "merge" ? ![
1193
+ "merge",
1194
+ "squash",
1195
+ "rebase"
1196
+ ].includes(input.strategy ?? "") || typeof input.branch !== "string" || !input.branch || input.branch.length > 1024 || typeof input.target !== "string" || !input.target || input.target.length > 1024 || input.body !== void 0 : input.strategy !== void 0 || input.branch !== void 0 || input.target !== void 0) || input.body !== void 0 && (typeof input.body !== "string" || new TextEncoder().encode(input.body).length > 6e4 || input.body.includes("\0")) || ["comment", "request_changes"].includes(input.action) && !input.body?.trim()) throw new Error("invalid_payload");
1197
+ return input;
1198
+ }
1199
+ function apply(ctx, config) {
1200
+ const lifetime = new AbortController();
1201
+ const actionsInFlight = /* @__PURE__ */ new Set();
1202
+ const read = readQueue(ctx.subprocess);
1203
+ ctx.effect(() => () => lifetime.abort());
1204
+ const list = async (session, signal, action, requested, summary = false) => {
1205
+ const cwd = ctx.workingDirectory.get(session);
1206
+ const argumentsSignal = signal;
1207
+ const run = async (executable, args, failure = "command_failed", allowed = [0], trim = true, options) => {
1208
+ const signal = options?.signal ?? argumentsSignal;
1209
+ let resolved;
1210
+ try {
1211
+ resolved = await ctx.subprocess.resolveExecutable(executable, void 0, signal);
1212
+ } catch {
1213
+ throw new Error(executable === "git" ? "repository" : "cli_missing");
1214
+ }
1215
+ const argv = [resolved, ...args];
1216
+ const policy = ctx.sandboxPolicy.resolve({ session });
1217
+ const command = policy.mode === "danger-full-access" ? argv : (await ctx.sandbox.confine(argv, {
1218
+ ...policy,
1219
+ mode: policy.mode
1220
+ }, signal)).argv;
1221
+ const child = ctx.subprocess.spawn({
1222
+ argv: command,
1223
+ cwd,
1224
+ signal,
1225
+ graceMs: 1e3,
1226
+ env: gitProcessEnvironment({
1227
+ GH_REPO: void 0,
1228
+ GH_HOST: void 0,
1229
+ GITLAB_REPO: void 0,
1230
+ GITLAB_HOST: void 0,
1231
+ TEA_LOGIN: void 0,
1232
+ TEA_REPO: void 0,
1233
+ ...executable === "tea" ? {
1234
+ GITEA_INSTANCE_URL: void 0,
1235
+ GITEA_INSTANCE_SSH_HOST: void 0,
1236
+ GITEA_INSTANCE_INSECURE: void 0,
1237
+ GITEA_TOKEN: void 0,
1238
+ GH_TOKEN: void 0
1239
+ } : {},
1240
+ GH_PROMPT_DISABLED: "1",
1241
+ GLAB_CHECK_UPDATE: "false",
1242
+ NO_COLOR: "1"
1243
+ }),
1244
+ stdio: {
1245
+ stdin: "ignore",
1246
+ stdout: { maxBytes: 2097152 },
1247
+ stderr: { maxBytes: 16384 }
1248
+ }
1249
+ });
1250
+ try {
1251
+ const outcome = await child.done;
1252
+ signal.throwIfAborted();
1253
+ const output = child.collected.stdout.readFrom(0);
1254
+ if (executable === "gh" && args[0] === "pr" && args[1] === "view" && !args.includes("--repo") && outcome.exitCode === 1 && !output.lossy && !output.text.trim()) {
1255
+ const stderr = child.collected.stderr.readFrom(0);
1256
+ if (!stderr.lossy && /^no pull requests found for branch "[^\n]+"\s*$/.test(stderr.text)) return "null";
1257
+ }
1258
+ if (outcome.exitCode === null || !allowed.includes(outcome.exitCode) || output.lossy) throw new Error(failure);
1259
+ if (executable === "tea" && args[0] === "api") {
1260
+ const headers = child.collected.stderr.readFrom(0);
1261
+ if (headers.lossy || !/^HTTP\/[\d.]+ 2\d\d\b/m.test(headers.text)) throw new Error(failure);
1262
+ options?.headers?.(headers.text);
1263
+ }
1264
+ return trim ? output.text.trim() : output.text;
1265
+ } finally {
1266
+ child.terminate();
1267
+ await child.waitForExit();
1268
+ }
1269
+ };
1270
+ const git = (args, allowed) => run("git", [
1271
+ "-c",
1272
+ "core.fsmonitor=false",
1273
+ ...args
1274
+ ], "repository", allowed);
1275
+ const bindings = ctx.forgeSession.changeRequests(session);
1276
+ const explicit = requested ?? (action ? lookupUrl(action.requestUrl) : void 0);
1277
+ const explicitRef = explicit ? ctx.forge.changeRequestFromUrl(explicit.href) : void 0;
1278
+ if (explicit && !explicitRef) throw new Error("unsupported");
1279
+ const canonical = explicitRef ? ctx.forge.changeRequestUrl(explicitRef) : void 0;
1280
+ const ref = (explicit ? bindings.find((entry) => entry.ref && ctx.forge.changeRequestUrl(entry.ref) === canonical) : bindings.find((entry) => entry.ref))?.ref;
1281
+ if (ref) requested = lookupUrl(ctx.forge.changeRequestUrl(ref));
1282
+ const branch = ref && !action ? "" : await git([
1283
+ "symbolic-ref",
1284
+ "--quiet",
1285
+ "--short",
1286
+ "HEAD"
1287
+ ], [0, 1]);
1288
+ const tracked = branch ? await git([
1289
+ "config",
1290
+ "--get",
1291
+ `branch.${branch}.remote`
1292
+ ], [0, 1]) : "";
1293
+ const raw = ref ? requested.origin + requested.pathname.replace(/\/(?:pull|pulls|-\/merge_requests)\/[1-9]\d*\/?$/, "") : await git([
1294
+ "remote",
1295
+ "get-url",
1296
+ "--",
1297
+ tracked && tracked !== "." ? tracked : "origin"
1298
+ ]);
1299
+ if (!ref && !ctx.forge.repositoryFromRemote(raw)) throw new Error("unsupported");
1300
+ let url;
1301
+ try {
1302
+ url = new URL(raw.includes("://") ? raw : `ssh://${raw.replace(/^([^@/]+@)?([^:/]+):/, "$1$2/")}`);
1303
+ } catch {
1304
+ throw new Error("unsupported");
1305
+ }
1306
+ if (![
1307
+ "https:",
1308
+ "http:",
1309
+ "ssh:"
1310
+ ].includes(url.protocol)) throw new Error("unsupported");
1311
+ let repository = url.pathname.replace(/^\//, "").replace(/\.git\/?$/, "").replace(/\/$/, "");
1312
+ if (!url.hostname || !repository.includes("/") || repository.split("/").some((part) => !/^[\w.-]+$/.test(part) || part === "." || part === "..")) throw new Error("unsupported");
1313
+ const provider = ref ? ref.repository.forge : config.provider === "auto" ? url.hostname === "github.com" ? "github" : url.hostname === "gitlab.com" ? "gitlab" : url.hostname === "gitea.com" ? "gitea" : url.hostname === "codeberg.org" ? "forgejo" : void 0 : config.provider;
1314
+ if (!provider || ![
1315
+ "github",
1316
+ "gitlab",
1317
+ "gitea",
1318
+ "forgejo"
1319
+ ].includes(provider)) throw new Error("unsupported");
1320
+ const forge = provider === "gitea" || provider === "forgejo";
1321
+ let host = url.hostname + (url.protocol !== "ssh:" && url.port ? `:${url.port}` : "");
1322
+ let origin = `${url.protocol === "http:" ? "http" : "https"}://${host}`;
1323
+ let login = "";
1324
+ if (forge) {
1325
+ const logins = JSON.parse(await run("tea", [
1326
+ "login",
1327
+ "list",
1328
+ "--output",
1329
+ "json"
1330
+ ]));
1331
+ if (!Array.isArray(logins)) throw new Error("invalid_response");
1332
+ const matches = logins.filter((entry) => {
1333
+ const base = new URL(safeUrl(entry.url));
1334
+ if (base.search || base.hash) throw new Error("invalid_response");
1335
+ if (url.protocol === "ssh:") return new URL(`ssh://${string(entry.ssh_host)}`).hostname === url.hostname && repository.split("/").length === 2;
1336
+ const prefix = base.pathname.replace(/\/$/, "");
1337
+ return base.protocol === url.protocol && base.host === url.host && url.pathname.startsWith(`${prefix}/`) && url.pathname.slice(prefix.length + 1).replace(/\.git\/?$/, "").split("/").length === 2;
1338
+ });
1339
+ if (matches.length !== 1) throw new Error("command_failed");
1340
+ login = string(matches[0].name);
1341
+ if (!login || login.startsWith("-")) throw new Error("invalid_response");
1342
+ const base = new URL(safeUrl(matches[0].url));
1343
+ host = base.host;
1344
+ origin = base.href.replace(/\/$/, "");
1345
+ if (url.protocol !== "ssh:") repository = repository.slice(base.pathname.replace(/^\/|\/$/g, "").length).replace(/^\//, "");
1346
+ }
1347
+ let requestedNumber;
1348
+ let requestedUrl;
1349
+ if (requested) {
1350
+ const prefix = `${new URL(origin).pathname.replace(/\/$/, "")}/${repository}`;
1351
+ const match = requested.pathname.match(provider === "github" ? /^(.*)\/pull\/([1-9]\d*)(?:\/(?:files|commits|checks))?\/?$/ : forge ? /^(.*)\/pulls\/([1-9]\d*)\/?$/ : /^(.*)\/-\/merge_requests\/([1-9]\d*)\/?$/);
1352
+ if (requested.origin !== new URL(origin).origin || provider === "github" && repository.split("/").length !== 2 || !match || !Number.isSafeInteger(Number(match[2]))) throw new Error("unsupported");
1353
+ if (provider === "github" ? match[1].toLowerCase() !== prefix.toLowerCase() : match[1] !== prefix) {
1354
+ if (provider === "gitlab") throw new Error("unsupported");
1355
+ const associated = await list(session, signal, void 0, void 0, summary);
1356
+ const linkedUrl = `${requested.origin}${match[1]}/${provider === "github" ? "pull" : forge ? "pulls" : "-/merge_requests"}/${match[2]}`;
1357
+ if ("request" in associated && associated.request && (provider === "github" ? associated.request.url.toLowerCase() === linkedUrl.toLowerCase() : associated.request.url === linkedUrl)) return associated;
1358
+ throw new Error("unsupported");
1359
+ }
1360
+ requestedNumber = match[2];
1361
+ requestedUrl = `${origin}/${repository}/${provider === "github" ? "pull" : forge ? "pulls" : "-/merge_requests"}/${requestedNumber}`;
1362
+ }
1363
+ const view = {
1364
+ provider,
1365
+ repository: `${host}/${repository}`,
1366
+ branch,
1367
+ request: null
1368
+ };
1369
+ if (!branch && !requested) return view;
1370
+ const mergeRef = tracked ? await git([
1371
+ "config",
1372
+ "--get",
1373
+ `branch.${branch}.merge`
1374
+ ], [0, 1]) : "";
1375
+ const pushedBranch = mergeRef.startsWith("refs/heads/") ? mergeRef.slice(11) : branch;
1376
+ const forgeApi = (endpoint, fields = [], trim = true, options) => run("tea", [
1377
+ "api",
1378
+ "--login",
1379
+ login,
1380
+ "--include",
1381
+ "--output",
1382
+ "-",
1383
+ ...fields,
1384
+ `${origin}/api/v1/${endpoint}`
1385
+ ], fields.length ? "action_failed" : "command_failed", [0], trim, options);
1386
+ const forgePages = async (endpoint) => {
1387
+ const rows = [];
1388
+ for (let page = 1; page <= 20; page++) {
1389
+ const data = JSON.parse(await forgeApi(`${endpoint}${endpoint.includes("?") ? "&" : "?"}limit=50&page=${page}`));
1390
+ if (data === null) return rows;
1391
+ if (!Array.isArray(data)) throw new Error("invalid_response");
1392
+ if (!data.length) return rows;
1393
+ rows.push(...data);
1394
+ }
1395
+ throw new Error("invalid_response");
1396
+ };
1397
+ let forgeRow;
1398
+ let forgeRepository = repository;
1399
+ if (forge && requestedNumber) forgeRow = JSON.parse(await forgeApi(`repos/${repository}/pulls/${requestedNumber}`));
1400
+ else if (forge) {
1401
+ const repo = JSON.parse(await forgeApi(`repos/${repository}`));
1402
+ const targets = [repository];
1403
+ if (repo.parent) {
1404
+ const parent = string(repo.parent.full_name);
1405
+ if (!/^[\w.-]+\/[\w.-]+$/.test(parent)) throw new Error("invalid_response");
1406
+ targets.push(parent);
1407
+ }
1408
+ for (const target of targets) {
1409
+ forgeRow = (await forgePages(`repos/${target}/pulls?state=all&sort=recentupdate`)).find((row) => row?.head?.ref === pushedBranch && row.head.repo?.full_name?.toLowerCase() === repository.toLowerCase() && row.base?.repo?.full_name?.toLowerCase() === target.toLowerCase());
1410
+ if (forgeRow) {
1411
+ forgeRepository = target;
1412
+ break;
1413
+ }
1414
+ }
1415
+ }
1416
+ const output = forge ? JSON.stringify(forgeRow ?? null) : requestedNumber ? provider === "github" ? await run("gh", [
1417
+ "pr",
1418
+ "view",
1419
+ requestedNumber,
1420
+ "--repo",
1421
+ `${origin}/${repository}`,
1422
+ "--json",
1423
+ "number,title,url,author,headRefName,baseRefName,isDraft,state,headRepository,body"
1424
+ ]) : await run("glab", [
1425
+ "mr",
1426
+ "view",
1427
+ requestedNumber,
1428
+ "--repo",
1429
+ `${origin}/${repository}`,
1430
+ "--output",
1431
+ "json"
1432
+ ]) : provider === "github" ? await run("gh", [
1433
+ "pr",
1434
+ "view",
1435
+ "--json",
1436
+ "number,title,url,author,headRefName,baseRefName,isDraft,state,headRepository,body"
1437
+ ]) : await run("glab", [
1438
+ "mr",
1439
+ "list",
1440
+ "--repo",
1441
+ `${origin}/${repository}`,
1442
+ "--source-branch",
1443
+ pushedBranch,
1444
+ "--all",
1445
+ "--output",
1446
+ "json",
1447
+ "--per-page",
1448
+ "1",
1449
+ "--page",
1450
+ "1",
1451
+ "--order",
1452
+ "updated_at",
1453
+ "--sort",
1454
+ "desc"
1455
+ ]);
1456
+ try {
1457
+ const data = JSON.parse(output || "null");
1458
+ if (provider === "gitlab" && !requested && (!Array.isArray(data) || data.length > 1)) throw new Error();
1459
+ const row = provider === "gitlab" && !requested ? data[0] : data;
1460
+ if (row == null) {
1461
+ if (requested) throw new Error();
1462
+ return view;
1463
+ }
1464
+ const state = forge && row.merged ? "merged" : row.state === "opened" ? "open" : row.state?.toLowerCase();
1465
+ if (![
1466
+ "open",
1467
+ "closed",
1468
+ "merged"
1469
+ ].includes(state)) throw new Error();
1470
+ const item = {
1471
+ number: provider === "gitlab" ? row.iid : row.number,
1472
+ title: row.title,
1473
+ url: forge ? row.html_url : provider === "github" ? row.url : row.web_url,
1474
+ author: (forge ? row.user?.login : provider === "github" ? row.author?.login : row.author?.username) ?? "",
1475
+ source: forge ? row.head.ref : provider === "github" ? row.headRefName : row.source_branch,
1476
+ target: forge ? row.base.ref : provider === "github" ? row.baseRefName : row.target_branch,
1477
+ draft: provider === "github" ? row.isDraft : row.draft ?? row.work_in_progress ?? false,
1478
+ state,
1479
+ body: "",
1480
+ headSha: "",
1481
+ comments: [],
1482
+ reviews: []
1483
+ };
1484
+ if (!Number.isSafeInteger(item.number) || item.number <= 0 || ![
1485
+ "title",
1486
+ "url",
1487
+ "author",
1488
+ "source",
1489
+ "target"
1490
+ ].every((key) => typeof item[key] === "string") || typeof item.draft !== "boolean") throw new Error();
1491
+ if (requested && ((provider === "github" ? item.url.toLowerCase() !== requestedUrl?.toLowerCase() : item.url !== requestedUrl) || String(item.number) !== requestedNumber)) throw new Error();
1492
+ const link = new URL(item.url);
1493
+ if (link.origin !== new URL(origin).origin || link.username || link.password || link.search || link.hash || !(forge ? link.href === `${origin}/${forgeRepository}/pulls/${item.number}` : provider === "github" ? /^\/[\w.-]+\/[\w.-]+\/pull\/\d+$/.test(link.pathname) && link.pathname.endsWith(`/pull/${item.number}`) : link.pathname === `/${repository}/-/merge_requests/${item.number}`)) throw new Error();
1494
+ if (!requested && (item.source !== pushedBranch || provider === "github" && row.headRepository?.nameWithOwner?.toLowerCase() !== repository.toLowerCase() || provider === "gitlab" && (!Number.isSafeInteger(row.source_project_id) || row.source_project_id <= 0 || row.source_project_id !== row.target_project_id))) return view;
1495
+ if (ref) view.branch = item.source;
1496
+ if (summary && !action) {
1497
+ item.body = string((provider === "gitlab" ? row.description : row.body) ?? "");
1498
+ return {
1499
+ ...view,
1500
+ request: item
1501
+ };
1502
+ }
1503
+ const targetRepo = provider === "github" ? `${origin}/${link.pathname.split("/").slice(1, 3).join("/")}` : `${origin}/${repository}`;
1504
+ const number = String(item.number);
1505
+ const api = (suffix) => run("glab", [
1506
+ "api",
1507
+ "--hostname",
1508
+ host,
1509
+ `projects/${encodeURIComponent(repository)}/merge_requests/${number}${suffix}`
1510
+ ]);
1511
+ const pages = async (endpoint) => {
1512
+ const rows = [];
1513
+ for (let page = 1; page <= 10; page++) {
1514
+ const data = JSON.parse(await run("glab", [
1515
+ "api",
1516
+ "--hostname",
1517
+ host,
1518
+ `${endpoint}${endpoint.includes("?") ? "&" : "?"}per_page=100&page=${page}`
1519
+ ]));
1520
+ if (!Array.isArray(data)) throw new Error();
1521
+ rows.push(...data);
1522
+ if (data.length < 100) return rows;
1523
+ }
1524
+ throw new Error();
1525
+ };
1526
+ const endpoint = `projects/${encodeURIComponent(repository)}/merge_requests/${number}`;
1527
+ const forgeEndpoint = `repos/${forgeRepository}/pulls/${number}`;
1528
+ const section = async (read) => {
1529
+ try {
1530
+ await read();
1531
+ } catch {
1532
+ item.detailsError = true;
1533
+ }
1534
+ };
1535
+ try {
1536
+ if (forge) {
1537
+ const detail = JSON.parse(await forgeApi(forgeEndpoint));
1538
+ if (detail.number !== item.number || detail.html_url !== item.url || detail.head?.ref !== item.source || detail.base?.ref !== item.target || detail.head.repo?.full_name?.toLowerCase() !== (requested ? row.head.repo?.full_name?.toLowerCase() : repository.toLowerCase()) || detail.base.repo?.full_name?.toLowerCase() !== forgeRepository.toLowerCase() || !["open", "closed"].includes(detail.state) || typeof detail.merged !== "boolean" || typeof detail.draft !== "boolean") throw new Error();
1539
+ item.headSha = string(detail.head.sha);
1540
+ if (!/^[a-fA-F0-9]{40,64}$/.test(item.headSha)) throw new Error();
1541
+ item.state = detail.merged ? "merged" : detail.state;
1542
+ item.draft = detail.draft;
1543
+ await section(() => {
1544
+ item.body = string(detail.body ?? "");
1545
+ });
1546
+ await section(async () => {
1547
+ const reviews = await forgePages(`${forgeEndpoint}/reviews`);
1548
+ item.reviews = reviews.map((review) => ({
1549
+ author: string(review.user?.login ?? ""),
1550
+ body: string(review.body),
1551
+ state: string(review.state)
1552
+ }));
1553
+ });
1554
+ await section(async () => {
1555
+ const comments = JSON.parse(await forgeApi(`repos/${forgeRepository}/issues/${number}/comments`));
1556
+ item.comments = comments.map((comment) => ({
1557
+ author: string(comment.user?.login ?? ""),
1558
+ body: string(comment.body),
1559
+ url: safeUrl(comment.html_url)
1560
+ }));
1561
+ });
1562
+ } else if (provider === "github") {
1563
+ const detail = JSON.parse(await run("gh", [
1564
+ "pr",
1565
+ "view",
1566
+ item.url,
1567
+ "--repo",
1568
+ targetRepo,
1569
+ "--json",
1570
+ "number,url,state,isDraft,headRefName,headRepository,body,headRefOid,comments,reviews"
1571
+ ]));
1572
+ if (detail.number !== item.number || detail.url !== item.url || detail.headRefName !== item.source || detail.headRepository?.nameWithOwner?.toLowerCase() !== (requested ? row.headRepository?.nameWithOwner?.toLowerCase() : repository.toLowerCase())) throw new Error();
1573
+ item.headSha = string(detail.headRefOid);
1574
+ if (![
1575
+ "OPEN",
1576
+ "CLOSED",
1577
+ "MERGED"
1578
+ ].includes(detail.state) || typeof detail.isDraft !== "boolean") throw new Error();
1579
+ item.state = detail.state.toLowerCase();
1580
+ item.draft = detail.isDraft;
1581
+ await section(() => {
1582
+ item.body = string(detail.body);
1583
+ });
1584
+ await section(() => {
1585
+ item.comments = detail.comments.map((comment) => ({
1586
+ author: string(comment.author?.login ?? ""),
1587
+ body: string(comment.body),
1588
+ url: safeUrl(comment.url)
1589
+ }));
1590
+ if (item.comments.length >= 100) throw new Error();
1591
+ });
1592
+ await section(() => {
1593
+ item.reviews = detail.reviews.map((review) => ({
1594
+ author: string(review.author?.login ?? ""),
1595
+ body: string(review.body),
1596
+ state: string(review.state)
1597
+ }));
1598
+ if (item.reviews.length >= 100) throw new Error();
1599
+ });
1600
+ } else {
1601
+ const detail = JSON.parse(await run("glab", [
1602
+ "mr",
1603
+ "view",
1604
+ number,
1605
+ "--repo",
1606
+ targetRepo,
1607
+ "--output",
1608
+ "json"
1609
+ ]));
1610
+ if (detail.iid !== item.number || detail.web_url !== item.url || detail.source_branch !== item.source || detail.source_project_id !== row.source_project_id || detail.target_project_id !== row.target_project_id) throw new Error();
1611
+ item.headSha = string(detail.sha ?? detail.diff_refs?.head_sha);
1612
+ if (![
1613
+ "opened",
1614
+ "closed",
1615
+ "merged"
1616
+ ].includes(detail.state)) throw new Error();
1617
+ item.state = detail.state === "opened" ? "open" : detail.state;
1618
+ item.draft = detail.draft ?? detail.work_in_progress ?? false;
1619
+ if (typeof item.draft !== "boolean") throw new Error();
1620
+ await section(() => {
1621
+ item.body = string(detail.description ?? "");
1622
+ });
1623
+ await section(async () => {
1624
+ const approvals = JSON.parse(await api("/approvals"));
1625
+ if (!Array.isArray(approvals.approved_by)) throw new Error();
1626
+ item.reviews = approvals.approved_by.map((entry) => ({
1627
+ author: string(entry.user?.username),
1628
+ body: "",
1629
+ state: "APPROVED"
1630
+ }));
1631
+ });
1632
+ await section(async () => {
1633
+ const notes = await pages(`${endpoint}/notes?sort=asc`);
1634
+ item.comments = notes.filter((note) => !note.system).map((note) => {
1635
+ if (!Number.isSafeInteger(note.id) || note.id <= 0) throw new Error();
1636
+ return {
1637
+ author: string(note.author?.username ?? ""),
1638
+ body: string(note.body),
1639
+ url: `${item.url}#note_${note.id}`
1640
+ };
1641
+ });
1642
+ });
1643
+ }
1644
+ if (!/^[a-fA-F0-9]{40,64}$/.test(item.headSha)) throw new Error();
1645
+ if (!action || action.action === "approve") {
1646
+ const changesSignal = AbortSignal.any([signal, AbortSignal.timeout(5e3)]);
1647
+ item.changes = await readChanges({
1648
+ provider,
1649
+ github: async () => {
1650
+ const detail = JSON.parse(await run("gh", [
1651
+ "pr",
1652
+ "view",
1653
+ item.url,
1654
+ "--repo",
1655
+ targetRepo,
1656
+ "--json",
1657
+ "changedFiles,files"
1658
+ ], "command_failed", [0], true, { signal: changesSignal }));
1659
+ const patch = await run("gh", [
1660
+ "pr",
1661
+ "diff",
1662
+ item.url,
1663
+ "--repo",
1664
+ targetRepo,
1665
+ "--color",
1666
+ "never"
1667
+ ], "command_failed", [0], false, { signal: changesSignal });
1668
+ return {
1669
+ files: detail.files,
1670
+ changedFiles: detail.changedFiles,
1671
+ diff: patch
1672
+ };
1673
+ },
1674
+ gitlab: async () => JSON.parse(await run("glab", [
1675
+ "api",
1676
+ "--hostname",
1677
+ host,
1678
+ `${endpoint}/changes`
1679
+ ], "command_failed", [0], true, { signal: changesSignal })),
1680
+ forge: async () => {
1681
+ const files = [];
1682
+ let total;
1683
+ for (let page = 1; page <= 3; page++) {
1684
+ let count;
1685
+ const raw = await forgeApi(`${forgeEndpoint}/files?limit=50&page=${page}`, [], true, {
1686
+ signal: changesSignal,
1687
+ headers: (headers) => {
1688
+ const matches = [...headers.matchAll(/^x-total-count:\s*(\d+)\s*$/gim)];
1689
+ if (matches.length === 1) count = Number(matches[0][1]);
1690
+ }
1691
+ });
1692
+ if (!Number.isSafeInteger(count) || count > 100 || total !== void 0 && count !== total) throw new Error("invalid_response");
1693
+ total = count;
1694
+ const rows = JSON.parse(raw);
1695
+ if (rows !== null && !Array.isArray(rows)) throw new Error("invalid_response");
1696
+ files.push(...rows ?? []);
1697
+ if (files.length > 100 || files.length > total) throw new Error("invalid_response");
1698
+ if (files.length === total) return {
1699
+ files,
1700
+ changedFiles: total,
1701
+ diff: await forgeApi(`${forgeEndpoint}.diff`, [], false, { signal: changesSignal })
1702
+ };
1703
+ if (!rows?.length) throw new Error("invalid_response");
1704
+ }
1705
+ throw new Error("invalid_response");
1706
+ }
1707
+ });
1708
+ }
1709
+ const latest = JSON.parse(await (forge ? forgeApi(forgeEndpoint) : provider === "github" ? run("gh", [
1710
+ "pr",
1711
+ "view",
1712
+ item.url,
1713
+ "--repo",
1714
+ targetRepo,
1715
+ "--json",
1716
+ "headRefOid"
1717
+ ]) : run("glab", [
1718
+ "mr",
1719
+ "view",
1720
+ number,
1721
+ "--repo",
1722
+ targetRepo,
1723
+ "--output",
1724
+ "json"
1725
+ ])));
1726
+ if ((forge ? latest.head?.sha : provider === "github" ? latest.headRefOid : latest.sha ?? latest.diff_refs?.head_sha) !== item.headSha) throw new Error();
1727
+ } catch {
1728
+ item.detailsError = true;
1729
+ }
1730
+ if (provider === "github" && (!action || action.action === "merge") && !item.detailsError && item.state === "open" && !item.draft) try {
1731
+ const statusRef = ctx.forge.changeRequestFromUrl(item.url);
1732
+ if (statusRef && ctx.forge.changeRequestUrl(statusRef) === item.url) {
1733
+ const status = await ctx.forge.fetchChecks(statusRef, signal);
1734
+ const methods = mergeMethods("headSha" in status && ctx.forge.changeRequestUrl(status.ref) === item.url ? status : void 0, item);
1735
+ if (methods.length) {
1736
+ const [owner, name] = link.pathname.split("/").slice(1, 3);
1737
+ if (completeChecks(JSON.parse(await run("gh", [
1738
+ "api",
1739
+ "--hostname",
1740
+ host,
1741
+ "graphql",
1742
+ "-f",
1743
+ `query=${checksQuery}`,
1744
+ "-f",
1745
+ `owner=${owner}`,
1746
+ "-f",
1747
+ `name=${name}`,
1748
+ "-F",
1749
+ `number=${number}`
1750
+ ])), item.headSha)) {
1751
+ item.mergeMethods = methods;
1752
+ view.checkoutBranch = ref && !action ? await git([
1753
+ "symbolic-ref",
1754
+ "--quiet",
1755
+ "--short",
1756
+ "HEAD"
1757
+ ], [0, 1]) : branch;
1758
+ }
1759
+ }
1760
+ }
1761
+ } catch {}
1762
+ if (action) {
1763
+ if (item.url !== action.requestUrl || item.headSha !== action.headSha || action.action === "merge" && item.target !== action.target) throw new Error("stale_request");
1764
+ if (action.action === "merge" && (provider !== "github" || !action.strategy || !item.mergeMethods?.includes(action.strategy) || !branch || branch !== action.branch)) throw new Error("action_failed");
1765
+ if (item.detailsError || item.state !== "open") throw new Error("action_failed");
1766
+ if (action.action === "approve" && (item.draft || !item.changes?.complete)) throw new Error("action_failed");
1767
+ if (await git([
1768
+ "symbolic-ref",
1769
+ "--quiet",
1770
+ "--short",
1771
+ "HEAD"
1772
+ ], [0, 1]) !== branch) throw new Error("stale_request");
1773
+ if (forge) {
1774
+ if (action.action === "merge") throw new Error("action_failed");
1775
+ const fields = [
1776
+ "--method",
1777
+ "POST",
1778
+ "-f",
1779
+ `body=${action.body ?? ""}`
1780
+ ];
1781
+ if (action.action !== "comment") fields.push("-f", `commit_id=${action.headSha}`, "-f", `event=${action.action === "approve" ? "APPROVED" : "REQUEST_CHANGES"}`);
1782
+ const response = JSON.parse(await forgeApi(action.action === "comment" ? `repos/${forgeRepository}/issues/${number}/comments` : `${forgeEndpoint}/reviews`, fields));
1783
+ if (!Number.isSafeInteger(response.id) || response.id <= 0 || action.action !== "comment" && (response.commit_id !== action.headSha || response.stale || response.dismissed)) throw new Error("action_failed");
1784
+ } else if (provider === "github" && action.action === "merge") {
1785
+ if (JSON.parse(await run("gh", [
1786
+ "api",
1787
+ "--hostname",
1788
+ host,
1789
+ `repos/${link.pathname.split("/").slice(1, 3).join("/")}/pulls/${number}/merge`,
1790
+ "--method",
1791
+ "PUT",
1792
+ "-f",
1793
+ `sha=${action.headSha}`,
1794
+ "-f",
1795
+ `merge_method=${action.strategy}`
1796
+ ], "action_failed"))?.merged !== true) throw new Error("action_failed");
1797
+ } else if (provider === "github") {
1798
+ const base = [
1799
+ "api",
1800
+ "--hostname",
1801
+ host,
1802
+ `repos/${link.pathname.split("/").slice(1, 3).join("/")}/pulls/${number}/reviews`,
1803
+ "--method",
1804
+ "POST",
1805
+ "-f",
1806
+ `event=${action.action === "approve" ? "APPROVE" : action.action === "comment" ? "COMMENT" : "REQUEST_CHANGES"}`,
1807
+ "-f",
1808
+ `commit_id=${action.headSha}`
1809
+ ];
1810
+ if (action.body !== void 0) base.push("-f", `body=${action.body}`);
1811
+ await run("gh", base, "action_failed");
1812
+ } else {
1813
+ if (action.action === "merge") throw new Error("action_failed");
1814
+ if (action.action === "request_changes" || action.action === "approve" && action.body?.trim()) throw new Error("unsupported_action");
1815
+ const base = [
1816
+ "mr",
1817
+ action.action === "comment" ? "note" : action.action,
1818
+ number,
1819
+ "--repo",
1820
+ targetRepo
1821
+ ];
1822
+ if (action.action === "comment") base.push("--message", action.body);
1823
+ else base.push("--sha", action.headSha);
1824
+ await run("glab", base, "action_failed");
1825
+ }
1826
+ return { completed: true };
1827
+ }
1828
+ return {
1829
+ ...view,
1830
+ request: item
1831
+ };
1832
+ } catch (error) {
1833
+ if (error instanceof Error && [
1834
+ "stale_request",
1835
+ "action_failed",
1836
+ "unsupported_action"
1837
+ ].includes(error.message)) throw error;
1838
+ throw new Error(action ? "action_failed" : "invalid_response");
1839
+ }
1840
+ };
1841
+ for (const route of [method, actionMethod]) ctx.effect(() => ctx.connection.fetch.register({
1842
+ path: `${channel}/${route}`,
1843
+ methods: ["POST"],
1844
+ requestBody: "buffered",
1845
+ async fetch(request) {
1846
+ const parsed = await parseRpcRequest(request, route);
1847
+ if (!parsed) return new Response("Invalid request", { status: 400 });
1848
+ const reply = (result) => rpcResponse(parsed.rpcId, result);
1849
+ const input = parsed.payload;
1850
+ if (!input || typeof input.sessionId !== "string" || !input.sessionId) return reply({
1851
+ ok: false,
1852
+ error: {
1853
+ code: "unavailable",
1854
+ message: "Invalid session",
1855
+ details: {}
1856
+ }
1857
+ });
1858
+ let inFlight = [];
1859
+ try {
1860
+ let action;
1861
+ if (route === "dungsil-forge-pulls/pull-requests/action") {
1862
+ try {
1863
+ action = actionInput(parsed.payload);
1864
+ } catch {
1865
+ throw new Error("invalid_payload");
1866
+ }
1867
+ const keys = [`session:${action.sessionId}`];
1868
+ if (action.action === "merge") keys.push(`request:${action.requestUrl.toLowerCase()}`);
1869
+ if (keys.some((key) => actionsInFlight.has(key))) throw new Error("action_failed");
1870
+ keys.forEach((key) => actionsInFlight.add(key));
1871
+ inFlight = keys;
1872
+ }
1873
+ const requested = route === "dungsil-forge-pulls/pull-requests/list" && input.requestUrl !== void 0 ? lookupUrl(input.requestUrl) : void 0;
1874
+ const signal = AbortSignal.any([
1875
+ request.signal,
1876
+ lifetime.signal,
1877
+ AbortSignal.timeout(2e4)
1878
+ ]);
1879
+ const sessionId = SessionId(input.sessionId);
1880
+ const execute = async () => {
1881
+ signal.throwIfAborted();
1882
+ let session;
1883
+ if (action) {
1884
+ const resolved = await ctx.sessionController.resolveAgent(sessionId);
1885
+ if ("error" in resolved) throw new Error("unavailable");
1886
+ signal.throwIfAborted();
1887
+ session = resolved.agent.session;
1888
+ } else session = await inspectSession(ctx, sessionId, signal);
1889
+ return list(session, signal, action, requested, input.summary === true);
1890
+ };
1891
+ const value = action ? await execute() : await read(signal, execute);
1892
+ if (action && !("completed" in value)) throw new Error("stale_request");
1893
+ return reply({
1894
+ ok: true,
1895
+ value
1896
+ });
1897
+ } catch (error) {
1898
+ return reply({
1899
+ ok: false,
1900
+ error: {
1901
+ code: error instanceof Error && [
1902
+ "repository",
1903
+ "unsupported",
1904
+ "cli_missing",
1905
+ "command_failed",
1906
+ "invalid_response",
1907
+ "invalid_payload",
1908
+ "stale_request",
1909
+ "action_failed",
1910
+ "unsupported_action"
1911
+ ].includes(error.message) ? error.message : "unavailable",
1912
+ message: route === "dungsil-forge-pulls/pull-requests/action" ? "Request action failed; refresh before trying again" : "Request lookup failed",
1913
+ details: {}
1914
+ }
1915
+ });
1916
+ } finally {
1917
+ inFlight.forEach((key) => actionsInFlight.delete(key));
1918
+ }
1919
+ }
1920
+ }));
1921
+ }
1922
+ export { Config, apply, inject, name };