Commit Graph

749 Commits

Author SHA1 Message Date
can1357 dfa6007f36 feat(coding-agent): removed recipe tool and all runner implementations
- Deleted RecipeTool, runner logic, and all task runner backends (just, make, cargo, pkg, task).
- Removed recipe from BUILTIN_TOOLS, auto-injection in createTools, and HTML export renderer.
- Deleted recipe tool prompt template and runner module exports.
2026-05-31 01:42:47 +02:00
can1357 725539aeeb feat(read): conditioned inspect_image docs on feature flag
- Updated read tool prompt to show alternate image description when inspect_image is disabled.
- Passed INSPECT_IMAGE_ENABLED flag into prompt rendering context.
- Added test verifying description omits inspect_image references when disabled.
2026-05-30 21:24:14 +02:00
can1357 0eee5a4019 feat(coding-agent): added todo-write strike-through completion animation
- Added todo_write strike-frame animation timing and updated execution flow after completion finalizes.
- Added strike animation cancellation in cleanup to clear todo timer and reset frames when spinner is idle.
- Removed todo-closing state and timeout handling from interactive mode and simplified empty todo-list rendering.
- Reworked todo-write to compute completion transitions, track completedTasks, and render strike-through frames.
- Added test coverage for completedTasks, theme setup, and strike-through progression at hold-frame thresholds.
2026-05-30 18:58:48 +02:00
can1357 e831c2c758 chore: reformat 2026-05-30 18:08:51 +02:00
can1357 6b4accd05e feat(memory): added memory_edit tool and stats/diagnose commands
- Added `memory_edit` tool for update, forget, and invalidate operations on Mnemosyne memories by id.
- Added `stats` and `diagnose` methods to `MemoryBackend` interface with Mnemosyne implementations.
- Exposed `/memory stats` and `/memory diagnose` slash commands in TUI and ACP modes.
- Refactored recall output to include memory ids via `formatScopedRecallWithIds`.
2026-05-30 16:48:02 +02:00
can1357 98de6510f0 fix(coding-agent/tools): renamed exit status label from "Status: exit N" to "Exit: N"
- Updated shell renderer footer label for non-zero exits to use the shorter `Exit: N` format.
- Updated changelog and tests to match the new label.
2026-05-30 16:35:34 +02:00
can1357 4356298182 fix(coding-agent/tools): handled non-zero bash exits as error results
- Tagged non-zero bash command completions as error results, capturing `exitCode` and keeping exit notices in returned text.
- Updated the shell renderer to hide duplicate exit notices from output while surfacing failed command status in the footer.
- Added tests for non-zero versus zero-exit bash results and footer rendering of failed commands.
2026-05-30 16:31:48 +02:00
can1357 318d553045 feat(tools): added memory inline renderers for retain/recall/reflect
- Added shared helpers and inline TUI renderers for retain, recall, and reflect tool outputs.
- Added tool registry entries for retain, recall, and reflect to use the new inline renderers.
- Updated changelog notes describing new memory inline rendering semantics and output headers.
- Added memory renderer tests for summary, truncation, streaming, and expand/collapse behavior.
2026-05-30 16:28:55 +02:00
can1357 6618bfb4f4 refactor(tools): renamed Hindsight tools to Memory and fixed per-bank db paths
- Renamed HindsightRecall/Reflect/RetainTool classes and files to Memory* for backend-neutral naming.
- Fixed Mnemosyne state to resolve separate db paths per bank instead of sharing one file.
- Updated test file and all imports to reflect the new names.
2026-05-30 14:47:54 +02:00
can1357 9d29fc9716 feat(mnemosyne): added configurable memory scoping with per-project-tagged mode
- Added `mnemosyne.scoping` setting: `global`, `per-project`, and `per-project-tagged`.
- `per-project-tagged` writes to a project-local bank while merging global memories on recall.
- Refactored `MnemosyneSessionState` to manage scoped recall/retain targets and deduplication.
- Updated hindsight tools to route recall/retain through scoped methods.
2026-05-30 14:47:53 +02:00
can1357 89b33823f3 feat(memory): wired Mnemosyne backend into recall/retain/reflect tools
- Extended tool factories to activate on `memory.backend === "mnemosyne"` in addition to `hindsight`.
- Implemented Mnemosyne execution paths in all three tools using `recallEnhanced`, `remember`, and `beam.formatContext`.
- Exposed `getMnemosyneSessionState` on `ToolSession` and wired it through `createAgentSession`.
- Added usage guidance for `recall`, `retain`, and `reflect` to Mnemosyne static instructions.
- Replaced Hindsight-only contract tests with expanded suite covering both backends.
2026-05-30 14:47:46 +02:00
can1357 9ce250eb99 chore: remove deprecated calc tool as it is completely useless with eval 2026-05-30 04:05:26 +02:00
can1357 8715ed207c feat(coding-agent-eval): added oneshot llm helper and __llm__ bridge
- Added one-shot `llm(prompt, opts)` helpers in JS and Python eval runtimes.
- Added `__llm__` eval bridge wiring for synthetic LLM tool dispatch and status/event output.
- Added `runEvalLlm` with tier-to-model resolution, effort handling, and oneshot completion execution.
- Added structured schema output handling via `respond` tool and JSON fallback parsing.
- Documented new llm behavior in eval docs/changelog and added tests for tier mapping and error cases.
2026-05-30 00:27:04 +02:00
can1357 04d6e831dc refactor(eval): replaced inline JSON tree renderer with shared renderJsonTreeLines
- Dropped local `renderJsonTree` and `formatJsonScalar` in favor of the shared `renderJsonTreeLines` used by tool args, MCP results, and subagent output.
- Removed `Object(N)`/`Array(N)` type labels and per-output `JSON output N` headers; type icons and bare keys are used instead.
- The `display[N]` header is now shown only when a cell emits more than one `display()` value.
2026-05-30 00:27:03 +02:00
can1357 01c34db450 feat(hashline): added full-file hash snapshots with 4-hex tags
- Replaced snapshot internals with full-file records and removed contiguous/sparse snapshot APIs.
- Added file-hash normalization, computed `computeFileHash`, and updated grammar/messages to 4-hex tags.
- Simplified recovery by checking whole-file hashes first, then applying merge-replay fallback after mismatches.
- Updated coding-agent tools to use `record`/`recordFileSnapshot` and skip hash headers for unsnapshotted large files.
- Expanded patcher and snapshot tests to verify 4-hex anchors, hash deduplication, and cache-capped behavior.
2026-05-29 18:12:08 +02:00
oldschoola 98fdcdcf63 feat(coding-agent): live cube, fuzzier matcher, auto-checkmark, close animation
Four refinements to the sticky Todos panel on top of the live SessionObserverRegistry linkage:

