@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
132 lines • 6.4 kB
JavaScript
import { CLAIM_VERDICT_ERRORS } from "../egress/placement-claim.js";
/** The input or output cannot cross the wire: it is not JSON, or not the closed envelope. */
export class HookContractError extends Error {
constructor() {
super(...arguments);
this.name = "HookContractError";
}
}
/** The request's placement claim did not verify, so no hook ran; `code`/`retryable` are the claim's wire answer. */
export class HookRequestRefusedError extends Error {
constructor(verdict) {
super(`hook.model_request refused: placement claim ${verdict}`);
this.name = "HookRequestRefusedError";
this.verdict = verdict;
this.code = CLAIM_VERDICT_ERRORS[verdict].code;
this.retryable = CLAIM_VERDICT_ERRORS[verdict].retryable;
}
}
const isPlainObject = (value) => {
if (typeof value !== "object" || value === null || Array.isArray(value))
return false;
const prototype = Object.getPrototypeOf(value);
return prototype === Object.prototype || prototype === null;
};
/** `value` as JSON, exactly; anything JSON would drop, coerce or reject is refused (an `undefined` member is absent). */
function wireJson(value, at) {
if (value === null || typeof value === "string" || typeof value === "boolean")
return value;
if (typeof value === "number") {
if (Number.isFinite(value))
return value;
throw new HookContractError(`${at} is not a finite number`);
}
if (Array.isArray(value))
return value.map((item, index) => wireJson(item, `${at}[${index}]`));
if (isPlainObject(value)) {
const out = {};
for (const [key, member] of Object.entries(value))
if (member !== undefined)
out[key] = wireJson(member, `${at}.${key}`);
return out;
}
throw new HookContractError(`${at} is not JSON`);
}
function wireModel(model) {
const { headers: _headers, ...rest } = model;
return wireJson(rest, "model");
}
/** The projection of a fused `before_provider_request` input. */
export function hookRequestInputOf(event) {
const payload = wireJson(event.payload, "payload");
return event.model === undefined ? { payload } : { payload, model: wireModel(event.model) };
}
/** A step call's hook input; an aux call runs no request hooks on the hand and has none. */
export function hookRequestInputForCall(call, event) {
return call.kind === "step" ? hookRequestInputOf(event) : undefined;
}
/** The reply's `output`: the payload the hooks produced, with the model the request carried. */
export function hookRequestOutputOf(input, payload) {
const out = wireJson(payload, "payload");
return input.model === undefined ? { payload: out } : { payload: out, model: input.model };
}
const MODEL_STRING_FIELDS = ["id", "name", "api", "provider", "baseUrl"];
/** Reads a wire value back as the closed envelope `{ payload, model? }`; the model never carries headers. */
export function parseHookRequestInput(value) {
if (!isPlainObject(value) || !("payload" in value))
throw new HookContractError("hook input is not an object with a payload");
const extra = Object.keys(value).filter((key) => key !== "payload" && key !== "model");
if (extra.length > 0)
throw new HookContractError(`hook input has unknown members: ${extra.join(", ")}`);
const payload = wireJson(value.payload, "payload");
if (value.model === undefined)
return { payload };
const model = value.model;
if (!isPlainObject(model) || MODEL_STRING_FIELDS.some((field) => typeof model[field] !== "string"))
throw new HookContractError("hook input model is not a model");
if ("headers" in model)
throw new HookContractError("hook input model carries headers");
return { payload, model: wireJson(model, "model") };
}
/** The effective model a hand hands its hooks, as the loop sent it. */
export function hookModelOf(input) {
return input.model;
}
/** Serves one `hook.model_request`: claim first, then the closed input, then the hooks. */
export async function serveHookModelRequest(request, ports) {
const verdict = await ports.verifyClaim(request.claim);
if (verdict !== "valid")
throw new HookRequestRefusedError(verdict);
const input = parseHookRequestInput(request.input);
const produced = await ports.runRequestHooks(request.sessionId, input);
return { t: "hook.model_request.reply", sessionId: request.sessionId, stepId: request.stepId, ...produced };
}
const isHookFailure = (value) => isPlainObject(value) &&
typeof value.extensionPath === "string" &&
typeof value.event === "string" &&
typeof value.error === "string";
function hookFailures(value) {
if (!Array.isArray(value) || !value.every(isHookFailure))
throw new HookContractError("the hand's request-hook reply has malformed errors");
return value.map(({ extensionPath, event, error }) => ({ extensionPath, event, error }));
}
function wireList(value, at) {
if (!Array.isArray(value))
throw new HookContractError(`the hand's request-hook reply has malformed ${at}`);
return value.map((item, index) => wireJson(item, `${at}[${index}]`));
}
/**
* `runRequestHooks` over a hand's loop-hook runner (`LooplessHand.loopHooks`): the session's hooks run on the runtime of
* `scope`, inside a loop-hook call bound to that session, with the loop busy (a model request is mid-turn). The hooks'
* failures and what they sent travel with the output, as they do on every loop-hook reply.
*/
export function loopHookRequestHooks(loopHooks, scope) {
return async (sessionId, input) => {
const reply = await loopHooks("before_provider_request", {
scope: { id: scope.id, root: scope.root },
sessionId,
idle: false,
input,
});
if (!isPlainObject(reply))
throw new HookContractError("the hand's request-hook reply is not an object");
const { errors, sent, notices } = reply;
return {
output: parseHookRequestInput(reply.output),
...(errors === undefined ? {} : { errors: hookFailures(errors) }),
...(sent === undefined ? {} : { sent: wireList(sent, "sent") }),
...(notices === undefined ? {} : { notices: wireList(notices, "notices") }),
};
};
}
//# sourceMappingURL=hook-contract.js.map