Adds `pi.on("credential_disabled", handler)` so extensions can react to
soft-disabled credentials (e.g. OAuth invalid_grant) without regex-matching
`agent_end` errorMessages.
`AuthStorage.onCredentialDisabled(listener)` returns an unsubscribe function;
multiple listeners fire for every event with per-listener exception isolation
and FIFO buffer-and-replay (cap 32) when none are attached. The constructor
option from #991 stays as sugar for an immediate permanent subscription.
`createAgentSession()` subscribes the per-session extension runner to
`modelRegistry.authStorage` immediately after resolution and unsubscribes on
dispose / startup failure. Events are forwarded via
`ExtensionRunner.emitCredentialDisabled(event)`, which buffers (cap 32,
drop-oldest) until `runner.initialize(...)` runs in the mode controller so
extension handlers see real UI/runtime context, not the constructor no-op
defaults.
Supersedes #997. Builds on #991.
Co-Authored-By: omp <noreply@oh-my-pi.dev>
- Added parent-to-subagent artifact manager adoption so subagents reuse the parent `ArtifactManager` and write artifacts into a shared directory with shared IDs.
- Passed the shared artifact manager through tool/session context into subagent executor startup and exposed it via `SessionManager` and `ToolSession` for lookup.
- Updated kernel environment and artifact-resolution paths to prefer `PI_ARTIFACTS_DIR`, falling back to existing session-file-based behavior when absent.
- Skipped writing compact conversation context files when IRC is enabled so subagents avoid using stale markdown snapshots.
- In runSubprocess, passed an undefined context file for IRC-enabled paths and kept context file prompting for non-IRC executions.
Two-edge fix for a runtime circular-import TDZ that manifested as
`ReferenceError: Cannot access 'TaskTool' / 'SUBAGENT_WARNING_*' /
'MAX_OUTPUT_BYTES' before initialization.` whenever the executor module
graph and the task tool module graph were evaluated together (e.g.
`bun test executor-warnings.test.ts task-simple-mode.test.ts` in either
order, or the wider `task/ discovery/ task-simple-mode` combination).
The runtime cycle is
task/index.ts → ./executor → ../sdk → ./tools → ../task
closed by `tools/index.ts:285` eagerly dereferencing `TaskTool.create`
while the `task` module's body had not yet reached its `export class
TaskTool` declaration. The throw aborted `tools/index.ts`, which
propagated back through `sdk → executor`, leaving executor's body
suspended before its post-import `const`s (`SUBAGENT_WARNING_*`,
`MAX_OUTPUT_BYTES`) were initialized.
Two structural changes:
1. `tools/index.ts:285`: replace `task: TaskTool.create` with
`task: s => TaskTool.create(s)`. Defers the `TaskTool` binding
dereference to factory-call time, by which point the cycle has
fully unwound. Matches the lazy-factory shape every other
`BUILTIN_TOOLS` entry already uses.
2. `task/executor.ts:31`: split the `"../tools"` import. Source
`truncateTail` directly from its leaf module
`../session/streaming-output` (the barrel was just re-exporting
it). Keep `ContextFileEntry` as a type-only import — erased at
runtime, so no participation in the cycle.
Neither change touches tests, test runners, or removes the cycle in
source. They eliminate the eager dereferences that turned a benign
linker-level cycle into a TDZ at evaluation time.
Verified:
- `bun test executor-warnings.test.ts task-simple-mode.test.ts`
passes in both orderings (11/11).
- Wider `bun test packages/coding-agent/test/task/
packages/coding-agent/test/discovery/
packages/coding-agent/test/tools/task-simple-mode.test.ts` now
100/100 (was 14 fail / 1 error).
- `bun --cwd=packages/coding-agent run check` clean apart from the
pre-existing unrelated `anthropic.ts:1206 'stop_details'` error
from 4e0ca3c0e.
Co-Authored-By: omp <noreply@oh-my-pi.dev>
- Added explicit prompt markers and wrappers across system templates, including `[env]`, `[role]`, `[coop]`, `[closure]`, and `[now]`.
- Removed `renderTemplate` and `sectionSeparator` flows, deleted `task/template.ts`, and switched to per-task `renderSubagentUserPrompt` rendering.
- Updated system prompt assembly to `shortenPath`-normalize `cwd`, append rendered now metadata, and preserve trailing `[now]` blocks.
- Removed legacy template tests and added prompt-composition tests for ordered `[contract]`->`[project]`->`[now]` blocks and context-only system placement.
- Reworked shared prompt utilities by collapsing consecutive blank lines and removing obsolete `OPENING_HBS`/`LIST_ITEM` helper behavior.
- Added `listWorkspace` native binding and API types, exporting bounded workspace trees with AGENTS.md candidates.
- Reworked `buildWorkspaceTree` and `buildDirectoryTree` to call `listWorkspace` with 5s timeout defaults.
- Replaced startup AGENTS.md discovery with workspace-tree-only scanning and removed legacy AgentsMdSearch session plumbing.
- Updated `WorkspaceTree` and system prompt context to expose `agentsMdFiles` and aligned tests/changelog expectations.
- Introduced a flag to detect when an explicit modelRegistry was supplied to runSubprocess.
- Skipped modelRegistry.refresh() when reusing the parent registry and retained refresh when creating a new one.
- Added a debug log to indicate when a parent modelRegistry is reused and refresh is bypassed.
Reporter screenshot showed a parent session on DeepSeek V4 Pro dispatching
a task subagent that resolved to `qwen3.6-plus-free` — an opencode-zen
model the user had no working credentials for. The dispatch hit a
provider that could not serve the model and surfaced a confusing API
rejection instead of using the parent's already-authenticated model.
Adds `resolveModelOverrideWithAuthFallback`, an auth-aware wrapper
around `resolveModelOverride` that checks the resolved subagent model's
credentials via `modelRegistry.getApiKey` + `isAuthenticated` and
falls back to the parent session's active model pattern when the
primary has no working auth. The parent's active model is plumbed
through `ExecutorOptions.parentActiveModelPattern` from `TaskTool`
into `runSubprocess`. If neither has working auth (or they resolve to
the same model), the primary resolution is preserved so the existing
error path still surfaces a meaningful failure downstream.
Fixes#985
- Updated system prompts to require every active turn to end with a tool call and clarified that reminders should default to resuming work unless the task was complete or genuinely blocked.
- Reworked the yield-reminder text to disallow fake blocker reasons and to permit continued tool-calling instead of forced immediate yields.
- In `runSubprocess`, applied `toolChoice` only on the final yield retry by adding an `isFinalRetry` check before sending the reminder.
Subagents previously re-ran buildAgentsMdSearch and buildWorkspaceTree on
every spawn, repeating the slowest part of system-prompt construction for
each task tool invocation. On large/pathological repos those scans
exceeded the 5s preparation deadline and tripped the per-subagent
'system prompt preparation timed out' warning.
Forward the parent's already-resolved AgentsMdSearch and WorkspaceTree
through createAgentSession (alongside the existing contextFiles, skills,
and promptTemplates inheritance):
- Add agentsMdSearch and workspaceTree to CreateAgentSessionOptions;
createAgentSession short-circuits the parallel scan promises when
these are provided.
- Resolve them with contextFiles before constructing ToolSession; expose
on ToolSession so the task tool can read the parent's values.
- Thread them through ExecutorOptions (task/executor.ts) into the
subagent's createAgentSession call, and pass them from the task tool
(task/index.ts) on both the worktree-isolated and non-isolated paths.
- Converted systemPrompt APIs and state types to ordered `string[]` across agent, AI, and coding-agent surfaces.
- Added `normalizeSystemPrompts` and applied it to context normalization before building provider request payloads.
- Updated AI providers to emit separate normalized prompt blocks/messages instead of a single merged system prompt.
- Removed dedicated `projectPrompt` state and remapped that context into system-context buckets in session, dump, and token accounting.
- Aligned tests and changelogs to pass and assert `systemPrompt` as arrays with ordered prompt semantics.
- Added `HindsightSessionState` to `AgentSession` and bound hindsight lifecycle hooks to session state.
- Removed global hindsight state/queue handling and replaced it with per-session `HindsightRetainQueue` batching and scoped flushing.
- Reworked recall, reflect, and retain tools to use `session.getHindsightSessionState()` instead of sessionId-based lookup.
- Updated SDK/task/backend/controller flows to pass `session`/`parentHindsightSessionState`, scope `/memory` behavior, and document it in changelog.
- Added a unified eval framework with parser grammar, backend interfaces, and JS/Python execution result types.
- Added eval tool docs and updated prompts for fenced cells, `eval.py`/`eval.js`, and fallback behavior.
- Replaced the built-in `python` tool with `eval` across registry, rendering, interactive modes, and tool settings.
- Migrated Python execution runtime from `src/ipy` to `src/eval/py`, renamed state fields, and removed legacy introspection.
- Refactored browser tooling from in-process VM helpers to worker-managed tab supervisors and protocol transport.
- Added eval parser fallback and JS tool-bridge tests, updated imports, and removed obsolete python-mode suites.
- Added a localProtocolOptions field to session and executor option types for configurable local:// behavior.
- Passed localProtocolOptions through to LocalProtocolHandler creation and subagent session bootstrap.
- Propagated parent session local protocol settings from TaskTool so subprocess subagents share the same local:// artifacts and session context.
- Updated `formatMatchLine` to emit `*` for matched lines, a leading space for context, and a `|` anchor/content separator.
- Revised grep/hashline mismatch messages and prompts to describe the new marker and separator format.
- Aligned affected atom and hashline tests with the updated match-line prefixes and separators.
- Added `AgentRegistry` singleton with session registration/unregistration and IRC routing metadata for peer lookups.
- Added IRC messaging prompts and tooling with `irc.enabled` setting, `list/send` tool paths, and peer roster rendering.
- Changed `/btw` to session-side `runEphemeralTurn`, added background IRC exchange flushing, and fixed empty-input checks.
- Added unit tests for IRC tool and BtwController ephemeral behavior, including disabled, busy, not-found, and abort cases.
- Renamed subagent completion flow from `submit_result` to `yield` across SDK tools, prompts, and docs.
- Updated executor/task handling to require and parse `yield` calls, replacing legacy submit-result extraction and state flags.
- Added `subagent-yield-reminder` and updated system prompts to require `yield` with `result.data` or `result.error`.
- Renamed hidden-tool and registration plumbing to `yield`, including discovery helpers and renderer/test surface.
Subagents created with enableMCP=false had toolSession.mcpManager
unset, causing depth-2+ sub-subagents to re-discover and spawn
duplicate MCP server processes.
- Add mcpManager option to CreateAgentSessionOptions
- Set toolSession.mcpManager unconditionally after MCP block
- Pass options.mcpManager from executor to createAgentSession
- Guard callback registration: only wire onToolsChanged/onPromptsChanged/
onResourcesChanged when the session owns the manager (created via
discovery), not when reusing a parent's — prevents child sessions
from clobbering the parent's live MCP refresh handlers
Latent since 91da560cc (in-process subagent migration), observable
since f82a5d121 added task.maxRecursionDepth allowing depth-2 agents.
- Standardized missing-file read errors and now return `File not found: <path>` for absent edit targets.
- Centralized AI provider, usage, and OAuth helpers into shared modules to remove duplicated logic.
- Migrated OAuth/API-key login flows to shared factory helpers and removed inline prompt/token-exchange code.
- Reused shared tools and formatter utilities for discovery, stream tails, LSP batching, and source formatting.
- Consolidated repeated test helpers and fixtures into shared modules, replacing inline helper duplicates.
- Removed `SearchDb` APIs and `searchDb` fields, dropping db-backed state from native and agent sessions.
- Replaced crate export `fff` with `fd`, moving fuzzy-find bindings into `fd.rs`.
- Removed `SearchDb`/picker fast-path logic from `glob` and `grep`, simplifying scan flow and dropping db args.
- Removed `SearchDb`/`getSearchDb` wiring from extension, tool, and task context constructors across coding-agent.
- Added over-indentation validation warnings in chunk-edit normalization for suspicious `~` body line formatting.
- Removed `bytes`, `fff-grep`, `fff-search`, and `blake3` deps, adding `grep-searcher = "0.1"`.
- Passed the user context when setting the session name during subprocess execution.
- Updated native build scripts to import detectHostAvx2Support from the correct shared module paths.
- Added bash.autoBackground.enabled and bash.autoBackground.thresholdMs settings with defaults for background job behavior.
- Added auto-backgrounding support for long foreground bash commands with managed job state and timeout threshold.
- Updated bash prompts, job-protocol messages, and tool activation checks to use async and auto-background support.
- Added background bash completion integration with AsyncJobManager and end-to-end tests for short/long auto-background scenarios.
- Document session name getter/setter methods in extensions.md
- Add stub methods to ExtensionProxy that throw if called before init
- Add delegating implementations to ExtensionProxyInit
- Wire up getSessionName and setSessionName in extension runtime
- Add method signatures to ExtensionContext interface and type
- Add getSessionName to session manager API
- Add getSessionName and setSessionName to all mode contexts:
- ACP agent
- Extension UI controller (also updates terminal title)
- Print mode
- RPC mode
- Extracted prompt rendering and formatting utilities from coding-agent to centralized pi-utils package with new API surface (prompt.render, prompt.format, prompt.registerHelper).
- Migrated parseFrontmatter utility from coding-agent to pi-utils package; updated 8 files to import from @oh-my-pi/pi-utils.
- Removed 170-line prompt-format.ts module and consolidated 192 lines of Handlebars helper registrations into pi-utils prompt module.
- Updated 60+ files across coding-agent and typescript-edit-benchmark to use new prompt.render() and prompt.format() API from pi-utils.
- Simplified prompt-templates.ts by delegating core functionality to pi-utils while retaining custom helper registrations (jtdToTypeScript, jsonStringify, etc.).
- Move lifecycle end event after finalizeSubprocessOutput() so
submit_result({status:'aborted'}) is correctly reflected in the
observer instead of showing completed/failed (P1)
- Reset observer registry on session resume and /new command so
stale subagent sessions from prior conversations are cleared (P2)
- Cache parsed JSONL transcript incrementally: track byte offset,
only read and parse new bytes on each refresh instead of reparsing
the entire file, avoiding render loop blocking on large sessions (P2)
Wire EventBus through task runtime so subagent lifecycle and progress
events propagate to the TUI. Add SessionObserverRegistry to track
active sessions, and a session observer overlay accessible via Ctrl+S
that shows a picker of running subagents and a read-only transcript
viewer that reads the subagent's session JSONL file to display
thinking, text, tool calls, and results.
- Add TASK_SUBAGENT_LIFECYCLE_CHANNEL for start/end events
- Add SubagentProgressPayload.sessionFile for session file tracking
- Pass eventBus through sdk.ts -> main.ts -> InteractiveMode
- SessionObserverRegistry with multi-listener onChange pattern
- Overlay picker preserves selection position across live refreshes
- Viewer renders full transcript from session JSONL (thinking, text,
tool calls with smart arg summaries, inline tool results)
- Added `wait_for_picker_scan()` function to search_db module with cancellation token support for polling picker scan completion.
- Integrated picker-based file search into glob matching logic with `collect_files_from_picker()` helper to reuse shared SearchDb picker results.
- Refactored fff and grep modules to use centralized `wait_for_picker_scan()` wrapper instead of direct FilePicker calls, improving cancellation handling.
- Propagated SearchDb instance through agent session initialization and input controller to enable unified file picker coordination across search operations.
- Added `attribution` option to `PromptOptions` for controlling billing and initiator attribution.
- Updated subagent prompts to explicitly set `attribution: "agent"` for accurate billing attribution.
- Refactored message attribution logic to use configurable `promptAttribution` with fallback defaults.
- Added test coverage for `attribution` option in subagent reminder prompts.
Fixes#439.
feat(coding-agent): added attribution option and explicit session directory control
- Added `attribution` option to `PromptOptions` for explicit billing and initiator attribution control.
- Updated `SessionManager.create()` to require both `cwd` and `sessionDir` parameters for explicit session directory control.
- Changed session directory naming for temporary working directories from `--` format to `-tmp-` prefix.
- Made `cwd` and `sessionDir` fields mutable in SessionManager to support session relocation.
- Fixed automatic migration of legacy session directories to new `-tmp-` prefixed naming scheme.
- Updated all test fixtures to pass both `cwd` and `sessionDir` parameters to `SessionManager.create()`.
- Fixed boolean type coercion in fetch and executor modules by wrapping truncation flags with Boolean() cast.
- Removed maxBytes property from truncation metadata to simplify output metadata structure.
- Normalized optional result properties with explicit fallbacks in output-meta module.
- Updated test expectations to reflect undefined truncation properties instead of false/null values.
- Added optional `assignment` field to task result and progress interfaces to track raw per-task assignment text separately from full templated task.
- Updated task rendering to display assignment text instead of full task template when available, improving clarity of task display.
- Modified task section rendering to show trimmed assignment text with fallback to task field if assignment is not available.
- Propagated assignment field through task executor, template renderer, and result objects to maintain consistency across task processing pipeline.
- Added 'todo.eager' configuration setting to automatically create a comprehensive todo list after the first user message.
- Added 'buildNamedToolChoice' utility function to build provider-aware tool choice constraints for named tools.
- Modified tool choice resolution to support per-turn tool choice overrides via consumeNextToolChoiceOverride() method.
- Implemented eager todo enforcement mechanism that injects a synthetic prompt to encourage todo creation when conditions are met.
- Extracted tool choice building logic into reusable utility module for better code organization.
- Added comprehensive test coverage for eager todo enforcement functionality in AgentSession.
- Introduced Effort enum and ThinkingConfig metadata for per-model reasoning capabilities with min/max effort levels.
- Migrated thinking level API from string-based ThinkingLevel to structured Effort enum across agent and AI packages.
- Added model-thinking module with effort mapping, policy application, and semantic versioning utilities for provider-specific thinking modes.
- Removed supportsXhigh() function and replaced effort clamping with model-aware validation using ThinkingConfig metadata.
- Expanded models.json with thinking configuration objects for 50+ models including Claude, Gemini, and OpenAI variants.
- Added Python analysis scripts for edit tool usage patterns and tool invocation stream processing.
- Updated option interfaces, param builders, and stream functions to use unified `reasoning` field.
- Added `resolveOpenAiReasoningEffort()` to centralize xhigh clamping logic.
- Replaced type casts with `castApi()` helper and fixed test option names.
- Updated coding-agent and benchmark references for consistency.
- Extracted thinking module with ThinkingEffort, ThinkingLevel, and ThinkingMode types to centralize reasoning configuration across packages.
- Migrated ThinkingLevel type from pi-agent-core to pi-ai package with new validation functions parseThinkingLevel() and getAvailableThinkingLevel().
- Consolidated thinking level constants and descriptions into reusable exports (ALL_THINKING_LEVELS, THINKING_MODE_DESCRIPTIONS) for consistent UI display.
- Removed local thinking-effort-label utility and replaced formatThinkingEffortLabel() with centralized formatThinking() function from pi-ai.
- Refactored thinking mode handling to distinguish ThinkingSelector (user-facing with 'off' option) from ThinkingEffort (provider-level).
- Add dereferenceJsonSchema() that inlines local $ref pointers and strips
$defs/definitions from MCP tool schemas before they reach LLM providers.
Previously, Anthropic's convertTools() extracted only properties/required,
dropping $defs and leaving dangling $ref — the LLM never saw the actual
type definitions (e.g. SourceAnchorInput enum values from nucleus).
- Silence Ajv logger (logger: false) on all three instances that use
strict: false. MCP servers may declare non-standard format keywords
(e.g. "uint") that caused console.warn() to corrupt TUI output.
- Cache compiled Ajv validators per schema object identity in validation.ts,
eliminating redundant recompilation on every tool call.
Co-authored-by: Miroslav Drbal <miroslav.drbal@gendigital.com>
- Add a dedicated abortReason field to SingleResult and thread it through task execution paths so aborted subagents show actionable context instead of a generic badge.
- Populate abortReason for signal cancellation, pre-start cancellation, submit_result aborted status, and missing submit_result after reminders
Fixes#248
- Added public `waitForIdle()` and `getLastAssistantMessage()` APIs to AgentSession for deterministic session state access.
- Refactored deferred continuation scheduling from raw `setTimeout()` to centralized post-prompt task tracking system for concurrent recovery operations.
- Fixed race conditions between deferred TTSR/context-promotion continuations and `prompt()` completion via shared recovery orchestrator.
- Replaced `#waitForRetry()` with `#waitForPostPromptRecovery()` to unify retry and TTSR resume gate handling.
- Removed per-task skill pinning feature; subagents now inherit session skill set instead of per-task selection.
- Removed `preloadedSkills` option from `CreateAgentSessionOptions` interface and related system prompt plumbing.
- Removed `skills` field from Task schema; task execution now passes available session skills directly to subagents.
- Simplified task execution pipeline by removing skill resolution logic and preloaded skills handling from system prompt templates.
- Added async background job execution for bash and task tools with configurable concurrency limits and automatic result delivery.
- Added cancel_job tool and /jobs slash command to manage and inspect running background jobs with status display.
- Added jobs:// internal protocol handler for querying job status and retrieving job execution details.
- Added async.enabled and async.maxJobs settings to control background job execution behavior.
- Enhanced status line to display count of running background jobs with visual indicator.
- Implemented AsyncJobManager with exponential backoff retry delivery, job lifecycle tracking, and automatic eviction.
Fixes#56.
- Fixed submit_result tool to only terminate on successful execution instead of always terminating.
- Removed deferred termination logic and simplified abort behavior to call requestAbort immediately.
- Added submitResultCalled flag tracking to properly manage tool execution state.
- Added test coverage for submit_result tool retry behavior after execution errors.
- Exported `finalizeSubprocessOutput()` function and `SubmitResultItem` interface for subprocess output finalization with submit_result validation.
- Added automatic reminders (up to 3) when subagent stops without calling submit_result tool, aborting with exit code 1 after final reminder.
- Extracted subprocess output finalization logic into dedicated `finalizeSubprocessOutput()` function for improved testability and reusability.
- Added comprehensive test coverage for subagent warning injection, reminder behavior, and abort handling in executor module.
- Added validation to submit_result tool to ensure status field is present and correctly typed as 'success' or 'aborted'.
- Fixed executor to only mark submitResultCalled when submit_result tool succeeds or aborts, preventing false positives on validation failures.
- Added type guards and error state checks to prevent setting completion flags on malformed tool execution results.
- Added comprehensive test coverage for submit_result extraction with valid and malformed payload validation.