UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

66 lines • 2.77 kB
import { AsyncLocalStorage } from "node:async_hooks"; /** Capture registrations before awaits; a routing string is never an incarnation. */ export class SessionConnectionContext { constructor(ownerOf, delegationOf = () => undefined) { this.storage = new AsyncLocalStorage(); this.ownerOf = ownerOf; this.delegationOf = delegationOf; } run(id, task) { const delegation = this.delegationOf(id); return this.storage.run({ id, owner: this.ownerOf(id), ...(delegation === undefined ? {} : { delegation }) }, task); } /** Host-owned background construction has no requesting transport or inherited delegation. */ outside(task) { return this.storage.exit(task); } /** The delegation the running line captured at its start, or undefined for a connection that never declared. */ get delegation() { return this.storage.getStore()?.delegation; } /** * Route a worker's targeted output to the exact incarnation and binding generation that captured it. * A routing string now registered to another transport, or a retired gate, leaves the frame stale. */ runCaptured(id, identity, task) { const owner = this.ownerOf(id); const binding = owner?.ownerId === identity.ownerId ? owner.peek(identity.bindingGeneration) : undefined; return this.storage.run({ id, owner: binding === undefined ? undefined : owner, binding }, task); } /** A session isolate has no transports of its own: it runs a command with the gate its host captured. */ runIssued(id, binding, task) { return this.storage.run({ id, owner: undefined, binding }, task); } getStore() { return this.storage.getStore()?.id; } transportOf(id) { return this.ownerOf(id); } get transport() { return this.storage.getStore()?.owner; } get owner() { return this.storage.getStore()?.binding; } withBinding(generation, task) { const captured = this.storage.getStore(); if (!captured?.owner) return task(); return this.storage.run({ ...captured, binding: captured.owner.capture(generation) }, task); } isCurrent() { return this.currentGuard()(); } /** A check of the captured destination that stays valid after this async context ends (queued output). */ currentGuard() { const captured = this.storage.getStore(); if (!captured) return () => true; return () => captured.owner !== undefined && this.ownerOf(captured.id) === captured.owner && !captured.owner.retired && captured.binding?.retired !== true; } } //# sourceMappingURL=session-connection-context.js.map