- Cube animates whenever any visible open todo is "live" (in_progress, or a still-pending todo with a matching in-flight subagent). The previous subagent-only gate left lone in_progress rows on the static '⟳' fallback; ticking on an orphan in_progress row is the correct "still open" signal.
- 'normalizeForTodoMatch' now collapses any non-alphanumeric run to one space, so subagent descriptions with '#', '.', ':' etc. match todo content that omits the punctuation. Fixes the case where 3 subagents were spawned but only 2 of 3 matching todos lit up because the matcher's normalizer collapsed whitespace but left '#' intact.
- New '#reconcileTodosWithSubagents' runs on every observer-registry change and auto-checkmarks any pending/in_progress todo whose content matches a 'status === "completed"' subagent description. Failed/aborted subagents intentionally don't auto-flip - those stay open for the user (or next agent turn) to decide.
- All-done close animation: when every visible task is closed, fold the panel away over ~1.4s. A 900ms celebratory frame holds the bright bold "Todos ✓" header so the user can read the final checkmarks, then a fade through 'muted' / 'dim' with rows progressively dropped from the bottom. '#todoClosingState' state machine plays the animation exactly once per open->all-closed transition and aborts cleanly if a new open task arrives mid-animation.

Verification:
  bun test test/tools/todo-write.test.ts → 24 pass / 0 fail (one new case for # punctuation tolerance)
  bun run check                          → biome + tsgo clean
2026-05-29 02:49:18 -07:00
oldschoola cea3ac53b0 feat(coding-agent): advance the sticky todo panel as tasks close
The always-on Todos panel above the editor pinned to the first 5 tasks of the active phase, so each todo_write flip mutated at most one row (color + strikethrough) and the +N more hint only shrank at end-of-phase. Marking task 1 done left tasks 6,7,... invisible until tasks 1-5 were all closed.

Introduce selectStickyTodoWindow(tasks, maxVisible=5) — returns up to 5 open (pending / in_progress) tasks in original phase order plus the count of remaining open tasks for +N more. When every task is closed, falls back to the trailing window (with +N more suppressed) so the panel keeps useful context until getActivePhase walks to the next phase. The collapsed branch of #renderTodoList now uses it; the expanded branch is untouched.
2026-05-29 00:16:36 -07:00
can1357 11da79a6bf fix(read): fixed column truncation mutating snapshot with display content
- Column truncation is now applied to a cloned array so `collectedLines` retains on-disk content for snapshot recording.
- Snapshots bound to hashline TAGs now hold the original file text, preventing hash-mismatch failures on subsequent edits to files with long lines.
- Added regression tests covering full-file, range, multi-range reads and a live edit-after-read scenario.
2026-05-29 06:42:46 +02:00
can1357 31f3fbda61 feat(write): added snapshot header to write tool output in hashline mode
- Prepended `¶path#TAG` hashline header to plain file, ACP-bridge, and conflict resolution write results.
- Bulk conflict resolutions emit a trailing `Snapshots:` block with one header per written file.
- Suppressed when hashline display mode is disabled or for archive/SQLite/internal-URL targets.
- Added tests covering header presence, patcher usability, and disabled-mode suppression.
2026-05-29 06:42:46 +02:00
can1357 1709172bfe feat(coding-agent): added obsidian integration
- Added vault:// URL parsing, typed variants, and path resolution with vault-root validation.
- Added VaultProtocolHandler with fs and Obsidian CLI-backed resolve/read/write/list support plus caching.
- Added vault scheme integration in router, path utils, and plan-mode guard using resolveVaultUrlToPath.
- Documented vault:// read/edit and `?op`-scoped URI formats in system prompts when Obsidian is available.
- Secured vault:// operations by rejecting traversal, absolute, and symlink-escape path cases.
- Fixed response.incomplete recovery by dropping truncated turns and promoting context.
- Added internal tests for vault protocol parsing, caching, CLI behavior, and invalid-path defenses.
2026-05-28 10:10:34 +02:00
can1357 7dd00c015b feat: hashline improvements for spark
- Redesigned hashline patch syntax from anchor-based (`A-B:`) to hunk-header format (`@@ A..B @@`) with unified-diff compatibility.
- Removed `autoDropPureInsertDuplicates` option and simplified apply behavior to preserve duplicated boundary and context lines.
- Changed repeat operator from `^A-B` to `&A..B` and range separator from `-` to `..` for consistency with hunk-header syntax.
- Added image resizing and dimension notes to eval tool output; improved write tool hashline header sanitation for legacy formats.
- Removed 521 lines of boundary-duplicate absorption code and simplified parser to auto-convert bare body rows and unified-diff contamination.
2026-05-28 03:06:52 +02:00
can1357 7c64576524 feat(hashline): replaced file-hash anchors with opaque snapshot-store tags
- Replaced 4-hex content-derived file hashes with 3-hex opaque tags minted by InMemorySnapshotStore, making tags session-bound pointers rather than content fingerprints.
- Removed lru-cache dependency; replaced LRU-bounded per-path rings with a flat 4096-slot global ring using a scrambled permutation to prevent LLM tag extrapolation.
- Made SnapshotStore required in Patcher (was optional); tag resolution now drives stale-anchor detection instead of recomputing hashes at apply time.
- Changed literal payload sigil from `|` to `+` and accepted `^A` shorthand for `^A-A`; added lenient recovery for bare bodies, lone `-` rows, and overlapping bare/concrete block pairs.
2026-05-28 01:00:23 +02:00
can1357 9474e95cb5 feat(coding-agent/tools): enabled shebang files to be auto-marked executable
- Added a `madeExecutable` result field to `WriteToolDetails` to surface executable changes.
- Implemented `maybeMarkExecutableForShebang` to chmod shebang files executable while preserving existing mode bits and swallowing chmod errors.
- Updated write flow and renderer output to return and display when a file was auto-marked executable.
2026-05-28 00:34:11 +02:00
can1357 1dbd2a0659 fix(coding-agent): pin streaming diff preview to tail of the diff 2026-05-27 19:57:54 +02:00
roboomp efba782fa7 fix(tools): isolate read URL reader-mode fallback chain from remote stalls
A stalled Jina reader request shared the overall reader-mode AbortSignal
with the downstream trafilatura/lynx/native fallbacks. When Jina hung
until the budget timer fired, the shared signal aborted and the catch
handler's signal?.throwIfAborted() re-threw before any local fallback
ran.

- Bound Jina and Parallel extract to their own per-attempt sub-budget
  (REMOTE_READER_MAX_MS, capped at 10s) so a remote stall cannot consume
  the whole overall reader-mode budget.
- Catch handlers now rethrow only on real userSignal cancellation, not
  on remote sub-budget or overall budget expiry.
- Wrap trafilatura/lynx in their own try/catch so a subprocess failure
  or abort does not skip the in-process native renderer.
- Always attempt the native renderer last: it works on already-loaded
  HTML with no network or subprocess, so even an exhausted overall
  budget still yields a result.

Fixes #1449
2026-05-27 19:00:49 +02:00
Can Bölük f9c5484892 Merge pull request #1425 from oldschoola/fix/search-regex-error-prefix
fix(search): wrap native regex-build errors in ToolError
2026-05-27 19:53:02 +03:00
can1357 9f1a442a06 fix(coding-agent): fixed xAI base URL resolution and pass resolved model to credentials
- Added check to avoid returning DEFAULT_BASE_URL when a custom provider base URL is configured.
- Passed resolvedModel argument to resolveXAIHttpCredentials call in image generation tool.
2026-05-27 18:46:03 +02:00
Can Bölük dc1eb8d96f Merge pull request #1446 from OutlineDriven/fix/xai-grok-oauth-stabilize
fix(ai,coding-agent): stabilize xAI Grok OAuth
2026-05-27 19:41:20 +03:00
metaphorics b76f39d3a6 fix(coding-agent): reopen approved plan on plan-mode reentry
Patch axis: extend

Displacement: net-zero; reuses existing plan reference state instead of adding persistence or overwriting approved artifacts

Rule violations averted: no approved-plan overwrite, no transcript format migration, no public CLI/API expansion

PASS/FAIL: PASS after plan-mode focused tests and package check. Note: system-prompt-templates has an unrelated HOME=/tmp path-shortening expectation failure.
2026-05-27 16:32:40 +00:00
metaphorics 2a7f716386 fix(coding-agent): route xAI image edits to /v1/images/edits; honor image_size
The xAI image branch on origin/main always posts to /v1/images/generations
and hard-codes `resolution: "1k"`, contradicting two advertised contracts:

  P1: generate_image schema declares `input: z.array(inputImageSchema)`
  globally; resolvedImages was populated for every provider but the xAI
  branch POST body only forwarded text fields. Image-edit and
  multi-reference prompts silently degraded to text-only.

  P2: user-supplied image_size was ignored on the xAI path even though
  every other provider honors it via resolveOpenAIImageSize /
  imageConfig.imageSize.

Fix:

  * Add XAIImageReference and XAIImageRequestBase typed interfaces;
    combine into a discriminated XAIImageRequestBody union with mutually-
    exclusive image / images fields (text-only branch carries
    `image?: never; images?: never`).
  * Route to POST /v1/images/edits when resolvedImages.length > 0; map
    1 source -> `image: {url, type}`, 2-3 sources -> `images: [{url,
    type}, ...]` per docs.x.ai. Cap at 3 with a tool-level error; xAI
    documents that limit.
  * Reuse the existing toDataUrl(InlineImageData) helper for the `url`
    field (data: URIs are accepted alongside public URLs per docs.x.ai).
    `type: "image_url"` is the OpenAI-compat discriminator every official
    xAI code example sends.
  * Add resolveXAIResolution(image_size): map OpenAI-style pixel size to
    xAI's discrete "1k" | "2k" tier. 1024x1024 -> 1k; anything wider ->
    2k. Absent image_size still defaults to "1k", matching hermes-agent
    DEFAULT_RESOLUTION (plugins/image_gen/xai/__init__.py:71).
  * buildXAIEditPayload uses tuple destructure + explicit guard rather
    than `resolvedImages[0]`, staying safe under future
    noUncheckedIndexedAccess: true.

No effect on the OpenAI / OpenAI-codex / antigravity / gemini / openrouter
branches.

Op: correct
Restores: ref:feat/xai-grok-oauth@ecedf7c7e
2026-05-27 15:49:23 +00:00
can1357 ff94f91104 feat: added extraBody support, xAI fixes, and image provider updates
- Added `extraBody` merging into OpenAI Responses request params.
- Fixed xAI OAuth redirect URI to fail fast on port conflicts.
- Exposed `antigravity` and `xai` as explicit `providers.image` options.
- Added `isImageProviderPreference` guard, replacing inline string checks.
- Fixed TTS tool to resolve output path relative to cwd and require write approval.
2026-05-27 15:20:55 +02:00
can1357 a3b27d0cdb chore(ai): fixup xAI cherrypick 2026-05-27 15:15:53 +02:00
cognitive 939b371937 refactor(coding-agent/tools): drop XAI_ASPECT identity map
The XAI_ASPECT object mapped each key to itself and held two keys
(3:2, 2:3) the aspect_ratio schema can never produce. The lookup
XAI_ASPECT[params.aspect_ratio ?? "1:1"] is semantically equivalent
to params.aspect_ratio ?? "1:1" — the schema's enum
["1:1", "3:4", "4:3", "9:16", "16:9"] already constrains the
type, and xAI's /v1/images/generations accepts those strings directly.

bun check baseline 53 errors preserved (no new TS errors).

Op: compress
2026-05-27 15:08:14 +02:00
cognitive bde0114f87 feat(coding-agent): add xAI Grok Voice TTS tool
Adds packages/coding-agent/src/tools/tts.ts: a CustomTool that POSTs to
https://api.x.ai/v1/tts using the shared xAI credentials helper
(supports both SuperGrok OAuth and plain XAI_API_KEY).

Built-in voices: ara, eve (default), leo, rex, sal. xAI also accepts
custom voice IDs (the schema does not enum-restrict voice_id). Output
codec inferred from output_path suffix (.wav → wav, else mp3). Max
15,000 characters per request. Composes the callers abort signal with
a 60s timeout fence.

Wired into sdk.ts immediately after the image-gen tool registration,
matching the await logger.time(...) pattern.

Ported from NousResearch/hermes-agent (MIT) — tools/tts_tool.py
L167-171 (constants) and L896-959 (_generate_xai_tts).

Op: extend
2026-05-27 15:08:13 +02:00
cognitive c7c285dc13 feat(coding-agent): add xAI credentials helper + image-gen xai branch
Adds packages/coding-agent/src/lib/xai-http.ts: a shared credential
resolver used by image generation (this commit) and TTS (next commit).
Tries the xai-oauth SuperGrok token first via
ModelRegistry.getApiKeyForProvider (refresh cascade lives there);
falls back to XAI_API_KEY. Ported from NousResearch/hermes-agent (MIT).

Extends imageGenTool with a "xai" provider branch that POSTs to
https://api.x.ai/v1/images/generations with the Grok Imagine surface:
grok-imagine-image (default, $0.02/image) or
grok-imagine-image-quality ($0.05/image). Aspect ratios 1:1, 16:9,
9:16, 4:3, 3:4, 3:2, 2:3. Resolutions 1k/2k. Decoded via the existing
saveImagesToTemp helper — no new image-handling code paths.

Op: extend
2026-05-27 15:07:53 +02:00
can1357 f051cc6a0e feat(tools): added multi-range line selectors and raw mode support for URLs and directories
- Added support for multi-range line selectors on URLs (e.g., `:5-10,20-30`) and combining `:raw` mode with line range selectors.
- Added support for line range selectors on directory listings with offset and limit parameters.
- Fixed `:raw` selector being ignored for JSON and feed URLs and directory listing line selectors dropping offset parameter.
- Added clear error message for line offset beyond directory listing end.
- Refactored URL parsing and directory reading to support multiple comma-separated ranges and improved line-based slicing logic.
- Added comprehensive test coverage for multi-range selectors, raw mode combinations, and directory range operations.
2026-05-27 15:03:12 +02:00
can1357 41d509eff0 feat(find): grouped output by directory and clamped limit to 200
- Changed output format to group results under `# /` headers to reduce token usage for shared path prefixes.
- Clamped the `limit` parameter to 1-200 (default 200) instead of the previous 1000.
- Updated tests to assert against raw file lists instead of parsed text output.
2026-05-27 13:13:11 +02:00
can1357 e3ff9826d1 fix(hashline): skipped markdown comments before hashline operations in parser
- Parser now buffers markdown-style `#` lines and skips them when they directly precede a hashline operation.
- It now preserves comment lines that are not immediately before an operation while still handling blank separators as regular raw input.
- Added focused parser tests plus prompt and changelog updates describing the new comment-skipping behavior.
2026-05-27 13:01:49 +02:00
can1357 44f0c14cb5 perf(coding-agent/tools): replaced readUrlCache with LRUCache to limit memory usage
- Replaced the standard Map cache with an LRUCache instance.
- Limited the maximum number of cached URL entries to 100.
2026-05-27 13:01:49 +02:00
oldschoola db84b52c0c fix(search): wrap native regex-build errors in ToolError
The catch block at search.ts:480-485 tried to convert native regex-build
failures into clean `ToolError`s but checked for the prefix `"regex parse
error"` (lowercase). The native crate at `crates/pi-natives/src/grep.rs`
actually emits `"Regex error: "` (capital R, no "parse"). The branch was
unreachable: invalid patterns like `a[` leaked out as raw `Error` with a
stack trace instead of being wrapped in a structured `ToolError` for the
agent to feed back on.

Match against `/^regex(?: parse)? error/i` so both the actual native
prefix and any hypothetical `regex parse error: ...` variant are caught.
Rewrite the leading prefix to `Invalid regex: ` so the agent immediately
sees the failure mode.

Test: new `test/tools/search-invalid-regex.test.ts` asserts the pattern
`a[` rejects with an `instanceof ToolError` whose message matches `/regex/i`.
Fails on current main (raw `Error` escapes); passes with the fix.
2026-05-26 23:26:15 -07:00
can1357 b12e4698a6 feat: added @oh-my-pi/hashline package and migrated hashline tooling
- Added a dedicated @oh-my-pi/hashline package with parser, patcher, filesystem, snapshots, and release metadata.
- Migrated coding-agent hashline and stream entrypoints to @oh-my-pi/hashline and removed old hashline module exports.
- Changed multi-section hashline execution to validate section hashes and flush diagnostics only at the final commit.
- Added session fileSnapshotStore support and rewired edit/read/search/write tools to use it instead of fileReadCache.
2026-05-27 04:03:49 +02:00
can1357 56c34a0d13 feat(summary): added BFS unfold and file-scoped line ranges to search
- Added `unfoldUntilLines`/`unfoldLimitLines` options to progressively reveal nested elidable spans breadth-first instead of collapsing everything behind the outermost elision.
- Added `minTotalLines` setting to skip summarization for short files, returning verbatim content instead.
- Added `:` selector support to `search` paths for constraining matches to specific line ranges.
- Extracted `parseLineRanges`/`parseLineRangeChunk`/`isLineInRanges` from `read.ts` into shared `path-utils.ts`.
2026-05-27 03:55:04 +02:00
can1357 3e5b0b2340 feat(coding-agent/tools): added bash wall-time tracking to results and renderer
- Measured bash wall-clock duration for direct, terminal-bridge, and interactive execution paths.
- Recorded wall time in result notices and details, then stripped the duplicated literal notice during shell rendering.
- Updated the renderer to include wall time in the status label and added tests for the new wall-time behavior.
2026-05-27 01:53:34 +02:00
can1357 535f7cfa89 fix(coding-agent/tools): reworked yolo approval resolution to honor user tool policies
- In `resolveApproval`, yolo mode now returns the user policy directly (`allow`/`prompt`/`deny`) and ignores tool `override` prompts.
- Updated approval-mode and approval unit tests to match the new behavior for critical bash patterns under yolo and auto-approve.
- Updated docs and settings metadata to describe yolo as user-policy-driven rather than override-driven.
2026-05-27 00:21:33 +02:00
can1357 e4a16451ec feat(coding-agent): added coding-agent approval types and mode options
- Added `ToolTier`, `ToolApproval`, and `ToolApprovalDecision` types and exported approval APIs.
- Updated approval-mode options from `auto|prompt|custom` to `always-ask|write|yolo` and defaulted mode to `yolo`.
- Changed approval resolution to apply per-tool decisions first, then mode-tier limits, with legacy-mode migration.
- Assigned read/write/exec `approval` and approval-detail prompts across built-in, custom, extension, and MCP tools.
2026-05-26 21:52:16 +02:00
can1357 be5837406b ux(coding-agent): implemented coding-agent tool approval selector
- Replaced tool-approval confirmations with an explicit Approve/Deny selector interface.
- Passed approval reason text as selector help and denied actions unless "Approve" was chosen.
- Removed formatApprovalPrompt, truncation helpers, and tool-specific prompt assembly logic.
- Deleted obsolete formatApprovalPrompt tests tied to removed approval prompt formatting.
2026-05-26 21:07:24 +02:00
oldschoola f5273eee6f fix(coding-agent): address PR #1378 review findings
- Decouple the per-tool approval gate from extension presence. ExtensionRunner
  and the ExtensionToolWrapper that hosts the gate are now constructed
  unconditionally in createAgentSession. Previously the runner was only built
  when extensionsResult.extensions.length > 0, so the entire approval system
  silently disappeared for sessions with no extensions loaded — any
  tools.approvalMode: prompt|custom setting was a no-op without feedback.
  Today this hole was masked by createAutoresearchExtension always being
  pushed inline; the unconditional construction makes the safety invariant
  explicit, and a new regression test in approval-mode.test.ts pins it.

- Extend CRITICAL_BASH_PATTERNS to cover remote-fetch-then-execute shapes
  that the original `bash <(curl …)` regex missed:
  - `source <(curl …)` / `. <(curl …)` (anchored at command boundary so
    `find . -name foo` doesn't false-positive)
  - `eval "$(curl …)"` / `eval $(curl …)` / `eval `curl …``
  Also adds `chmod -R` symbolic-mode forms (`u+x`, `u+rwx,o+w …`) targeting
  filesystem root, and `tee` / `tee -a` writes to /etc/{passwd,shadow,sudoers}
  (the standard way to write root-owned files without redirect). Benign
  forms (`source ./local.sh`, `chmod -R u+x ./build`, `tee /var/log/app.log`,
  `eval "$VAR"`) are pinned negative in the test suite.

- Extend formatApprovalPrompt with payload previews for the destructive tools
  that previously rendered as bare `Allow tool: <name>`: eval (language +
  first cell's code), task (agent + first task's id + assignment), ast_edit
  (first op's pattern / replacement / paths), browser (action + tab + url +
  code), and write content (alongside path). For `task` in particular this
  closes the gap that docs/approval-mode.md's "parent's approval covers the
  subagent" claim was waving at — the prompt now actually shows what's being
  delegated.

- Tighten isMcpToolName: drop the fallback `|| toolName.includes("__")` so
  an extension tool legally named `my__feature` or `pkg__util__do` is no
  longer falsely labelled `Origin: MCP server tool` in the approval prompt.
  Strict `mcp__` prefix only.

- Revert the cargo-cult `{ autoApprove: true } as AgentToolContext` insertions
  in agent-session-python-cleanup.test.ts and sdk-move-cwd.test.ts. The tests
  create sessions without passing settings, so the wrapper falls through to
  approvalMode "auto" automatically; the explicit flag was unnecessary and
  the `as AgentToolContext` cast hid that autoApprove lives on
  CustomToolContext, not AgentToolContext.

- Document in commands/launch.ts the dual --auto-approve declaration (oclif
  Flags for --help, manual parseArgs for runtime) so a future rename catches
  both call sites.

- Promote the subagent caveat in docs/approval-mode.md to a callout near the
  top: anything `task` is asked to do runs unattended once the parent task
  call is approved.

Verification:
- bun test packages/coding-agent/test/tools/approval.test.ts → 75 pass / 0 fail
  (was 57; +18 cases covering new remote-exec patterns, chmod symbolic, tee
  /etc, isMcp negative, and eval/task/ast_edit/browser/write payload previews)
- bun test packages/coding-agent/test/tools/approval-mode.test.ts → 7 pass /
  0 fail (was 7; +1 case asserting extensionRunner is always constructed)
- bun tsc --noEmit -p packages/coding-agent → clean
- bun x biome check . → clean
- Windows EBUSY tempdir-cleanup noise in agent-session-python-cleanup and
  sdk-move-cwd is pre-existing on this branch (already documented in the
  PR body) and absent on Linux CI.
2026-05-26 20:53:35 +02:00
oldschoola 384f429461 fix(coding-agent): tighten approval edge cases and rewrite mode docs
- approval: user 'tool: deny' now wins over critical-pattern override
  (the override only tightens allow->prompt; it must never re-arm a denied tool).
- approval: rename hindsight policy keys to match registered tool names
  (recall/retain/reflect, not hindsight_recall/hindsight_retain).
- approval: head+tail truncation for bash/ssh command prompts so a
  destructive suffix buried after a long benign preamble stays visible.
- task/executor: force tools.approvalMode='auto' in createSubagentSettings
  so subagents (which have no UI) cannot deadlock on per-tool prompts;
  the parent's approval of the task call is the authorization.
- docs/approval-mode: rewrite so every example surfaces tools.approvalMode
  and explains that tools.approval is ignored outside 'custom' mode.
2026-05-26 20:53:35 +02:00
oldschoola 4d26453a0b feat(coding-agent): restore per-tool approval policies with safer defaults
Re-introduces the per-tool approval system from luzidd's commit 39124f3 (which
is no longer reachable from main) and improves it before re-landing.

What's restored:
- ApprovalPolicy (allow/deny/prompt) plus DEFAULT_APPROVAL_POLICIES.
- ACTION_EXCEPTIONS registry (LSP read-only, bash critical patterns).
- getApprovalPolicy() six-level resolution order.
- ExtensionToolWrapper.execute() gate before extension handlers.
- --auto-approve / --yolo CLI flag and tools.approval.<tool> user config.
- docs/approval-mode.md user guide.

What's improved over the original:
- Replaced unchecked 'as any' casts with typed unknown narrowing helpers.
- Validate userConfig values: invalid strings, numbers, etc. fall through to
  the built-in default instead of being silently honoured (typo no longer
  locks a tool out or grants implicit approval).
- Expanded CRITICAL_BASH_PATTERNS: chmod -R /, chown -R /, bash <(curl ...),
  writes to /etc/passwd|shadow|sudoers, shutdown/reboot/halt/init 0,
  kill -9 1, nc -e / nc -c reverse shells. Pattern shapes require a
  command-position boundary so 'npm run reboot-tests' and 'echo "shutdown the
  queue"' don't false-positive.
- Added DEBUG_READONLY_ACTIONS exception so DAP inspection actions (threads,
  stack_trace, variables, scopes, read_memory, …) auto-allow while
  execution-side actions (launch, attach, continue, evaluate, write_memory,
  set_breakpoint, …) still prompt.
- formatApprovalPrompt: labels mcp__<server>__<tool> calls as MCP server
  tools, surfaces ssh host + command, recognises the modern § hashline header
  for edit, and truncates >240-char fields so a heredoc-sized body cannot
  blow out the confirmation dialog.
- Test suite grown from 40 to 57 cases — new coverage for invalid user
  config, the extended critical-bash patterns, benign-keyword negatives,
  debug exceptions, MCP/ssh prompt formatting, and command truncation.

Verification:
- bun test packages/coding-agent/test/tools/approval.test.ts -> 57 pass
- bun x biome check . -> clean
- bun run check:ts across all 9 workspaces -> clean
2026-05-26 20:53:33 +02:00
Can Bölük 70480e9875 Merge branch 'main' into fix/coding-agent-misc 2026-05-26 21:27:39 +03:00