hook.ts
This file
Path
apps/cli/src/hook.ts
193 lines · 5.6 KiB · TypeScript
Last changed by
Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f
History of this fileTake it
The walk stopped after 200 commits: lines older than 10c8b54 point at it.
Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f
line 1why, one step back1// The gateway is the authority, so the hook fails open: on anything it cannot judge it prints `{}` and exits 0.Merge branch 'build/906-platform-root-page'oscabrielbefore adoption10c8b54
lines 2–53why, one step back2import { HookEvent } from "@repo/agent-kit/hook-events";3import { Brand } from "@repo/brand";4import {5 Cause,6 Console,7 Effect,8 Option,9 Runtime,10 Schema,11 Stdio,12 Stream,13} from "effect";14import { Argument, Command, Flag } from "effect/cli";1516import { decideHook } from "./hook/decide.ts";17import type { HookOutput } from "./hook/decide.ts";18import { gatherFacts } from "./hook/facts.ts";19import { decodeHookInput } from "./hook/input.ts";20import type { HookInput } from "./hook/input.ts";21import { PushCheck, PushCheckChild } from "./hook/push-check.ts";22import type { PushCheckFailed } from "./hook/push-check.ts";23import { loadSession, saveSession } from "./hook/session.ts";24import type { SessionState } from "./hook/session.ts";25import { Output } from "./output.ts";2627const EVENTS = HookEvent.literals.join(", ");2829export class HookUsage extends Schema.TaggedError<HookUsage>()("HookUsage", {30 event: Schema.String,31}) {32 override readonly [Runtime.errorExitCode] = 2;33 override readonly [Runtime.errorReported] = false;3435 override get message() {36 return `hook: no event ${this.event}; the events are ${EVENTS}`;37 }38}3940const decodeEvent = Schema.decodeUnknownOption(HookEvent);4142const stdinText = Effect.flatMap(Stdio.Stdio, ({ stdin }) =>43 stdin.pipe(Stream.decodeText(), Stream.mkString)44);4546const pushCheck = Effect.flatMap(47 Effect.serviceOption(PushCheck),48 Option.match({49 onNone: () => Effect.provide(Effect.service(PushCheck), PushCheckChild),50 onSome: Effect.succeed,51 })52);53Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f
line 54why, one step back54/** `pre-tool-use` never asks the platform, so an edit never waits on the network. */Merge branch 'build/906-platform-root-page'oscabrielbefore adoption10c8b54
lines 55–193why, one step back55const sessionFacts = (event: HookEvent, input: HookInput) =>56 Effect.gen(function* () {57 const kept = yield* loadSession(input.session_id);5859 if (60 Option.isSome(kept) &&61 (kept.value.claim !== undefined || event === "pre-tool-use")62 ) {63 return kept.value;64 }6566 const gathered = yield* gatherFacts(input.cwd);6768 yield* saveSession(input.session_id, gathered).pipe(69 Effect.catchTag("SessionUnsaved", (unsaved) =>70 Output.use((output) => output.note(unsaved.message))71 )72 );7374 return gathered;75 });7677const refusalsFor = (event: HookEvent, state: SessionState) => {78 const { claim } = state;7980 return event === "stop" && claim !== undefined81 ? Effect.flatMap(pushCheck, (check) => check.run(state.root, claim.base))82 : Effect.succeed([]);83};8485const answer = (event: HookEvent, input: HookInput) =>86 Effect.gen(function* () {87 const output = yield* Output;88 const state = yield* sessionFacts(event, input);8990 const decision = decideHook(event, input, {91 claim: Option.fromUndefinedOr(state.claim),92 holds: state.holds,93 judge: state.judge,94 refusals: yield* refusalsFor(event, state),95 root: state.root,96 });9798 const counted =99 decision.holds === state.holds100 ? true101 : yield* saveSession(input.session_id, {102 ...state,103 holds: decision.holds,104 }).pipe(105 Effect.as(true),106 Effect.catchTag("SessionUnsaved", (unsaved) =>107 Effect.as(output.note(unsaved.message), false)108 )109 );110111 // A hold the session cannot count could never reach the cap: allow.112 if (!counted && decision.holds > state.holds) {113 yield* output.note(114 `${event}: this hold could not be counted, so the agent may stop; ${Brand.cli} check still refuses its work`115 );116117 return {};118 }119120 // Why the session has no claim says more than the policy's "no claim".121 const why = Option.orElse(122 Option.fromUndefinedOr(state.why),123 () => decision.note124 );125126 if (Option.isSome(why)) {127 yield* output.note(`${event}: ${why.value}`);128 }129130 return decision.output;131 });132133const print = (json: boolean, output: HookOutput) =>134 Console.log(json ? JSON.stringify(output) : JSON.stringify(output, null, 2));135136const failOpen = (json: boolean, why: string) =>137 Effect.andThen(138 Output.use((output) => output.note(`hook: ${why}; allowing`)),139 print(json, {})140 );141142const run = (name: string, json: boolean) =>143 Effect.gen(function* () {144 const event = decodeEvent(name);145146 if (Option.isNone(event)) {147 return yield* new HookUsage({ event: name });148 }149150 const input = yield* Effect.flatMap(stdinText, decodeHookInput).pipe(151 Effect.option152 );153154 if (Option.isNone(input)) {155 return yield* failOpen(156 json,157 "could not read the harness's JSON on stdin"158 );159 }160161 return yield* answer(event.value, input.value).pipe(162 Effect.flatMap((output) => print(json, output)),163 Effect.catchTag("PushCheckFailed", (failed: PushCheckFailed) =>164 failOpen(json, failed.message)165 ),166 // Any defect of the hook's own: the gateway still judges the push.167 Effect.catchCauseIf(168 (cause) => !Cause.hasInterruptsOnly(cause),169 (cause) =>170 failOpen(json, String(Cause.squash(cause)).split("\n")[0] ?? "")171 )172 );173 });174175export const hook = Command.make(176 "hook",177 {178 event: Argument.String("event").pipe(179 Argument.withDescription(`The harness event: ${EVENTS}.`)180 ),181 json: Flag.Boolean("json").pipe(182 Flag.withDefault(false),183 Flag.withDescription(184 "Print the answer as one line of JSON, as a harness reads it; without it, indented."185 )186 ),187 },188 ({ event, json }) => run(event, json)189).pipe(190 Command.withDescription(191 "Answer a harness hook (session-start, pre-tool-use, stop) with the gate's policy."192 )193);