@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
87 lines • 3.42 kB
JavaScript
import { randomUUID } from "node:crypto";
import { carriesExtensionOwner, ExtensionOwner, } from "./extension-owner.js";
const identityKey = (identity) => `${identity.ownerId}\u0000${identity.bindingGeneration}`;
/**
* Host half of a worker binding's extension owners (#4728). Gates are captured at ingress, before the
* command's first await, and retired atomically before the isolate hears about it.
*/
export class WorkerOwnerGates {
constructor() {
this.generation = randomUUID();
this.issued = new Map();
}
capture(context, connection, command) {
const transport = context.transport;
if (connection === undefined || transport === undefined || !carriesExtensionOwner(command))
return undefined;
let owner = transport.capture(this.generation);
// The isolate retires a generation by replacing its session; the next request opens a new one.
if (owner.retired) {
this.generation = randomUUID();
owner = transport.capture(this.generation);
}
const owners = this.issued.get(connection) ?? new Set();
owners.add(owner);
this.issued.set(connection, owners);
return owner.wire;
}
/**
* `connection` left this session. Only the incarnation that left is retired: a gate for a transport now
* registered under the same routing string with a different owner was already retired with its transport.
*/
detach(context, connection) {
const owners = this.issued.get(connection);
if (!owners)
return [];
this.issued.delete(connection);
const current = context.transportOf(connection);
const kept = new Set();
const retired = [];
for (const owner of owners) {
if (current !== undefined && current.ownerId !== owner.wire.ownerId && !owner.retired)
kept.add(owner);
else {
owner.retire();
retired.push({ ownerId: owner.wire.ownerId, bindingGeneration: owner.wire.bindingGeneration });
}
}
if (kept.size > 0)
this.issued.set(connection, kept);
return retired;
}
retireAll() {
const retired = [];
for (const owners of this.issued.values())
for (const owner of owners) {
owner.retire();
retired.push({ ownerId: owner.wire.ownerId, bindingGeneration: owner.wire.bindingGeneration });
}
this.issued.clear();
this.generation = randomUUID();
return retired;
}
}
/** Isolate half: one owner object per issued gate, sharing the host's retirement word. */
export class IssuedWorkerOwners {
constructor() {
this.owners = new Map();
}
adopt(wire) {
const key = identityKey(wire);
const existing = this.owners.get(key);
if (existing)
return existing;
const owner = new ExtensionOwner(wire);
this.owners.set(key, owner);
return owner;
}
/** Exact identities only: a late notice for one incarnation never reaches another. */
retire(identities) {
for (const identity of identities) {
const key = identityKey(identity);
this.owners.get(key)?.retire();
this.owners.delete(key);
}
}
}
//# sourceMappingURL=session-worker-owners.js.map