@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
236 lines • 10.2 kB
JavaScript
import { isSessionControlDeliveryDetails, SESSION_CONTROL_DELIVERY_TYPE, } from "./extensions/session-control-types.js";
import { markInputTurnOrigin } from "./turn-origin.js";
export class ExternalAdmission {
constructor(port) {
this.turnEpochValue = 0;
this.pending = new Map();
this.emitted = new Set();
this.failed = new Map();
this.fileTakesWrites = true;
this.emittedListeners = new Set();
this.inputHolds = new Set();
this.settledListeners = new Set();
this.port = port;
}
get turnEpoch() {
return this.turnEpochValue;
}
/** Why admission is closed (a release or a graceful close took the session); `undefined` while it admits. */
get closed() {
return this.closedReason;
}
get hasInputWork() {
return this.inputHolds.size > 0;
}
/** Called when an agent run begins; a steer names the epoch it was meant for. */
beginTurn() {
this.turnEpochValue += 1;
}
/** The terminal whose submitted-but-untaken input holds admissions; `undefined` detaches it (never held). */
setEditorSource(source) {
this.editorSource = source;
}
/**
* Holds admission while user input is on its way into the runtime: from `prompt()` entry until the
* prompt reports a disposition or returns. A `command` hold (an extension or built-in command that
* may submit text after an await) also ends as soon as a prompt the command submitted - one from
* an extension (`submittedByCommand`) that began while it was open - is accepted. Ending a hold is
* idempotent; the last one to end notifies `onInputsSettled`.
*/
beginInput(options = {}) {
const parents = options.submittedByCommand ? [...this.inputHolds].filter((hold) => hold.command) : [];
const state = { command: options.command === true };
this.inputHolds.add(state);
const end = () => this.endHold(state);
return {
accepted: () => {
end();
for (const parent of parents)
this.endHold(parent);
},
end,
};
}
onInputsSettled(listener) {
this.settledListeners.add(listener);
return () => this.settledListeners.delete(listener);
}
onEmitted(listener) {
this.emittedListeners.add(listener);
return () => this.emittedListeners.delete(listener);
}
/** Durable custody will replay this delivery: reserve its id before asynchronous recovery or gateway admission. */
restoreQueued(deliveryId, isOwned) {
if (this.pending.has(deliveryId) || this.emitted.has(deliveryId) || this.failed.has(deliveryId))
return;
// Recovery chooses the payload's queue lane; this reservation only tracks durable ownership.
this.pending.set(deliveryId, isOwned);
}
/**
* From here on every `admit` throws `reason` and changes nothing: the runtime is being handed to
* another writer, so the delivery stays with its sender and is delivered there instead.
*/
close(reason) {
this.closedReason ??= reason;
}
/** Undoes `close` when the hand-over it was closed for did not happen. */
reopen() {
this.closedReason = undefined;
}
gate() {
const editor = this.editorSource?.() ?? { revision: 0 };
const base = { editor_revision: editor.revision, turn_epoch: this.turnEpochValue };
if (this.inputHolds.size > 0)
return { can_admit: false, hold_reason: "draft", ...base };
return editor.hold_reason === undefined
? { can_admit: true, ...base }
: { can_admit: false, hold_reason: editor.hold_reason, ...base };
}
admit(input, stamp = {}) {
if (this.closedReason !== undefined)
throw new Error(this.closedReason);
const turn_epoch = this.turnEpochValue;
const id = input.delivery_id;
this.releaseRestored();
if (this.pending.has(id) || this.emitted.has(id) || this.failed.has(id)) {
return { kind: "already_admitted", turn_epoch };
}
if (!this.gate().can_admit)
return { kind: "held_draft", turn_epoch };
if (input.expected_turn_id !== undefined && input.expected_turn_id !== turn_epoch) {
return { kind: "turn_conflict", turn_epoch };
}
const message = deliveryMessage(input, stamp);
if (!this.isBusy() && input.whenIdle !== "queue") {
const holds = this.port.heldBy();
this.pending.set(id, "start");
// A start that settles without writing the entry left it queued for later (the runtime's
// admission-retention path): from then on it is held like any queued delivery.
void this.port.start(message).finally(() => {
if (this.pending.get(id) === "start")
this.pending.set(id, "followUp");
});
// A held start is kept as a notice and starts once its hold is released: the sender is told it waits (senpi#6490).
return holds.length > 0 ? { kind: "held", holds: [...holds], turn_epoch } : { kind: "started", turn_epoch };
}
if (input.deliverAs === "steer" && this.isBusy()) {
if (input.expected_turn_id === undefined)
return { kind: "turn_conflict", turn_epoch };
this.pending.set(id, "steer");
this.port.enqueue(message, "steer");
return { kind: "steered", turn_epoch };
}
// Mid-turn follow-up, or input an idle session holds for its next turn in the mode it was sent as.
const mode = this.isBusy() ? "followUp" : input.deliverAs;
this.pending.set(id, mode);
this.port.enqueue(message, mode);
return { kind: "queued", turn_epoch };
}
list() {
this.releaseRestored();
const deliveries = { pending: [...this.pending.keys()], emitted: [...this.emitted] };
if (this.failed.size === 0)
return deliveries;
const failed = [...this.failed].map(([delivery_id, error]) => ({ delivery_id, error }));
return { ...deliveries, failed };
}
/** A message's transcript entry was written: the file takes writes; a delivery's own entry makes it emitted. */
observePersisted(message) {
this.fileTakesWrites = true;
const id = deliveryIdOf(message);
if (id === undefined || this.emitted.has(id))
return;
this.pending.delete(id);
this.emitted.add(id);
for (const listener of this.emittedListeners)
listener(id);
}
/**
* The session file refused a delivery's entry: the delivery is settled as failed with `error` and is
* no longer held, so its start stops counting as busy and later deliveries start. It stays with its sender.
*/
observeRefused(message, error) {
this.fileTakesWrites = false;
const id = deliveryIdOf(message);
if (id === undefined || this.emitted.has(id))
return;
this.pending.delete(id);
this.failed.set(id, error);
}
/**
* A run settled: its refused messages leave the model context at the next run's start, so the failed
* deliveries may be admitted again - unless the file's last write was refused too.
*/
observeRunSettled() {
if (this.fileTakesWrites)
this.failed.clear();
}
/** Cleared carriers are no longer held; custody not yet enqueued for recovery still owns its delivery. */
dropQueued() {
this.releaseRestored();
for (const [id, lane] of this.pending) {
if (lane !== "start" && typeof lane !== "function")
this.pending.delete(id);
}
}
releaseRestored() {
for (const [id, lane] of this.pending) {
if (typeof lane === "function" && !lane())
this.pending.delete(id);
}
}
endHold(state) {
if (!this.inputHolds.delete(state))
return;
if (this.inputHolds.size === 0)
for (const listener of this.settledListeners)
listener();
}
isBusy() {
if (this.port.isBusy())
return true;
for (const lane of this.pending.values())
if (lane === "start")
return true;
return false;
}
}
function deliveryMessage(input, stamp) {
const message = {
role: "custom",
customType: SESSION_CONTROL_DELIVERY_TYPE,
content: input.text,
display: true,
details: {
delivery_id: input.delivery_id,
source: "session_control",
deliverAs: input.deliverAs,
...(input.sender === undefined ? {} : { sender: input.sender }),
...(input.display_text === undefined ? {} : { display_text: input.display_text }),
...(stamp.remoteOrigin === undefined ? {} : { remote_origin: stamp.remoteOrigin }),
...(stamp.chainCount === undefined ? {} : { chain_count: stamp.chainCount }),
},
timestamp: Date.now(),
};
// The mark rides the message into the run, where the turn that consumes it takes its origin (turn-origin.ts).
if (stamp.turnMark !== undefined)
markInputTurnOrigin(message, stamp.turnMark);
return message;
}
/** Every delivery id the transcript holds an entry for: what answers for the process-lifetime ledger after a restart. */
export const writtenDeliveryIds = {
initial: () => new Set(),
add: (ids, entry) => {
if (entry.type === "custom_message" &&
entry.customType === SESSION_CONTROL_DELIVERY_TYPE &&
isSessionControlDeliveryDetails(entry.details))
ids.add(entry.details.delivery_id);
return ids;
},
};
export function deliveryIdOf(message) {
if (message.role !== "custom" || message.customType !== SESSION_CONTROL_DELIVERY_TYPE)
return undefined;
return isSessionControlDeliveryDetails(message.details) ? message.details.delivery_id : undefined;
}
//# sourceMappingURL=external-admission.js.map