consortium
Version:
Remote control and session sharing CLI for AI coding agents
499 lines (486 loc) • 12.7 kB
JavaScript
class PromiseResolver {
#promise;
get promise() {
return this.#promise;
}
#resolve;
#reject;
#state = "running";
get state() {
return this.#state;
}
constructor() {
this.#promise = new Promise((resolve, reject) => {
this.#resolve = resolve;
this.#reject = reject;
});
}
resolve = (value) => {
this.#resolve(value);
this.#state = "resolved";
};
reject = (reason) => {
this.#reject(reason);
this.#state = "rejected";
};
}
function isPromiseLike(value) {
return typeof value === "object" && value !== null && "then" in value;
}
const { AbortController } = globalThis;
const ReadableStream = /* @__PURE__ */ (() => {
const { ReadableStream: ReadableStream2 } = globalThis;
if (!ReadableStream2.from) {
ReadableStream2.from = function(iterable) {
const iterator = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();
return new ReadableStream2({
async pull(controller) {
const result = await iterator.next();
if (result.done) {
controller.close();
return;
}
controller.enqueue(result.value);
},
async cancel(reason) {
await iterator.return?.(reason);
}
});
};
}
if (!ReadableStream2.prototype[Symbol.asyncIterator] || !ReadableStream2.prototype.values) {
ReadableStream2.prototype.values = async function* (options) {
const reader = this.getReader();
try {
while (true) {
const { done, value } = await reader.read();
if (done) {
return;
}
yield value;
}
} finally {
if (!options?.preventCancel) {
await reader.cancel();
}
reader.releaseLock();
}
};
ReadableStream2.prototype[Symbol.asyncIterator] = // eslint-disable-next-line @typescript-eslint/unbound-method
ReadableStream2.prototype.values;
}
return ReadableStream2;
})();
const { WritableStream, TransformStream } = globalThis;
class TaskQueue {
#ready;
#disposed = false;
enqueue(task, bail = false) {
if (this.#disposed) {
throw new Error("TaskQueue is disposed");
}
if (!this.#ready) {
try {
const result2 = task();
if (isPromiseLike(result2)) {
this.#ready = result2.then(() => {
}, (e) => {
if (bail) {
throw e;
}
});
}
return result2;
} catch (e) {
if (bail) {
const promise = Promise.reject(e);
void promise.catch(() => {
});
this.#ready = promise;
}
throw e;
}
}
const result = this.#ready.then(() => {
if (this.#disposed) {
throw new Error("TaskQueue is disposed");
}
return task();
});
this.#ready = result.then(() => {
}, (e) => {
if (bail || this.#disposed) {
throw e;
}
});
return result;
}
dispose() {
this.#disposed = true;
}
}
class PushReadableStream extends ReadableStream {
/**
* Create a new `PushReadableStream` from a source.
*
* @param source If `source` returns a `Promise`, the stream will be closed
* when the `Promise` is resolved, and be errored when the `Promise` is rejected.
* @param strategy
*/
constructor(source, strategy, logger) {
let controller;
const tasks = new TaskQueue();
let zeroHighWaterMarkAllowEnqueue = false;
let waterMarkLow;
const abortController = new AbortController();
let stopped = false;
const enqueue = (chunk) => {
logger?.({
source: "producer",
operation: "enqueue",
value: chunk,
phase: "start"
});
if (abortController.signal.aborted) {
logger?.({
source: "producer",
operation: "enqueue",
value: chunk,
phase: "ignored"
});
return false;
}
if (controller.desiredSize === null) {
controller.enqueue(chunk);
throw new Error("unreachable");
}
if (zeroHighWaterMarkAllowEnqueue) {
zeroHighWaterMarkAllowEnqueue = false;
controller.enqueue(chunk);
logger?.({
source: "producer",
operation: "enqueue",
value: chunk,
phase: "complete"
});
return true;
}
if (controller.desiredSize <= 0) {
logger?.({
source: "producer",
operation: "enqueue",
value: chunk,
phase: "waiting"
});
waterMarkLow = new PromiseResolver();
return waterMarkLow.promise.then(() => {
controller.enqueue(chunk);
logger?.({
source: "producer",
operation: "enqueue",
value: chunk,
phase: "complete"
});
return true;
}, () => {
logger?.({
source: "producer",
operation: "enqueue",
value: chunk,
phase: "ignored"
});
return false;
});
}
controller.enqueue(chunk);
logger?.({
source: "producer",
operation: "enqueue",
value: chunk,
phase: "complete"
});
return true;
};
const close = (explicit) => {
logger?.({
source: "producer",
operation: "close",
explicit,
phase: "start"
});
if (abortController.signal.aborted || stopped && !explicit) {
logger?.({
source: "producer",
operation: "close",
explicit,
phase: "ignored"
});
return;
}
controller.close();
stopped = true;
waterMarkLow?.reject();
logger?.({
source: "producer",
operation: "close",
explicit,
phase: "complete"
});
};
const error = (error2, explicit) => {
logger?.({
source: "producer",
operation: "error",
explicit,
phase: "start"
});
stopped = true;
controller.error(error2);
waterMarkLow?.reject();
logger?.({
source: "producer",
operation: "error",
explicit,
phase: "complete"
});
};
super({
start: (controller_) => {
controller = controller_;
const result = source({
abortSignal: abortController.signal,
enqueue: async (chunk) => (
// Run `enqueue`s in serial
// Use `async/await` to always return a `Promise`
await tasks.enqueue(() => enqueue(chunk))
),
close() {
close(true);
},
error(e) {
error(e, true);
}
});
if (!stopped && isPromiseLike(result)) {
result.then(() => close(false), (e) => error(e, false));
}
},
pull: () => {
logger?.({
source: "consumer",
operation: "pull",
phase: "start"
});
if (waterMarkLow) {
waterMarkLow.resolve(void 0);
waterMarkLow = void 0;
} else if (strategy?.highWaterMark === 0) {
zeroHighWaterMarkAllowEnqueue = true;
}
logger?.({
source: "consumer",
operation: "pull",
phase: "complete"
});
},
cancel: (reason) => {
logger?.({
source: "consumer",
operation: "cancel",
phase: "start"
});
stopped = true;
abortController.abort(reason);
waterMarkLow?.reject();
logger?.({
source: "consumer",
operation: "cancel",
phase: "complete"
});
}
}, strategy);
}
}
function tryClose(value) {
try {
const result = value.close();
if (isPromiseLike(result)) {
return result.then(() => true, () => false);
}
return true;
} catch {
return false;
}
}
async function tryCancel(stream) {
try {
await stream.cancel();
return true;
} catch {
return false;
}
}
class ConsumableReadableStream extends ReadableStream {
static async enqueue(controller, chunk) {
const output = new Consumable(chunk);
controller.enqueue(output);
await output.consumed;
}
constructor(source, strategy) {
let wrappedController;
let wrappedStrategy;
if (strategy) {
wrappedStrategy = {};
if ("highWaterMark" in strategy) {
wrappedStrategy.highWaterMark = strategy.highWaterMark;
}
if ("size" in strategy) {
wrappedStrategy.size = (chunk) => {
return strategy.size(chunk.value);
};
}
}
super({
start(controller) {
wrappedController = {
enqueue(chunk) {
return ConsumableReadableStream.enqueue(controller, chunk);
},
close() {
controller.close();
},
error(reason) {
controller.error(reason);
}
};
return source.start?.(wrappedController);
},
pull() {
return source.pull?.(wrappedController);
},
cancel(reason) {
return source.cancel?.(reason);
}
}, wrappedStrategy);
}
}
class ConsumableWrapByteReadableStream extends ReadableStream {
constructor(stream, chunkSize, min) {
const reader = stream.getReader({ mode: "byob" });
let array = new Uint8Array(chunkSize);
super({
async pull(controller) {
const { done, value } = await reader.read(array, { min });
if (done) {
controller.close();
return;
}
await ConsumableReadableStream.enqueue(controller, value);
array = new Uint8Array(value.buffer);
},
cancel(reason) {
return reader.cancel(reason);
}
});
}
}
class ConsumableWrapWritableStream extends WritableStream {
constructor(stream) {
const writer = stream.getWriter();
super({
write(chunk) {
return chunk.tryConsume((chunk2) => writer.write(chunk2));
},
abort(reason) {
return writer.abort(reason);
},
close() {
return writer.close();
}
});
}
}
class ConsumableWritableStream extends WritableStream {
static async write(writer, value) {
const consumable = new Consumable(value);
await writer.write(consumable);
await consumable.consumed;
}
constructor(sink, strategy) {
let wrappedStrategy;
if (strategy) {
wrappedStrategy = {};
if ("highWaterMark" in strategy) {
wrappedStrategy.highWaterMark = strategy.highWaterMark;
}
if ("size" in strategy) {
wrappedStrategy.size = (chunk) => {
return strategy.size(chunk instanceof Consumable ? chunk.value : chunk);
};
}
}
super({
start(controller) {
return sink.start?.(controller);
},
write(chunk, controller) {
return chunk.tryConsume((chunk2) => sink.write?.(chunk2, controller));
},
abort(reason) {
return sink.abort?.(reason);
},
close() {
return sink.close?.();
}
}, wrappedStrategy);
}
}
const { console } = globalThis;
const createTask = /* @__PURE__ */ (() => console?.createTask?.bind(console) ?? (() => ({
run(callback) {
return callback();
}
})))();
class Consumable {
static WritableStream = ConsumableWritableStream;
static WrapWritableStream = ConsumableWrapWritableStream;
static ReadableStream = ConsumableReadableStream;
static WrapByteReadableStream = ConsumableWrapByteReadableStream;
#task;
#resolver;
value;
consumed;
constructor(value) {
this.#task = createTask("Consumable");
this.value = value;
this.#resolver = new PromiseResolver();
this.consumed = this.#resolver.promise;
}
consume() {
this.#resolver.resolve();
}
error(error) {
this.#resolver.reject(error);
}
tryConsume(callback) {
try {
let result = this.#task.run(() => callback(this.value));
if (isPromiseLike(result)) {
result = result.then((value) => {
this.#resolver.resolve();
return value;
}, (e) => {
this.#resolver.reject(e);
throw e;
});
} else {
this.#resolver.resolve();
}
return result;
} catch (e) {
this.#resolver.reject(e);
throw e;
}
}
}
export { AbortController as A, Consumable as C, PushReadableStream as P, ReadableStream as R, TransformStream as T, WritableStream as W, tryClose as a, PromiseResolver as b, createTask as c, isPromiseLike as i, tryCancel as t };