# Consultations

## The Executor and the Advisor

The Executor is the model of your pi session or spawned yaag Agent.
The Advisor is a second model that reads the Executor's transcript and returns advice.
A Consultation is one Advisor call. It is not a yaag Ask.
A Prompt Cycle starts with one user message and ends when the Executor stops for the next message.
An Ask starts a Prompt Cycle in a spawned Agent.

The Advisor has no tools. It changes no files and never writes to the user.
The Executor decides how to use the advice. It must compare the advice with the facts.

## The `advisor` tool

For Client-side Consultations, `advisor` requires a `question` of at most 2,000 characters.
Name the decision or problem in the question. The optional `checkpoint` accepts:

- `planning`
- `stuck`
- `before_done`

The checkpoint is a hint. The Advisor can change it.
The Advisor is instructed to write at most 300 words as plain text.
The advice names a checkpoint and gives a verdict, one to three numbered actions, and optional risks.
The result header identifies the Advisor model, thinking level, and Consultation index and limit.

### Consultation limits

`maxConsultations` limits Consultations in each Prompt Cycle. The default is three.
The Executor can make only one Consultation per assistant message.
If it calls `advisor` twice in one message, only the first call can proceed.

A sent request counts even when it fails, times out, returns empty advice, or is aborted.
An abort before the request does not count.
Unavailable models, missing authentication, and invalid redaction patterns do not count.
Duplicate and exhausted-limit results do not count.
Two attempts after empty advice still count as one Consultation.
The package keeps completed, nonempty advice when a timeout or user abort arrives after the reply.
Cancellation that stops the reply still gives a timeout or aborted result.
See [Troubleshooting](troubleshooting.md) for the exact failures and recovery steps.

## How the mechanism follows the Executor

The Advisor State is fixed for each Prompt Cycle:

- **Off:** settings have an error, no Advisor model is set, or the model does not resolve.
- **Native:** the Executor uses a `yaag-advisor` model and Native Consultations are not disabled for the session.
- **Client-side:** settings and model availability permit advice, but the native conditions do not apply.

Settings and an available, authenticated Advisor model are prerequisites for both mechanisms.
The native mechanism sends a server tool, not the client-side pi tool.
The client-side tool must be allowed and active before the Executor can call it.
A hermetic tool list does not automatically gain `advisor`.

