Skip to content
Myr

pi.ts

This file

Path

apps/cli/src/pi.ts

437 lines · 12.6 KiB · TypeScript

Last changed by

Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f

History of this file

Take it

1// Loaded at user level through the package's "pi" key, never from a project's `.pi/extensions/`: a stranger's repo runs no code in your harness.2import type {3  AgentBeforeSettleEvent,4  AgentBeforeSettleEventResult,5  BeforeAgentStartEvent,6  BeforeAgentStartEventResult,7  CustomMessageEntryDraft,8  ExtensionContext,9  ExtensionFactory,10  ExtensionUIContext,11  ToolCallEvent,12  ToolCallEventResult,13} from "@earendil-works/pi-coding-agent";14import {15  BunChildProcessSpawner,16  BunFileSystem,17  BunPath,18} from "@effect/platform-bun";19import { claudeEventOf } from "@repo/agent-kit/hook-events";20import type { HookEvent } from "@repo/agent-kit/hook-events";21import { Brand } from "@repo/brand";22import type { Client } from "@repo/protocol/contracts";23import type { Refusal } from "@repo/protocol/refusal";24import { explain } from "@repo/protocol/render";25import {26  Array,27  Cause,28  Data,29  Effect,30  Layer,31  Match,32  Option,33  Schema,34} from "effect";35import type { FileSystem, Path } from "effect";36import type { ChildProcessSpawner } from "effect/process";3738import { CredentialsFile } from "./credentials.ts";39import { decideHook, MAX_HOLDS, toolRefusals } from "./hook/decide.ts";40import type { HookFacts } from "./hook/decide.ts";41import { gatherFacts } from "./hook/facts.ts";42import type { HookInput } from "./hook/input.ts";43import { PushCheck, pushCheckWith } from "./hook/push-check.ts";44import { loadSession, saveSession } from "./hook/session.ts";45import type { SessionState } from "./hook/session.ts";46import { RemoteClient } from "./remote.ts";4748export class HookFailed extends Schema.TaggedError<HookFailed>()("HookFailed", {49  reason: Schema.String,50}) {51  override get message() {52    return `the hook policy gave no answer: ${this.reason}`;53  }54}5556export interface PiSession {57  readonly cwd: string;58  readonly id: string;59}6061export type GuardedCall =62  | { readonly _tag: "Write"; readonly file: string }63  | { readonly _tag: "Push" };6465export const GuardedCall = Data.taggedEnum<GuardedCall>();6667export type SettleVerdict =68  | { readonly _tag: "Landed" }69  | { readonly _tag: "Waiting" }70  | {71      readonly _tag: "Refused";72      readonly refusals: Array.NonEmptyReadonlyArray<Refusal>;73      readonly actionable: boolean;74    };7576export const SettleVerdict = Data.taggedEnum<SettleVerdict>();7778export interface PiDeps {79  readonly brief: (80    session: PiSession81  ) => Effect.Effect<Option.Option<string>, HookFailed>;82  readonly guardTool: (83    session: PiSession,84    call: GuardedCall85  ) => Effect.Effect<86    Option.Option<Array.NonEmptyReadonlyArray<Refusal>>,87    HookFailed88  >;89  readonly settle: (90    session: PiSession91  ) => Effect.Effect<SettleVerdict, HookFailed>;92}9394export type PiContext = Pick<ExtensionContext, "cwd"> & {95  readonly sessionManager: Pick<96    ExtensionContext["sessionManager"],97    "getSessionId"98  >;99  readonly ui?: Pick<ExtensionUIContext, "notify">;100};101102export interface PiHandlers {103  readonly agent_before_settle: (104    event: AgentBeforeSettleEvent,105    ctx: PiContext106  ) => Promise<AgentBeforeSettleEventResult | undefined>;107  readonly before_agent_start: (108    event: BeforeAgentStartEvent,109    ctx: PiContext110  ) => Promise<BeforeAgentStartEventResult | undefined>;111  readonly tool_call: (112    event: ToolCallEvent,113    ctx: PiContext114  ) => Promise<ToolCallEventResult | undefined>;115}116117export interface PiEvents {118  readonly on: {119    (120      event: "agent_before_settle",121      handler: PiHandlers["agent_before_settle"]122    ): () => void;123    (124      event: "before_agent_start",125      handler: PiHandlers["before_agent_start"]126    ): () => void;127    (event: "tool_call", handler: PiHandlers["tool_call"]): () => void;128  };129}130131export interface PiOptions {132  readonly maxContinuations?: number;133}134135const BRIEF = `${Brand.slug}-brief`;136137const VERDICT = `${Brand.slug}-verdict`;138139const verdictEntry = (140  refusals: Array.NonEmptyReadonlyArray<Refusal>141): CustomMessageEntryDraft => ({142  content: [143    `The gate refuses this answer as it stands, so you are not done. Fix what follows, then run \`${Brand.cli} check\` before you push again:`,144    ...explain(refusals),145  ].join("\n"),146  customType: VERDICT,147  display: true,148  type: "custom_message",149});150151const decodeFile = Schema.decodeUnknownOption(152  Schema.Struct({ path: Schema.String })153);154155const decodeCommand = Schema.decodeUnknownOption(156  Schema.Struct({ command: Schema.String })157);158159/** Matches a push after any git options; a false match only runs the preflight. */160const GIT_PUSH =161  /(?:^|[\s;&|(`])git(?:\s+-[Cc]\s+\S+|\s+-\S+)*\s+push(?![\w-])/u;162163const guardedCall = (event: ToolCallEvent): Option.Option<GuardedCall> =>164  Match.value(event.toolName).pipe(165    Match.when(Match.is("edit", "write"), () =>166      Option.map(decodeFile(event.input), ({ path }) =>167        GuardedCall.Write({ file: path })168      )169    ),170    Match.when("bash", () =>171      Option.flatMap(decodeCommand(event.input), ({ command }) =>172        GIT_PUSH.test(command) ? Option.some(GuardedCall.Push()) : Option.none()173      )174    ),175    Match.orElse(() => Option.none())176  );177178const fixable = (refusals: readonly Refusal[]) =>179  refusals.filter((refusal) => !refusal.retryable);180181const blockFor = (182  refusals: Option.Option<Array.NonEmptyReadonlyArray<Refusal>>183): Option.Option<ToolCallEventResult> => {184  const final = fixable(Option.getOrElse(refusals, () => []));185186  return Array.isReadonlyArrayNonEmpty(final)187    ? Option.some({ block: true, reason: explain(final).join("\n") })188    : Option.none();189};190191const toActOn = (refusals: Array.NonEmptyReadonlyArray<Refusal>) =>192  Array.match(fixable(refusals), {193    onEmpty: () => refusals,194    onNonEmpty: (final) => final,195  });196197const sessionOf = (ctx: PiContext): PiSession => ({198  cwd: ctx.cwd,199  id: ctx.sessionManager.getSessionId(),200});201202const firstLine = (cause: Cause.Cause<unknown>) =>203  String(Cause.squash(cause)).split("\n")[0] ?? "unknown failure";204205/** A rejecting `tool_call` handler would block the tool, so a failing policy or defect lets pi go on. */206const reply = <A>(207  ctx: PiContext,208  event: keyof PiHandlers,209  decided: Effect.Effect<Option.Option<A>, HookFailed>210): Promise<A | undefined> =>211  Effect.runPromise(212    decided.pipe(213      Effect.catchCause((cause) =>214        Effect.as(215          Effect.sync(() =>216            ctx.ui?.notify(217              `${Brand.cli} ${event}: ${firstLine(cause)}; allowing, and the gateway still judges every push`,218              "warning"219            )220          ),221          Option.none<A>()222        )223      ),224      Effect.map(Option.getOrUndefined)225    )226  );227228export const piAdapter =229  (deps: PiDeps, options: PiOptions = {}) =>230  (pi: PiEvents): void => {231    const most = options.maxContinuations ?? MAX_HOLDS;232    const continued = new Map<string, number>();233    const briefed = new Set<string>();234235    // pi starts the agent on every prompt; each session gets the brief once.236    pi.on("before_agent_start", (_event, ctx) => {237      const session = sessionOf(ctx);238239      return reply(240        ctx,241        "before_agent_start",242        briefed.has(session.id)243          ? Effect.succeedNone244          : deps.brief(session).pipe(245              Effect.tap((brief) =>246                Effect.sync(() => {247                  if (Option.isSome(brief)) {248                    briefed.add(session.id);249                  }250                })251              ),252              Effect.map(253                Option.map((content): BeforeAgentStartEventResult => ({254                  message: { content, customType: BRIEF, display: true },255                }))256              )257            )258      );259    });260261    pi.on("tool_call", (event, ctx) =>262      reply(263        ctx,264        "tool_call",265        Option.match(guardedCall(event), {266          onNone: () => Effect.succeedNone,267          onSome: (call) =>268            Effect.map(deps.guardTool(sessionOf(ctx), call), blockFor),269        })270      )271    );272273    // Only a completed run with an actionable verdict is sent back, at most `most` times.274    // `event.context.canContinue` is no guide: pi computes it before this handler's entry.275    pi.on("agent_before_settle", (event, ctx) => {276      const session = sessionOf(ctx);277      const used = continued.get(session.id) ?? 0;278279      return reply(280        ctx,281        "agent_before_settle",282        event.outcome !== "completed" || used >= most283          ? Effect.succeedNone284          : Effect.flatMap(deps.settle(session), (verdict) =>285              SettleVerdict.$is("Refused")(verdict) && verdict.actionable286                ? Effect.sync(() => {287                    continued.set(session.id, used + 1);288289                    return Option.some<AgentBeforeSettleEventResult>({290                      continue: true,291                      entries: [292                        ...event.entries,293                        verdictEntry(toActOn(verdict.refusals)),294                      ],295                    });296                  })297                : Effect.succeedNone298            )299      );300    });301  };302303const factsOf = (session: PiSession, look: boolean) =>304  Effect.gen(function* () {305    const kept = yield* loadSession(session.id);306307    if (Option.isSome(kept) && (kept.value.claim !== undefined || !look)) {308      return kept.value;309    }310311    const gathered = yield* gatherFacts(session.cwd);312313    // A cache: facts that cannot be kept are gathered again next time.314    yield* Effect.ignore(saveSession(session.id, gathered));315316    return gathered;317  });318319/** Holds are 0: the adapter counts pi's continuations itself. */320const hookFacts = (321  state: SessionState,322  refusals: readonly Refusal[]323): HookFacts => ({324  claim: Option.fromUndefinedOr(state.claim),325  holds: 0,326  judge: state.judge,327  refusals,328  root: state.root,329});330331const hookInput = (event: HookEvent, session: PiSession): HookInput => ({332  cwd: session.cwd,333  hook_event_name: claudeEventOf[event],334  session_id: session.id,335});336337const localCheck = ({ claim, root }: SessionState) =>338  claim === undefined339    ? Effect.succeed<readonly Refusal[]>([])340    : Effect.flatMap(Effect.service(PushCheck), (check) =>341        check.run(root, claim.base)342      );343344export type PolicyServices =345  | ChildProcessSpawner.ChildProcessSpawner346  | Client347  | FileSystem.FileSystem348  | Path.Path349  | PushCheck;350351export const policyDeps = (services: Layer.Layer<PolicyServices>): PiDeps => ({352  brief: (session) =>353    Effect.gen(function* () {354      const state = yield* factsOf(session, true);355356      const { output } = decideHook(357        "session-start",358        hookInput("session-start", session),359        hookFacts(state, [])360      );361362      return "hookSpecificOutput" in output &&363        "additionalContext" in output.hookSpecificOutput364        ? Option.some(output.hookSpecificOutput.additionalContext)365        : Option.none();366    }).pipe(Effect.provide(services)),367368  guardTool: (session, call) =>369    GuardedCall.$match(call, {370      Push: () =>371        Effect.gen(function* () {372          const refusals = yield* localCheck(yield* factsOf(session, false));373374          return Array.isReadonlyArrayNonEmpty(refusals)375            ? Option.some(refusals)376            : Option.none();377        }).pipe(378          Effect.mapError(379            (failed) => new HookFailed({ reason: failed.message })380          ),381          Effect.provide(services)382        ),383      Write: ({ file }) =>384        Effect.map(factsOf(session, false), (state) =>385          Array.match(386            toolRefusals(387              {388                ...hookInput("pre-tool-use", session),389                tool_input: { file_path: file },390                tool_name: "Write",391              },392              hookFacts(state, [])393            ),394            {395              onEmpty: () => Option.none(),396              onNonEmpty: (refusals) => Option.some(refusals),397            }398          )399        ).pipe(Effect.provide(services)),400    }),401402  settle: (session) =>403    Effect.gen(function* () {404      const state = yield* factsOf(session, true);405      const refusals = yield* localCheck(state);406407      if (!Array.isReadonlyArrayNonEmpty(refusals)) {408        return SettleVerdict.Waiting();409      }410411      const { output } = decideHook(412        "stop",413        hookInput("stop", session),414        hookFacts(state, refusals)415      );416417      return SettleVerdict.Refused({418        actionable: "decision" in output,419        refusals,420      });421    }).pipe(422      Effect.mapError((failed) => new HookFailed({ reason: failed.message })),423      Effect.provide(services)424    ),425});426427const LiveServices = Layer.mergeAll(428  RemoteClient.pipe(Layer.provide(CredentialsFile)),429  pushCheckWith([Brand.cli])430).pipe(431  Layer.provideMerge(BunChildProcessSpawner.layer),432  Layer.provideMerge(Layer.mergeAll(BunFileSystem.layer, BunPath.layer))433);434435export const livePiDeps = policyDeps(LiveServices);436437export default piAdapter(livePiDeps) satisfies ExtensionFactory;