Repository navigation
fix(pi): prevent ask_user batch errors and retry loops #177
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
sajor2000
wants to merge
1
commit into
main
Choose a base branch
from
fix/pi-ask-user-batch-padding-pr
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,96 @@ | ||
| import type { PiExtensionFile } from "../types/pi" | ||
|
|
||
| /** Standalone runtime adapter: keep the community UI and its approval semantics. */ | ||
| export function piAskUserGuard(): PiExtensionFile { | ||
| return { name: "methodsmith-ask-user-guard.ts", content: PI_ASK_USER_GUARD } | ||
| } | ||
|
|
||
| // No host-package imports: this file also loads on older Pi versions. It does | ||
| // not inspect credentials, answers, patient files, or settings. Only transient | ||
| // hashes of failed ask arguments are retained, never their contents. | ||
| const PI_ASK_USER_GUARD = String.raw`import { createHash } from "node:crypto"; | ||
|
|
||
| type Params = Record<string, unknown>; | ||
| type Event = { | ||
| toolName?: string; | ||
| toolCallId?: string; | ||
| input?: Params; | ||
| args?: unknown; | ||
| isError?: boolean; | ||
| }; | ||
| type Block = { block: true; reason: string; terminate: true }; | ||
| type Context = { abort(): void }; | ||
| type Pi = { on(name: string, handler: (event: Event, ctx?: Context) => Block | void): unknown }; | ||
|
|
||
| const ENTRY_FIELDS = ["context", "options", "allowMultiple", "allowFreeform"] as const; | ||
| const FALLBACK = " Ask one focused question in chat and wait for the user's answer. No approval is inferred; keep all safeguards in place."; | ||
|
|
||
| export function normalizeBatchPadding(params: Params): void { | ||
| // Invalid arrays stay invalid. Do not invent a batch or move question data. | ||
| if (!Array.isArray(params.questions) || params.questions.length < 2 || params.questions.length > 4) return; | ||
| if (typeof params.context === "string" && params.context.trim() === "") delete params.context; | ||
| if (Array.isArray(params.options) && params.options.length === 0) delete params.options; | ||
| // These are the tool's documented neutral defaults, not permission choices. | ||
| // Every entry's own flags remain untouched, including non-default flags. | ||
| if (params.allowMultiple === false) delete params.allowMultiple; | ||
| if (params.allowFreeform === true) delete params.allowFreeform; | ||
| const conflicts = ENTRY_FIELDS.filter((field) => params[field] != null); | ||
| if (conflicts.length) { | ||
| throw new Error("ask_user batch has meaningful or invalid top-level fields: " + conflicts.join(", ") | ||
| + ". Put these fields on each questions entry; do not discard their meaning." + FALLBACK); | ||
| } | ||
| } | ||
|
|
||
| function canonical(value: unknown): unknown { | ||
| if (Array.isArray(value)) return value.map(canonical); | ||
| if (value !== null && typeof value === "object") { | ||
| return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)) | ||
| .map(([key, child]) => [key, canonical(child)])); | ||
| } | ||
| return value; | ||
| } | ||
|
|
||
| function fingerprint(value: unknown): string { | ||
| return createHash("sha256").update(JSON.stringify(canonical(value)) ?? "undefined").digest("hex"); | ||
| } | ||
|
|
||
| export default function(pi: Pi): void { | ||
| const calls = new Map<string, string>(); | ||
| const failed = new Set<string>(); | ||
| const remember = (digest: string) => { | ||
| failed.add(digest); | ||
| if (failed.size > 32) failed.delete(failed.values().next().value!); | ||
| }; | ||
| const reset = () => { calls.clear(); failed.clear(); }; | ||
| pi.on("session_start", reset); | ||
| pi.on("input", reset); | ||
| pi.on("tool_call", (event) => { | ||
| if (event.toolName !== "ask_user" || !event.input) return; | ||
| try { | ||
| normalizeBatchPadding(event.input); | ||
| } catch (error) { | ||
| remember(fingerprint(event.input)); | ||
| return { block: true, terminate: true, reason: (error as Error).message }; | ||
| } | ||
| const digest = fingerprint(event.input); | ||
| if (failed.has(digest)) { | ||
| return { block: true, terminate: true, | ||
| reason: "Do not repeat the same failed ask_user call. Correct its arguments once or use the chat fallback." + FALLBACK }; | ||
| } | ||
| if (event.toolCallId) calls.set(event.toolCallId, digest); | ||
| }); | ||
| pi.on("tool_execution_end", (event, ctx) => { | ||
| if (event.toolName !== "ask_user") return; | ||
| const digest = event.toolCallId ? calls.get(event.toolCallId) : undefined; | ||
| if (event.isError) { | ||
| const key = digest ?? fingerprint(event.args); | ||
| const repeated = failed.has(key); | ||
| remember(key); | ||
| // Schema failures skip tool_call. Stop their second identical failure | ||
| // here so they cannot spin forever outside the normalizing hook. | ||
| if (repeated) ctx?.abort(); | ||
| } | ||
| if (event.toolCallId) calls.delete(event.toolCallId); | ||
| }); | ||
| } | ||
| ` | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Capture schema-failure arguments before execution ends.
Pi's
tool_execution_endevent has noargsfield, including in v0.73.1. Schema failures also skiptool_call, so this branch fingerprintsundefinedfor every schema failure. Two different invalid calls therefore triggerctx.abort()as if the second call repeated the first. This stops recovery for corrected or unrelated questions. (raw.githubusercontent.com)Capture the argument digest in
tool_execution_start, keyed bytoolCallId. Replace that digest after normalization intool_call. Do not classify an unavailable digest as a shared failed input. Update the test helper to omitargsfrom end events.