Settings and model changes take effect at the next Prompt Cycle.
A switch away from `yaag-advisor` selects Client-side Consultations.
A switch back can select Native Consultations again.
An invalid Executor/Advisor pair disables Native Consultations for the whole session.
Recovery then uses Client-side Consultations from the next Prompt Cycle.
See [native notices](troubleshooting.md#native-notices).

Native Consultations require the CLIProxyAPI proxy.
Place `cliproxyapi.json`, with `baseUrl` and `apiKey`, in pi's agent directory.
`PI_CODING_AGENT_DIR` changes that directory.
Without valid proxy configuration, the package registers no `yaag-advisor` models.
The Advisor `thinking` setting has no effect on Native Consultations.
Anthropic controls native thinking.

## Advisor Triggers

A trigger sends a message that asks the Executor to start a Consultation.
The message is not itself a Consultation. The Executor subsequently calls `advisor`.
Each trigger message costs one Executor request.
A yaag Ask's `maxTurns` counts that turn.
The subsequent Consultation can add Advisor cost too.

Both triggers need these conditions:

- The trigger is enabled.
- A Consultation mechanism is available.
- Consultations remain in this Prompt Cycle.
- No messages are pending.
- The activity outcome is completed, not an error or abort.

### Before done

Before the Executor stops, the package checks `triggers.beforeDone.minToolCalls`.
The default minimum is three tool calls in the Prompt Cycle.
The last tool call must not be a Consultation.
The trigger sends its message at most once per Prompt Cycle.

The client-side message and native message differ. Only the client-side message names a checkpoint.

<!-- quote: src/trigger/trigger-texts.ts -->
> Before you finish, call advisor with checkpoint before_done. Ask about the risks of your change. Then do what the advice tells you. Then write your complete final answer again.

<!-- quote: src/trigger/trigger-texts.ts -->
> Before you finish, call advisor. Then do what the advice tells you. Then write your complete final answer again.

### Stuck

The package checks consecutive failed tool results and repeated failed calls after a turn with tool results.
`triggers.stuck.errors` defaults to 3.
`triggers.stuck.repeats` defaults to 2.
The same-call count includes only failed calls.
Repeated calls have the same tool name and canonical arguments.
If both thresholds apply, the error reason takes precedence.

A successful tool result or a Consultation resets both counts.
Successful polling does not cause a stuck message.
Any client-side `advisor` result resets the counts, including a failure or skipped result.
A native Advisor call also resets them.
After a stuck message, the package suppresses further stuck messages until a reset.
A new Prompt Cycle also starts new counts.

The examples below use three failed calls or two identical failed calls. Each mechanism has its own message.

<!-- quote: src/trigger/trigger-texts.ts -->
> The last 3 tool calls failed. Call advisor with checkpoint stuck. In your question, describe what you tried.

<!-- quote: src/trigger/trigger-texts.ts -->
> The last 3 tool calls failed. Call advisor before you try again.

<!-- quote: src/trigger/trigger-texts.ts -->
> You made the same tool call 2 times in a row. Call advisor with checkpoint stuck. In your question, describe what you tried.

<!-- quote: src/trigger/trigger-texts.ts -->
> You made the same tool call 2 times in a row. Call advisor before you try again.

<!-- quote: src/trigger/trigger-texts.ts -->
> The last 3 tool calls failed.

<!-- quote: src/trigger/trigger-texts.ts -->
> You made the same tool call 2 times in a row.

## What the Advisor sees

A Client-side Consultation receives the effective branch context after compaction, not the entire session file.
It includes earlier Consultation results and current Prompt Cycle thinking only.
It excludes encrypted and redacted thinking, including thinking signatures.
Images become text placeholders. Custom messages remain when pi retains them for model context.

The package cuts tool results to 4,000 characters and each tool-call argument to 2,000 characters.
The transcript budget uses the smaller of `maxTranscriptTokens` and the room in the Advisor context window.
It reserves the Advisor's maximum output tokens, its system prompt estimate, and five percent of the context window.
An unknown context window uses the configured cap.

When the transcript exceeds the budget, the package removes the oldest unpinned messages first.
It keeps the first user message in effective context and all compaction summaries.
These preserved messages can exceed the budget by themselves.
An omission marker reports the number of removed messages.

The Advisor also receives project context files, active tool names, the question, and the checkpoint hint.
It receives its own Advisor system prompt, not the Executor's full system prompt.
Native Consultations instead use the Executor request that Anthropic already holds.

## Redaction

Client-side Consultations apply fixed patterns for these secret categories:

- PEM private keys and JWTs.
- Authorization header values and Bearer tokens.
- Anthropic and OpenAI API keys.
- GitHub tokens, AWS access key IDs, and Slack tokens.
- Environment assignments whose names contain API key, secret, token, password, passwd, credential, authorization, or cookie terms.

Custom `redact` regular expressions from both settings files run after the fixed patterns.
The package combines global patterns first, then project patterns, and removes exact duplicates.
Custom patterns use the global regular-expression flag.
Matches become `<redacted:<kind>>`, such as `<redacted:custom>`.
Zero-length matches do not count as redactions.

The order is serialize → redact → cut → budget.
The implementation redacts the serialized transcript, before cuts can split a secret.
Project context files and the separately appended question do not pass through that redaction step.
Patterns cannot guarantee complete secret removal. Do not include secrets in questions or project context files.

Native Consultations get no redaction from this package.
Anthropic processes the Executor request already sent to its server.

## Transcript display

In the TUI, Client-side Consultations start collapsed.
The compact display identifies the model, checkpoint, Consultation count, and verdict when available.
Expansion shows the advice and statistics: sent and omitted messages, estimated tokens, redactions, and elapsed time.
Ctrl+O is pi's default expansion key. Custom pi keybindings can change it.
Failures show a short failure line, even when expanded. The underlying plain tool result retains the complete text.
Trigger messages show the trigger name and reason. Expansion shows the message sent to the Executor.

Native Consultations add display records with the model, count, encrypted-advice label, and cost.
The advice remains encrypted and unreadable to the user.
Expansion shows separate Advisor input and output token details.
Print and RPC modes retain plain result text without TUI rendering.

## Cost

Client-side Advisor tokens and cost enter the session totals.
Native Advisor tokens remain outside token totals, but native Advisor cost enters cost totals.
In native assistant messages, `usage.input`, `usage.output`, `usage.cacheRead`, and `usage.cacheWrite` remain Executor-only.
These token fields remain suitable for context sizing.
Do not add native Advisor tokens to the Executor's context estimate.

yaag reports combined Agent usage, not a separate Advisor breakdown.
Trigger messages also cost Executor requests. Provider rates determine the price.
An empty-advice retry can add token usage and cost within one Consultation.

## Spawned yaag Agents

1. Load `npm:@yaag/advisor` through a spawn's `extensions` or yaag configuration's `agents.extensions`.
2. For Client-side Consultations, list `"advisor"` in the Agent's `tools`, or use `inherit: true` without a `tools` list.
3. Configure the Advisor through its settings files or `YAAG_ADVISOR_MODEL` and `YAAG_ADVISOR_THINKING`.

The Advisor package must load, and an authenticated Advisor model must resolve.
An explicit tool list or exclusion can still prevent access to `advisor`.
Extension CLI flags do not reach spawned Agents.
The Agent's Executor model is separate from the configured Advisor model.
A `yaag-advisor` Executor model selects Native Consultations, subject to the normal settings, model, and proxy prerequisites.
Native Consultations use the server tool rather than the pi `advisor` tool.

Spawned Agents use saved project trust decisions. They cannot prompt you to trust a project.
Warnings appear on stderr, including in RPC mode.
See [configuration](configuration.md) and [troubleshooting](troubleshooting.md) for settings and recovery.
Return to the [README](../README.md).
