UNPKG

@code-yeongyu/senpi

Version:

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

425 lines • 22.3 kB
import { randomUUID } from "node:crypto"; import { join } from "node:path"; import { parentPort, workerData } from "node:worker_threads"; import "../../windows-power-throttling-startup.js"; import { captureAdmissionReply } from "./compact-admission-reply.js"; import { workerAdmissionCommand } from "./worker-admission-command.js"; import { runWithProviderScope } from "@earendil-works/pi-ai/node/provider-scope"; import { isBunBinary } from "../../config.js"; import { WAKE_SOURCE_STATE_EVENT } from "../../core/extensions/builtin/monitor-state-event.js"; import { attachMcpGrantPresentation } from "../../core/mcp-grant-presentations.js"; import { startOpenTimer } from "../../core/open-timing.js"; import { takeOverStdout } from "../../core/output-guard.js"; import { executionCallKey } from "../../core/session-call-keys.js"; import { recoveryCarrier, setSessionRecoveryEpoch } from "../../core/session-recovery-identity.js"; import { getDefaultSessionDir } from "../../core/session-manager.js"; import { subscriptionLimits } from "../../core/subscription-limits/limit-store.js"; import { SettingsManager } from "../../core/settings-manager.js"; import { registerWebViewBroker } from "../../core/webview/webview-broker.js"; import { createCliRuntimeFactory } from "../../main.js"; import { initTheme } from "../interactive/theme/theme.js"; import { CommandAuthority, commandAuthority, withReceipt } from "./command-authority.js"; import { ConnectionRoles, roleConnection } from "./connection-roles.js"; import { authorityConflict, DELEGATION_AUTHORITY_CONFLICT } from "./delegation-resolve.js"; import { isHandoffBusy } from "./handoff-activity.js"; import { createRpcSessionBinding } from "./session-binding.js"; import { SessionEventWriter } from "./session-event-writer.js"; import { canonicalSessionPath } from "./session-path-key.js"; import { resolveMovedProfile } from "./session-registry-moved-path.js"; import { createWorkerCredit } from "./session-worker-credit.js"; import { workerSnapshot } from "./session-worker-snapshot.js"; import { WorkerTransfer } from "./session-worker-transfer.js"; import { carriedCanonical, carriedRefusal } from "./compact-canonical-pairing.js"; import { COMPACT_PROTOCOL_MAX_DEPTH, protocolDepthLimitOf } from "./compact-protocol-depth.js"; import { legacyJsonText } from "./jsonl.js"; import { jsonTextDeeperThan } from "./legacy-record-depth.js"; import { CompactProducerStamp } from "./compact-producer-stamp.js"; import { SESSION_WORKER_LIMITS, withinFrameLimit, } from "./session-worker-protocol.js"; import { createSessionWorkerRegistry } from "./session-worker-registry.js"; import { IssuedWorkerOwners } from "./session-worker-owners.js"; import { McpFormWorker } from "./mcp-form-worker.js"; import { WorkerSecretRoutes } from "./session-worker-secret-route.js"; if (isBunBinary) { const { registerBunRuntimeModules } = await import("../../bun/runtime-modules.js"); registerBunRuntimeModules(); } takeOverStdout(); registerWebViewBroker(Reflect.get(Object(workerData), "webviewBroker")); const port = parentPort; // Reply identity follows the command across the isolate without a per-request lookup table. if (!port) throw new Error("Session worker requires a parent port"); const send = (message) => port.postMessage(message); const privateForms = new McpFormWorker(send); let privateFormsEnforced = false; function failWorker(error) { send({ type: "failure", error }); process.exit(1); } const { exchange, transfer, post, installTransport, installWriteReservation, declareOnHost } = createWorkerCredit(send, failWorker); // The host's key for the same file, so a deleted directory neither throws here nor misses (senpi#2285). installWriteReservation(canonicalSessionPath); class WorkerEventWriter extends SessionEventWriter { secretInputRoute(_sessionId) { return this.secrets.route(); } bindMcpForms(_sessionId, durableId, ui, admit) { return privateFormsEnforced ? privateForms.bind(durableId, ui, admit) : undefined; } constructor() { super(() => { }); this.secrets = new WorkerSecretRoutes(exchange, () => this.currentConnection()); this.workerSecurityBridge = true; } bindSecurityPresentations(sessionId, durableId, notices, ui) { const detach = attachMcpGrantPresentation(durableId, ui.select); const stop = notices.subscribe((snapshot) => { this.enqueue(sessionId, { type: "security_notice_snapshot", snapshot }); }); return () => { detach(); stop(); }; } settleGrantDialog(sessionId, id) { this.enqueue(sessionId, { type: "security_grant_settled", id }); } publishLoadedSurfacesChanged(_sessionId, previous, digest) { // The isolate never emits the event itself: the host owns the per-(connection, session) // dedupe across every attachment, so a connection attached to several worker sessions // hears one notice per inventory change on either runtime (#3198 review, L5). exchange((signal) => ({ type: "loaded_surfaces", ...(previous === undefined ? {} : { previous }), digest, signal, })); } enqueue(_sessionId, value) { // The command's receipt is stamped where the command ran (omo-relay-daemon#307); the host never overwrites it. const record = withReceipt(value, this.currentConnection()); let epochSignal; // Built under the host's payload permit (S12b): no line, snapshot or transcript exists before it is held. transfer((signal) => { const line = legacyJsonText(record); if (Buffer.byteLength(line) > SESSION_WORKER_LIMITS.outputBytes) failWorker("session_worker_output_limit"); const session = entry?.runtime?.session; if (!session) throw new Error("Session output preceded runtime creation"); const activity = { busy: session.isSessionBusy, handoffBusy: isHandoffBusy(session.activitySnapshot), streaming: session.isStreaming, }; const replacement = "type" in record && (record.type === "session_replaced" || record.type === "session_archived_changed" || record.type === "session_settled_changed" || record.type === "question_resolved" || record.type === "question_updated" || record.type === "auto_retry_start" || record.type === "auto_retry_end" || (record.type === "extension_ui_request" && "method" in record && record.method === "question")) ? workerSnapshot(entry) : undefined; if (replacement && Buffer.byteLength(JSON.stringify(replacement)) > SESSION_WORKER_LIMITS.outputBytes) failWorker("session_worker_snapshot_limit"); const replaced = "type" in record && record.type === "session_replaced"; const issued = this.connectionContext.owner?.wire; const owner = issued && { ownerId: issued.ownerId, bindingGeneration: issued.bindingGeneration }; if (ordered && replaced) { journaled = session.sessionManager; stamp.forget(); canonicalLost = false; } const transitions = ordered && !replaced ? (journaled?.drainTranscript() ?? []) : []; epochSignal = ordered && replaced ? new SharedArrayBuffer(36) : undefined; const recovery = recoveryCarrier(record); const callKey = executionCallKey(record); const canonical = carriedCanonical(record); const order = ordered ? { ...stamp.stamp(recovery, canonical, record), recovery, ...(callKey ? { callKey } : {}), ...(canonical ? { canonical } : {}), ...(carriedRefusal(record) ? { canonicalRefused: true } : {}), ...(replaced ? { bootstrap: { transcript: withinFrameLimit(session.sessionManager.beginTranscriptJournal()), epochSignal, }, } : {}), ...(transitions.length > 0 ? { transitions: withinFrameLimit(transitions) } : {}), } : {}; return { ...order, type: "output", admissionReply: captureAdmissionReply(), // Keep one JSON-normal transfer format, including toJSON and non-cloneable fields; with the flag ON a record // over one fragment then travels as bounded fragments of this message's JSON (S12b). ...(jsonTextDeeperThan(line, COMPACT_PROTOCOL_MAX_DEPTH) ? { record: {}, recordText: line } : { record: JSON.parse(line) }), connection: this.currentConnection(), ...(owner === undefined ? {} : { owner }), signal, activity, snapshot: replacement, }; }); if (epochSignal && entry?.runtime) setSessionRecoveryEpoch(entry.runtime.session, Buffer.from(epochSignal).toString("ascii")); return true; } enqueueCanonical(_sessionId, control) { if (!ordered) return; const { ordinal, firstOrdinal = ordinal } = stamp.stamp(control.carrier, control.record); const { record, carrier: recovery } = control; transfer((signal) => ({ type: "canonical", ordinal, firstOrdinal, recovery, record, signal })); } canonicalUnavailable(_sessionId, cause) { // The host's compact state for this epoch is already gone after the first real loss; later losses would only cost // exchanges. A depth refusal is never that loss and is always sent: the host counts it, live state or not (RULING-59 C). const limit = protocolDepthLimitOf(cause); if (!ordered || (canonicalLost && limit === undefined)) return; canonicalLost ||= limit === undefined; const { ordinal } = stamp.stamp(undefined, undefined); const reason = cause instanceof Error ? cause.message : String(cause); transfer((signal) => ({ type: "canonical_unavailable", ordinal, reason, limit, signal })); } } const writer = new WorkerEventWriter(); const issuedOwners = new IssuedWorkerOwners(); // One session per isolate: the roles of the connections it serves, adopted from the host before each command. const connectionRoles = new ConnectionRoles(); let prepared; let registry; let entry; let binding; let closing = false; /** Set by `commit` when the host owns an acceptance lane; each output frame then carries the next ordinal. */ let ordered = false; /** The output-frame ordinal (S04a) is the compact producer ordinal: one numbering (RULING-36). */ const stamp = new CompactProducerStamp(); /** One `canonical_unavailable` frame per epoch: set by the first, cleared with `stamp.forget()` at a replacement. */ let canonicalLost = false; /** The manager whose committed transcript changes ride the next output frame; replaced with the session. */ let journaled; let unsubscribe; let unsubscribeWake; function publishSnapshot(settled = false) { transfer((signal) => { const value = workerSnapshot(entry); if (Buffer.byteLength(JSON.stringify(value)) > SESSION_WORKER_LIMITS.outputBytes) failWorker("session_worker_snapshot_limit"); return { type: "snapshot", snapshot: value, signal, settled }; }); } function subscribeSession() { unsubscribe?.(); unsubscribeWake?.(); unsubscribeWake = entry?.runtime?.session.extensionRunner.onBusEvent(WAKE_SOURCE_STATE_EVENT, () => publishSnapshot()); // Settled for the host's drain only at agent_idle: agent_settled can precede its extension handlers (omo#11419). unsubscribe = entry?.runtime?.session.subscribe((event) => publishSnapshot(event.type === "agent_idle")); } async function handle(message) { switch (message.type) { case "prepare": { if (prepared) throw new Error("Session worker already prepared"); for (const limits of message.subscriptionLimits) subscriptionLimits.adopt(limits); // Resolved here, not on the host loop, which never inspects caller paths (senpi#2898). const profile = resolveMovedProfile(message.profile); const path = profile.sessionPath ?? join(getDefaultSessionDir(profile.cwd, message.configuration.agentDir), `${new Date().toISOString().replace(/[:.]/g, "-")}_${randomUUID()}.jsonl`); prepared = { ...message, profile: { ...profile, sessionPath: canonicalSessionPath(path) } }; send({ type: "prepared", request: message.request, sessionPath: canonicalSessionPath(path) }); return; } case "commit": { if (!prepared || registry) throw new Error("Invalid session commit"); const timer = startOpenTimer(`worker-commit:${message.request}`); const startupSettingsManager = SettingsManager.create(prepared.configuration.cwd, prepared.configuration.agentDir); timer.mark("settings"); const factory = createCliRuntimeFactory(prepared.configuration, { startupSettingsManager }); initTheme(startupSettingsManager.getTheme(), false); registry = createSessionWorkerRegistry(prepared.configuration.agentDir, factory); timer.mark("factory"); const opened = await registry.openSession(prepared.profile); timer.mark("registry_open"); entry = registry.getForCommand(opened.sessionId, "open_session"); // The host offers acceptance only with the flag on (RULING-112); a session without the structured lane declines // it with a `ready` lacking a bootstrap, which the host refuses (RULING-106). ordered = message.acceptance === true && entry.runtime?.session.hasStructuredLane === true; if (message.recoveryEpoch && entry.runtime) setSessionRecoveryEpoch(entry.runtime.session, message.recoveryEpoch); journaled = ordered ? entry.runtime?.session.sessionManager : undefined; if (ordered && message.permits) installTransport(new WorkerTransfer(send, message.permits, stamp, failWorker)); // The bootstrap answer is built only once the initial permit is held (S12b X03). post(() => ({ type: "ready", request: message.request, snapshot: workerSnapshot(entry), ...(ordered ? { bootstrap: { transcript: withinFrameLimit(journaled?.beginTranscriptJournal() ?? []) } } : {}), })); return; } case "bind": { if (!entry || binding) throw new Error("Invalid session binding"); const bound = roleConnection(message.connection); if (message.delegation !== undefined && connectionRoles.retain(bound, message.delegation).kind === "conflict") throw new Error(DELEGATION_AUTHORITY_CONFLICT); if (message.delegation !== undefined) connectionRoles.noteCarriedDelegation(bound); if (message.roles !== undefined) connectionRoles.adopt(bound, message.roles, message.delegation?.incarnation); const bindingEntry = entry; privateFormsEnforced = message.mcpFormsEnforced === true; const createBinding = () => createRpcSessionBinding(message.sessionId, bindingEntry, writer, () => send({ type: "request_close" }), { capabilities: message.capabilities, connectionRoles, clientInfo: { connectionId: () => writer.currentConnection(), // The incarnation is the declaring command's own, passed in, never read here (#307). setCapabilities: (connection, capabilities, incarnation) => declareOnHost((signal) => ({ type: "capabilities", connection, capabilities, ...(incarnation === undefined ? {} : { incarnation }), signal, })) === "stale" ? "stale" : undefined, }, }); binding = await (message.connection === undefined ? createBinding() : writer.withConnection(message.connection, createBinding)); const rebind = entry.rebindSession; entry.rebindSession = async (session) => { await rebind?.(session); subscribeSession(); }; entry.runtime?.setRebindSession(entry.rebindSession); subscribeSession(); publishSnapshot(); send({ type: "result", request: message.request }); return; } case "cancel_grant": { await binding?.handle({ type: "extension_ui_response", id: message.id, cancelled: true }); return; } case "cancel_secret": writer.secrets.cancels.get(message.id)?.(); return; case "secret_sealed_answer": send({ type: "secret_sealed_result", request: message.request, reply: await writer.secrets.answer(message.answer), }); return; case "command": { const privileged = "type" in message.command && ["abort", "abort_bash", "extension_ui_response", "extension_ui_progress"].includes(String(message.command.type)); if (!binding || (closing && !privileged)) throw new Error("session_closing"); const connection = roleConnection(message.connection); const resolved = message.delegation === undefined ? undefined : connectionRoles.retain(connection, message.delegation); if (resolved?.kind !== "conflict" && message.roles !== undefined) connectionRoles.adopt(connection, message.roles, message.delegation?.incarnation); if (message.delegation !== undefined) connectionRoles.noteCarriedDelegation(connection); if (message.origin !== undefined) connectionRoles.declareOrigin(connection, message.origin); const activeBinding = binding; const run = resolved?.kind === "conflict" ? async () => void writer.enqueue("", authorityConflict(message.command)) : () => activeBinding.handle(message.command); const authority = new CommandAuthority(message.connection, resolved === undefined || resolved.kind === "conflict" ? message.delegation : resolved.descriptor, message.exec, resolved?.kind === "stale"); await commandAuthority.run(authority, () => workerAdmissionCommand(message, writer, issuedOwners, run)); publishSnapshot(); send({ type: "result", request: message.request }); return; } case "prompt_surface": if (!entry?.runtime) throw new Error("session_closing"); entry.runtime.setPromptSurface(message.surface); send({ type: "result", request: message.request }); return; case "browser_engine": if (!entry?.runtime) throw new Error("session_closing"); entry.runtime.setBrowserEngine(message.engine); send({ type: "result", request: message.request }); return; case "permission_preset": if (!entry?.runtime) throw new Error("session_closing"); entry.runtime.setPermissionPreset(message.preset); send({ type: "result", request: message.request }); return; case "subscription_limits": for (const limits of message.accounts) subscriptionLimits.adopt(limits); return; case "owners_retired": issuedOwners.retire(message.owners); return; case "cancel_ui": binding?.cancelPendingExtensionUiRequests?.(); send({ type: "control_done", control: "cancel_ui" }); return; case "close": closing = true; unsubscribe?.(); unsubscribeWake?.(); await binding?.dispose(); connectionRoles.clear(); if (entry?.runtime) { const current = entry; await runWithProviderScope(current.scope, async () => { await current.runtime?.session.abort(); await current.runtime?.session.waitForIdle(); await current.runtime?.dispose(); await current.scope.close(); }); } process.exit(0); } } // A turn in this isolate reports into its own store; the host mirrors it so its clients see it (senpi#3695). subscriptionLimits.subscribeMirror((limits) => send({ type: "subscription_limits", limits })); port.on("message", (message) => { if (privateForms.receive(message)) return; void handle(message).catch((cause) => { const error = cause instanceof Error ? cause.message : String(cause); if (error.startsWith("session_worker_")) { send({ type: "failure", error }); process.exit(1); } if ("request" in message) send({ type: "result", request: message.request, error }); else { send({ type: "failure", error }); process.exit(1); } }); }); //# sourceMappingURL=session-worker.js.map