UNPKG

@code-yeongyu/senpi

Version:

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

211 lines • 10.2 kB
import { randomUUID } from "node:crypto"; import { armSecretInputDeadline, isSecretInputValue, resolveSecretInputTimeout, SecretInputUnavailableError, } from "../../core/extensions/secret-input.js"; import { openSealedValue } from "./secret-sealed-answers.js"; import { generateSecretRequestKey } from "./secret-sealed.js"; import { answeredUiRequestId, refusedExtensionUiResponse, } from "./extension-ui-response.js"; /** Private, live-only state. Never registered in progress, snapshot, transcript or answer-ledger maps. */ export class SecretInputRequests { constructor(route, admit) { this.pending = new Map(); this.receipts = new Map(); this.route = route; this.admit = admit; route.bindSealedResponder?.({ settled: (id, answerId, principal) => this.pending.has(id) ? undefined : this.receipt(id, answerId, principal), respond: (answer, claim) => this.respondSealed(answer, claim), }); } /** `created` receives the request id once the prompt is pending, for a local answer through `answerLocal`. */ input(title, placeholder, opts, created) { if (opts?.signal?.aborted) return Promise.resolve(undefined); const timeout = resolveSecretInputTimeout(opts); const id = randomUUID(); const refused = this.route.select(id, () => this.pending.get(id)?.finish("unavailable")); if (refused) return Promise.reject(new SecretInputUnavailableError(refused)); return new Promise((resolve) => { const deadline = Date.now() + timeout; let disarm; const onAbort = () => finish("cancelled"); const finish = (outcome, value, winnerGrant) => { if (!this.pending.delete(id)) return; disarm?.(); opts?.signal?.removeEventListener("abort", onAbort); this.remember(id); this.route.send(id, { type: "secret_input_settled", id, outcome }); this.route.sealedOutcome?.(id, outcome, winnerGrant); this.route.settled(id); resolve(value); }; const sealed = this.route.sealed?.(id) === true; this.pending.set(id, { deadline, finish }); opts?.signal?.addEventListener("abort", onAbort, { once: true }); disarm = armSecretInputDeadline(deadline, () => finish("timed_out")); created?.(id); if (opts?.signal?.aborted) return finish("cancelled"); this.route.send(id, { type: "extension_ui_request", id, method: "input", secret: true, title, ...(placeholder === undefined ? {} : { placeholder }), timeout, deadlineAtMs: deadline, ...(opts?.toolCallId === undefined ? {} : { toolCallId: opts.toolCallId }), ...(opts?.parentToolCallId === undefined ? {} : { parentToolCallId: opts.parentToolCallId }), }); if (sealed) this.offerSealed(id, { title, placeholder, deadlineAtMs: deadline }); }); } /** Generates the request key off the host loop, then offers the request to its sealed holders if it is still open. */ offerSealed(id, offer) { generateSecretRequestKey().then((key) => { const pending = this.pending.get(id); if (!pending) return; pending.key = key.privateKey; pending.hpkePk = key.hpkePk; this.route.offerSealed?.(id, { hpkePk: key.hpkePk, ...offer }); }, () => this.pending.get(id)?.finish("unavailable")); } has(id) { return this.pending.has(id) || this.receipts.has(id); } answered() { return [...this.receipts] .filter((entry) => entry[1] !== undefined && entry[1].principal === undefined && this.route.accepts(entry[0])) .slice(-64) .map(([uiRequestId, receipt]) => ({ uiRequestId, answerId: receipt.answerId })); } respond(frame) { const id = typeof frame.id === "string" ? frame.id : ""; const requestId = answeredUiRequestId(frame); if (!requestId || !this.route.accepts(requestId)) return refusedExtensionUiResponse(id, "secret_answer_refused"); if (!this.has(requestId)) return refusedExtensionUiResponse(id, "unknown_extension_ui_request"); const allowed = new Set(["type", "id", "uiRequestId", "answerId", "sessionId", "secret", "value", "cancelled"]); if (frame.secret !== true || typeof frame.id !== "string" || typeof frame.answerId !== "string" || frame.answerId.length < 1 || frame.answerId.length > 256 || Object.keys(frame).some((key) => !allowed.has(key)) || !("value" in frame ? !("cancelled" in frame) && typeof frame.value === "string" && isSecretInputValue(frame.value) : frame.cancelled === true)) return refusedExtensionUiResponse(id, "invalid_secret_response"); const pending = this.pending.get(requestId); const reply = { type: "response", command: "extension_ui_response", id }; if (!pending) { const receipt = this.receipts.get(requestId); if (receipt?.answerId === frame.answerId && receipt.principal === undefined) return { ...reply, success: true, disposition: "replay" }; return receipt === undefined ? refusedExtensionUiResponse(id, "unknown_extension_ui_request") : { ...reply, success: false, error: "already_answered", disposition: "already_answered" }; } if (Date.now() >= pending.deadline) { pending.finish("timed_out"); return refusedExtensionUiResponse(id, "unknown_extension_ui_request"); } this.admit(); pending.finish(frame.cancelled === true ? "cancelled" : "answered", typeof frame.value === "string" ? frame.value : undefined); this.receipts.set(requestId, { answerId: frame.answerId }); return { ...reply, success: true, disposition: "applied" }; } /** * Design 7.1 steps 3 and 6 at the latch, synchronously: a settled request answers `replay` or `already_answered` * from its receipt before the step-up token is consumed; then the claim re-checks the request, the deadline and the * grant, and only then opens the ciphertext. A losing answer is never decrypted. */ respondSealed(answer, claim) { const id = answer.uiRequestId; const pending = this.pending.get(id); if (!pending) return this.receipt(id, answer.answerId, answer.principal); if (answer.value && !claim.admitJti(answer.value.jti, answer.value.exp)) return { error: "secret_stepup_refused" }; if (Date.now() >= pending.deadline) { pending.finish("timed_out"); return { error: "unknown_extension_ui_request" }; } if (!claim.current()) return { error: "secret_answer_refused" }; let value; if (answer.value) { if (!pending.key || pending.hpkePk === undefined) return { error: "invalid_secret_response" }; try { value = openSealedValue(answer, pending.key, pending.hpkePk); } catch { // No fault inside the open may escape or carry the plaintext: it is a refusal (decision 0022 SP-0 L2). value = undefined; } if (value === undefined || !isSecretInputValue(value)) return { error: "invalid_secret_response" }; } this.admit(); pending.finish(answer.value ? "answered" : "cancelled", value, answer.grantId); this.receipts.set(id, { answerId: answer.answerId, principal: answer.principal }); return { disposition: "applied" }; } /** 7.1 step 3: `replay` for the same answer id and principal, else `already_answered`; no receipt is unknown. */ receipt(id, answerId, principal) { const receipt = this.receipts.get(id); if (receipt === undefined) return { error: "unknown_extension_ui_request" }; return receipt.answerId === answerId && receipt.principal === principal ? { disposition: "replay" } : { error: "already_answered" }; } /** * The terminal's own answer to a prompt it also offered to sealed holders (D11 S3-6b parity): the same latch, so the * first answer wins. The terminal's component admits its own human answer, so this does not. */ answerLocal(id, value) { const pending = this.pending.get(id); if (!pending) return; pending.finish(value === undefined ? "cancelled" : "answered", value); this.receipts.set(id, { answerId: "terminal" }); } cancelAll(outcome = "cancelled") { for (const pending of [...this.pending.values()]) pending.finish(outcome); } recheck() { for (const [id, pending] of this.pending) if (!this.route.available(id)) pending.finish("unavailable"); } /** Final teardown: also releases the sealed latch, so the route no longer keeps this request set alive. */ dispose() { this.close(); this.route.bindSealedResponder?.(undefined); } /** Ends every prompt; the latch stays bound because the connection reuses this set on every rebind. */ close() { this.cancelAll(); for (const id of this.receipts.keys()) this.route.forget(id); this.receipts.clear(); } remember(id) { this.receipts.set(id, undefined); if (this.receipts.size > 1024) { const oldest = this.receipts.keys().next().value; if (oldest !== undefined) { this.receipts.delete(oldest); this.route.forget(oldest); } } } } //# sourceMappingURL=secret-input-requests.js.map