@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
339 lines • 15.5 kB
JavaScript
var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
if (value !== null && value !== void 0) {
if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
var dispose, inner;
if (async) {
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
dispose = value[Symbol.asyncDispose];
}
if (dispose === void 0) {
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
dispose = value[Symbol.dispose];
if (async) inner = dispose;
}
if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
env.stack.push({ value: value, dispose: dispose, async: async });
}
else if (async) {
env.stack.push({ async: true });
}
return value;
};
var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
return function (env) {
function fail(e) {
env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
env.hasError = true;
}
var r, s = 0;
function next() {
while (r = env.stack.pop()) {
try {
if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
if (r.dispose) {
var result = r.dispose.call(r.value);
if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
}
else s |= 1;
}
catch (e) {
fail(e);
}
}
if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
if (env.hasError) throw env.error;
}
return next();
};
})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
});
import { adjustBlock, appendBlock, deltaBlock } from "./compact-active-block.js";
import { CompactActiveMessages } from "./compact-active-messages.js";
import { foldCallBlock, foldCallRecord, foldCallTerminal } from "./compact-call-fold.js";
import { readCalls } from "./compact-call-view.js";
import { coldFlowOperations } from "./compact-cold-flows.js";
import { CompactCurrentComponents } from "./compact-current-components.js";
import { CompactReadError, CompactReadLease } from "./compact-read-lease.js";
import { foldSeededBlock } from "./compact-seeded-block.js";
import { CompactSeededDraft } from "./compact-seeded-draft.js";
import { recordMessage, seedMessage, updateFields } from "./compact-seeded-messages.js";
import { CompactSessionCalls } from "./compact-session-calls.js";
import { readActiveMessages, readCompactState } from "./compact-state-view.js";
import { CompactTransitionError } from "./compact-transition.js";
/** Synchronous acceptance; cuts and settlement transfer persistent component roots (senpi#4272). */
export class CompactSessionState extends CompactActiveMessages {
constructor() {
super(...arguments);
this.frozenTailBytes = 0;
this.cuts = new WeakMap();
this.components = new CompactCurrentComponents(this.store);
this.calls = new CompactSessionCalls(this.store);
}
get acceptedSequence() {
return this.sequence;
}
/** Open broadcast questions right now, for synchronous status reads (R3.C6.4). */
get openBroadcastDialogs() {
return this.components.openBroadcast;
}
/**
* `sequence` is the acceptance lane's own sequence for this unit (one numbering with the lane, RULING-26);
* `turnId` is the lane-minted turn the unit belongs to, consumed by the calls component (RULING-13 Q6).
*/
accept(t, sequence = this.sequence + 1, turnId = null) {
if (t.type !== "message_remove")
this.store.assertReadable();
const step = { sequence, scope: this.callScope(turnId) };
if ((t.type === "message_status" || t.type === "message_remove") && !this.active.has(t.messageId))
throw new CompactTransitionError("cold_operation_required", "use applyCold after acceptance");
switch (t.type) {
case "seeded_block": {
const env_1 = { stack: [], error: void 0, hasError: false };
try {
const address = { messageId: t.messageId, contentIndex: t.event.contentIndex };
const old = this.active.get(t.messageId)?.blocks.get(address.contentIndex);
if (old?.epoch !== undefined && old.epoch !== t.epoch)
throw new CompactTransitionError("wrong_epoch", t.messageId);
if (!Number.isSafeInteger(address.contentIndex) || address.contentIndex < 0)
throw new CompactTransitionError("unknown_block", String(address.contentIndex));
const starting = "seed" in t.event ||
(t.event.type === "message_block_state" &&
t.event.phase === "insert" &&
(!old || old.seeded?.phase === "initial"));
if (starting)
this.identity.validate(t);
const draft = __addDisposableResource(env_1, new CompactSeededDraft(this.store), false);
const fields = updateFields(draft, this.active.get(t.messageId)?.fields, t);
const block = foldSeededBlock(draft, old?.seeded, t.event);
this.publish(address, { ...block.body, seeded: block, epoch: t.epoch }, fields);
if (starting)
this.identity.commit(t);
foldCallBlock(this.calls, t, step, this.active.get(t.messageId)?.blocks.get(address.contentIndex));
break;
}
catch (e_1) {
env_1.error = e_1;
env_1.hasError = true;
}
finally {
__disposeResources(env_1);
}
}
case "seeded_message": {
const { message, terminal } = recordMessage(t.record);
// The terminal replaces the live blocks, so the calls own their raw text from the blocks being replaced.
if (terminal)
foldCallTerminal(this.calls, t.messageId, message, step, this.active.get(t.messageId)?.blocks);
this.acceptMessage(t);
break;
}
case "block_start":
this.start(t);
break;
case "block_delta": {
const block = { ...this.block(t) };
adjustBlock(this.store, block, 1);
try {
deltaBlock(this.store, block, t.offset, t.text);
this.publish(t, block);
}
finally {
adjustBlock(this.store, block, -1);
}
break;
}
case "block_replace": {
const block = {
...this.block(t),
root: 0,
tail: "",
tailRoot: 0,
units: 0,
covered: 0,
witness: "",
};
appendBlock(this.store, block, t.text);
block.emitted = block.units;
this.publish(t, block);
adjustBlock(this.store, block, -1);
break;
}
case "message_status":
this.settle(t.messageId, t.persistence);
break;
case "message_remove":
this.dropActive(t.messageId);
break;
case "component":
this.components.apply(t.record);
break;
}
this.sequence = sequence;
return sequence;
}
/** A call record at its lane step; `changed` is false when the record is ignored and takes no sequence (Q9). */
acceptCall(record, sequence, turnId, callKey) {
this.store.assertReadable();
const fold = foldCallRecord(this.calls, record, this.callScope(turnId), sequence, callKey);
if (fold.changed)
this.sequence = sequence;
return fold;
}
/** The outstanding call whose block this is: the call a `toolcall_*` update streams (RULING-123), by the table's index. */
callOwning(messageId, contentIndex) {
return this.calls.table.byOwner(messageId, contentIndex);
}
applyCold(t) {
return this.cold.run(t, this.sequence);
}
/** One ordered cold unit per flow: its operations run back to back after acceptance, each with its outcome. */
applyColdFlow(flow) {
return this.cold.runAll(coldFlowOperations(flow), this.sequence);
}
freeze() {
this.store.assertReadable();
const active = this.messages.ref;
const tails = this.residentTailBytes;
if (active)
this.store.adjust(active.owner, 0, 1);
this.frozenTailBytes += tails;
const frozen = {
sequence: this.sequence,
active,
settled: this.settled.freeze(),
components: this.components.freeze(),
calls: this.calls.freeze(),
};
this.cuts.set(frozen, new CompactReadLease(() => {
if (active)
this.store.adjust(active.owner, 0, -1);
this.frozenTailBytes -= tails;
this.settled.release(frozen.settled);
this.components.release(frozen.components);
this.calls.release(frozen.calls);
}));
return frozen;
}
release(frozen) {
this.cutLease(frozen).release();
}
/** Whole-view compatibility assembly; persistent nodes and text ranges are read separately. */
async read(frozen) {
return this.under(frozen, (valid) => readCompactState(frozen, { ...this.roots, settled: this.settled }, valid));
}
/** The live messages at the cut with the current value of every block (R3.C6.4), never the settled history. */
readActive(frozen) {
return this.under(frozen, (valid) => readActiveMessages(frozen, this.roots, valid));
}
/** Run state, lifecycle and open dialogs at the cut (RULING-26 Q4). */
readComponents(frozen) {
return this.under(frozen, (valid) => this.components.read(frozen.components, valid));
}
/** The outstanding calls at the cut (R3.C3), raw text resolved from the slots the calls own. */
readCalls(frozen) {
const owner = { calls: this.calls, ...this.roots };
return this.under(frozen, (valid) => readCalls(frozen, owner, valid));
}
cutStorage(frozen, use) {
return this.under(frozen, (valid) => use(this.store, valid));
}
get roots() {
return { store: this.store, blockRoots: this.blockRoots, messageRoots: this.messageRoots };
}
callScope(turnId) {
return { sessionEpoch: this.sessionEpoch, turnId };
}
cutLease(frozen) {
const lease = this.cuts.get(frozen);
if (!lease)
throw new CompactReadError("ownership");
return lease;
}
/** Every read runs under the cut's operation lease and re-checks it with the store at each step. */
under(frozen, read) {
const lease = this.cutLease(frozen);
const valid = () => {
lease.assert();
this.store.assertReadable();
};
valid();
return lease.run(() => read(valid));
}
storageStatus() {
return {
...this.store.status(),
...this.settled.status(),
residentTailBytes: this.residentTailBytes,
frozenTailBytes: this.frozenTailBytes,
hotWitnessBytes: this.hotWitnessBytes,
residentComponentNodes: this.blockRoots.residentNodes + this.messageRoots.residentNodes,
residentComponentIndexBytes: (this.blockRoots.residentNodes + this.messageRoots.residentNodes) * 192,
residentTextNodes: this.store.text.residentNodes,
residentTextIndexBytes: this.store.text.residentNodes * 192,
};
}
async idle() {
await this.cold.idle();
await this.store.idle();
}
async retire() {
await this.store.retire();
await this.cold.idle();
}
start(t) {
this.identity.validate(t);
if (this.active.get(t.messageId)?.blocks.has(t.contentIndex))
throw new CompactTransitionError("duplicate_block", `${t.messageId}#${t.contentIndex}`);
const covered = t.coveredCodeUnits;
if (!Number.isInteger(covered) || (covered !== 0 && covered !== t.seed.length))
throw new CompactTransitionError("invalid_coverage", `${covered} of ${t.seed.length} seed code units`);
const block = {
kind: t.kind,
root: 0,
tail: "",
tailRoot: 0,
units: 0,
emitted: covered > 0 ? 0 : t.seed.length,
covered,
witness: t.seed.slice(0, covered),
};
appendBlock(this.store, block, t.seed);
this.publish(t, block);
adjustBlock(this.store, block, -1);
this.identity.commit(t);
}
/** A start installs initial slots once; a terminal wins whole, and the outer end settles it as pending. */
acceptMessage(t) {
const env_2 = { stack: [], error: void 0, hasError: false };
try {
const live = this.active.get(t.messageId);
if (live?.epoch !== undefined && live.epoch !== t.epoch)
throw new CompactTransitionError("wrong_epoch", t.messageId);
const { message, terminal } = recordMessage(t.record);
if (!terminal && [...(live?.blocks.values() ?? [])].some((block) => block.seeded?.phase !== "initial"))
throw new CompactTransitionError("invalid_phase", "a start cannot rewind streamed blocks");
if (!live)
this.identity.validate(t);
const draft = __addDisposableResource(env_2, new CompactSeededDraft(this.store), false);
const next = seedMessage(draft, message, terminal, live?.blocks, t);
// Bound once, by the first message-level record that carries it, even when an indexed start created the message.
const correlation = live?.correlation ?? (t.correlation && draft.fields(t.correlation));
this.install(t.messageId, { fields: next.fields, correlation, epoch: t.epoch }, next.blocks);
if (!live)
this.identity.commit(t);
if (t.record.type === "message_end")
this.settle(t.messageId, "pending");
}
catch (e_2) {
env_2.error = e_2;
env_2.hasError = true;
}
finally {
__disposeResources(env_2);
}
}
}
//# sourceMappingURL=compact-session-state.js.map