Skip to content
Myr

Send a pi agent back at stop in a real session, and name only the refusals it can fix

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Review of 706. The settle handler skipped any event whose `context.canContinue` was false, and pi 1.0.3 computes that preview before a handler's entries: a run that ends on the agent's own reply reads false until a message is appended (`_buildBoundaryContext`, pi's `dist/core/agent-session.js`). So in a real session the policy was never asked and the agent was never sent back. - The settle now skips only a run that did not complete (aborted or errored). pi itself refuses a continuation without runnable context, and an Esc during the settle aborts it, so the dropped guard protected nothing. Checked against a real AgentSession over pi-ai's faux provider (a throwaway probe outside the repo): 1 provider call before, 4 after (three sends-back, the fourth settle stands); a second probe gave the brief once over two prompts and blocked a `write` to the config folder's project file with TouchedJudge's text, nothing written. - The send-back's entry names the refusals the agent can fix, as the stop hook's hold does (`explain(fixable)`), through one `fixable` helper the push block shares; when a policy holds on retryable refusals alone, it names those. - The handler runner is `reply`, not `answer`: Answer is a glossary noun, and the verdict text in the same file uses it in that sense. - Tests: the settle fixture now has `canContinue: false`, as pi sends it (red by assertion on six tests before the fix); added "sends back a completed run whose context ends on the agent's own reply" and "lists only the refusals the agent can fix, as the stop hook does"; the stopped-or-failed test drops its canContinue case. - Still for 799, outside the territory: the live edit guard (decide.ts's `toolRefusals`), one home for `sessionFacts`, and `--base` in PushCheck.

authored by oscabriel · committed by oscabriel · parent ed8b3f6 · Browse files · 2 files+109 added−38 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+109 added−38 removed

  • tests:+78 added−23 removed
  • other:+31 added−15 removed

2 files+109 added−38 removed

modified:apps/cli/src/pi.ts+31 added-15 removed
212 unmodified lines
213 Match.orElse(() => Option.none())214 );215216/**217 * The refusals retrying cannot help: the ones the agent must fix. A218 * retryable refusal is a wait (the repo was busy), as the stop hook reads it.219 */220const fixable = (refusals: readonly Refusal[]) =>221 refusals.filter((refusal) => !refusal.retryable);222223/**224 * pi's block for what the gate would refuse that retrying cannot help, with225 * the gateway's own text; a retryable refusal is a wait, never a block.226 */227const blockFor = (228 refusals: Option.Option<Array.NonEmptyReadonlyArray<Refusal>>229): Option.Option<ToolCallEventResult> => {223 const final = Option.getOrElse(refusals, () => []).filter(224 (refusal) => !refusal.retryable225 );230 const final = fixable(Option.getOrElse(refusals, () => []));231232 return Array.isReadonlyArrayNonEmpty(final)233 ? Option.some({ block: true, reason: explain(final).join("\n") })234 : Option.none();235};236237/**238 * What a verdict tells the agent to act on: the refusals it can fix, as the239 * stop hook's hold names them, or every refusal when the policy holds on240 * retryable ones alone.241 */242const toActOn = (refusals: Array.NonEmptyReadonlyArray<Refusal>) =>243 Array.match(fixable(refusals), {244 onEmpty: () => refusals,245 onNonEmpty: (final) => final,246 });247248/** The session a handler runs in. */249const sessionOf = (ctx: PiContext): PiSession => ({250 cwd: ctx.cwd,251 id: ctx.sessionManager.getSessionId(),
3 unmodified lines
255const firstLine = (cause: Cause.Cause<unknown>) =>256 String(Cause.squash(cause)).split("\n")[0] ?? "unknown failure";257258/**243 * Runs one handler's answer for pi, which awaits a promise. The gate stays259 * Runs one handler's reply for pi, which awaits a promise. The gate stays260 * the authority, so a policy that fails, or any defect, lets pi go on as it261 * would without the adapter (a `tool_call` handler that rejects would block262 * the tool), and says why through `ctx.ui.notify` when pi gives one.263 */248const answer = <A>(264const reply = <A>(265 ctx: PiContext,266 event: keyof PiHandlers,267 decided: Effect.Effect<Option.Option<A>, HookFailed>268): Promise<A | undefined> =>
30 unmodified lines
299 // so each session gets it once, at its first prompt with a claim.300 pi.on("before_agent_start", (_event, ctx) => {301 const session = sessionOf(ctx);302287 return answer(303 return reply(304 ctx,305 "before_agent_start",306 briefed.has(session.id)307 ? Effect.succeedNone
14 unmodified lines
322 );323 });324325 pi.on("tool_call", (event, ctx) =>310 answer(326 reply(327 ctx,328 "tool_call",329 Option.match(guardedCall(event), {330 onNone: () => Effect.succeedNone,
3 unmodified lines
334 )335 );336337 // Only a verdict the agent can act on sends it back, at most `most`322 // times a session, and only a run that completed and can go on: a run323 // the person stopped, or one that failed, stays stopped. Otherwise the324 // policy is not even asked.338 // times a session, and only a run that completed: a run the person339 // stopped, or one that failed, stays stopped. Otherwise the policy is340 // not even asked. `event.context.canContinue` is no guide: pi computes341 // it before this handler's entry, and a run that ends on the agent's own342 // reply reads false until the verdict is appended.343 pi.on("agent_before_settle", (event, ctx) => {344 const session = sessionOf(ctx);345 const used = continued.get(session.id) ?? 0;346329 const ended = event.outcome !== "completed" || !event.context.canContinue;330331 return answer(347 return reply(348 ctx,349 "agent_before_settle",334 ended || used >= most350 event.outcome !== "completed" || used >= most351 ? Effect.succeedNone352 : Effect.flatMap(deps.settle(session), (verdict) =>353 SettleVerdict.$is("Refused")(verdict) && verdict.actionable354 ? Effect.sync(() => {
2 unmodified lines
357 return Option.some<AgentBeforeSettleEventResult>({358 continue: true,359 entries: [360 ...event.entries,345 verdictEntry(verdict.refusals),361 verdictEntry(toActOn(verdict.refusals)),362 ],363 });364 })365 : Effect.succeedNone
155 unmodified lines
modified:apps/cli/test/pi.test.ts+78 added-23 removed
197 unmodified lines
198 toolName: "bash",199 type: "tool_call",200});201202/** A settle with `entries` already proposed by earlier handlers. */202/**203 * A completed run's settle with `entries` already proposed by earlier204 * handlers, as pi 1.0.3 hands it over: the run ended on the agent's own205 * reply, so the preview says it cannot go on (`canContinue` is false while206 * the last message is the assistant's, `_buildBoundaryContext` in207 * `dist/core/agent-session.js`) until a handler appends a message.208 */209const settleOf = (entries: SessionBoundaryDraft[]): AgentBeforeSettleEvent => ({210 context: {205 canContinue: true,211 canContinue: false,212 contextEntries: [],213 contextMessages: [],214 llmMessages: [],215 pendingMessages: [],
333 unmodified lines
549 })550 );551552 it.effect(547 "never sends back a run that was stopped, failed, or cannot go on",553 "sends back a completed run whose context ends on the agent's own reply",554 () =>555 Effect.gen(function* () {550 const ended: readonly AgentBeforeSettleEvent[] = [551 { ...settleOf([]), outcome: "aborted" },552 { ...settleOf([]), outcome: "error" },556 const { asked, handlers } = loaded({ settle: refused(true) });557 const { ctx } = contextOf("s1");558 const event = settleOf([]);559560 const result = yield* fire(handlers.agent_before_settle, event, ctx);561562 // The verdict the adapter appends is what lets the run go on.563 expect({564 asked,565 canContinue: event.context.canContinue,566 continued: result?.continue,567 entries: result?.entries?.length,568 }).toStrictEqual({569 asked: ["settle s1"],570 canContinue: false,571 continued: true,572 entries: 1,573 });574 })575 );576577 it.effect(578 "lists only the refusals the agent can fix, as the stop hook does",579 () =>580 Effect.gen(function* () {581 const { handlers } = loaded({582 settle: () =>583 SettleVerdict.Refused({584 actionable: true,585 refusals: [new RepoBusy(), outside],586 }),587 });588589 const { ctx } = contextOf("s1");590591 const result = yield* fire(592 handlers.agent_before_settle,593 settleOf([]),594 ctx595 );596597 expect(result?.entries).toStrictEqual([598 {554 ...settleOf([]),555 context: { ...settleOf([]).context, canContinue: false },599 content: [600 `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:`,601 ...explain([outside]),602 ].join("\n"),603 customType: `${Brand.slug}-verdict`,604 display: true,605 type: "custom_message",606 },557 ];607 ]);608 })609 );610559 for (const event of ended) {560 const { asked, handlers } = loaded({ settle: refused(true) });561 const { ctx } = contextOf("s1");611 it.effect("never sends back a run the person stopped or that failed", () =>612 Effect.gen(function* () {613 const ended: readonly AgentBeforeSettleEvent[] = [614 { ...settleOf([]), outcome: "aborted" },615 { ...settleOf([]), outcome: "error" },616 ];617563 const result = yield* fire(564 handlers.agent_before_settle,565 event,566 ctx567 );618 for (const event of ended) {619 const { asked, handlers } = loaded({ settle: refused(true) });620 const { ctx } = contextOf("s1");621622 const result = yield* fire(handlers.agent_before_settle, event, ctx);623569 expect({ asked, result }).toStrictEqual({570 asked: [],571 result: undefined,572 });573 }574 })624 expect({ asked, result }).toStrictEqual({625 asked: [],626 result: undefined,627 });628 }629 })630 );631632 it.effect(633 "never continues on a landing, a wait, or a refusal the agent cannot act on",
301 unmodified lines