Skip to content
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
106 commits
Select commit Hold shift + click to select a range
da0e69a
feat(claude/mcp): optional capability filter for genesis-tools MCP
genesiscz Jul 13, 2026
c26a6df
fix(agents): survive repeated shutdown signals without orphaning the …
genesiscz Jul 13, 2026
bc15f8e
fix(agents): bump listener sanity cap to 8h
genesiscz Jul 13, 2026
de07733
fix(jenkins-mcp): stage event duration/status + parallel branch context
genesiscz Jul 13, 2026
81efb07
feat(agents): add --body-file to message command
genesiscz Jul 13, 2026
0003c2d
feat(agents): echo body_length in message command's JSON output
genesiscz Jul 13, 2026
62290fd
docs(agents): document idle-teammate wake asymmetry + dual-channel pr…
genesiscz Jul 13, 2026
bf6f20e
docs(agents): monitor events are dropped for idle teammates, not queued
genesiscz Jul 13, 2026
6db0de8
docs(agents): refine idle-teammate monitor semantics (no wake, no wak…
genesiscz Jul 13, 2026
19006f0
feat(cli): shared port-style box tables in @app/utils/table
genesiscz Jul 14, 2026
349a889
fix(tools): strip socks proxy env when spawning tool children
genesiscz Jul 14, 2026
6c7d370
feat(ai-proxy): xai-api-key provider, live catalogs, cleaner model list
genesiscz Jul 14, 2026
76d8e34
feat(github): stack-safe merge command and smarter 403 rate-limit det…
genesiscz Jul 14, 2026
d067c01
feat(ai): grok-sub account type, env-referenced API keys, explicit su…
genesiscz Jul 15, 2026
ac0b854
feat(youtube): extension side-panel overhaul — shadow-DOM fixes, dev …
genesiscz Jul 15, 2026
1823d38
chore: add puppeteer-core dev-dep for headless extension verification
genesiscz Jul 15, 2026
49a794d
feat(ai): authFile reference mode for openai-sub accounts (Codex CLI …
genesiscz Jul 15, 2026
31338c4
feat(youtube): ask tab, live job progress, shadow-DOM select dismiss,…
genesiscz Jul 15, 2026
8bffeaa
fix(ai): resolve subscription tokens per-request in sub resolvers (40…
genesiscz Jul 15, 2026
85d9376
feat(youtube): themed markdown Ask answers + strip LiteLLM routing pr…
genesiscz Jul 15, 2026
fa0bc35
feat(youtube): users/credits/qa-history DB schema and methods
genesiscz Jul 15, 2026
07a34aa
feat(youtube): users lib with argon2id register/login
genesiscz Jul 15, 2026
22443ad
feat(youtube): user auth guard, users routes, credit-gated LLM endpoints
genesiscz Jul 15, 2026
abd38b7
feat(youtube-ext): user auth messages, token storage, account hooks
genesiscz Jul 15, 2026
7ac1ddb
feat(youtube-ext): settings dialog, diamonds chip, server-backed ask …
genesiscz Jul 15, 2026
067d76f
style(youtube): biome formatting for users tests and types barrel
genesiscz Jul 15, 2026
8934c32
feat(youtube/billing): diamond packs, stripe env accessors, signature…
genesiscz Jul 15, 2026
bcd1dad
feat(youtube/billing): checkout session creation + webhook grant/refu…
genesiscz Jul 15, 2026
b846302
feat(youtube/server): checkout + stripe webhook routes
genesiscz Jul 15, 2026
b41b588
feat(youtube/extension): checkout message/hook + diamonds pack picker UI
genesiscz Jul 15, 2026
2d35604
feat(youtube/usage): ledger-views aggregation lib for the activity da…
genesiscz Jul 15, 2026
7035376
feat(youtube): ledger + usage-summary routes, messages, hooks
genesiscz Jul 15, 2026
8f37b06
feat(youtube/extension): settings "activity · last 30 days" compact b…
genesiscz Jul 15, 2026
6cf5b35
feat(youtube/extension): panel Activity view with reason filters + in…
genesiscz Jul 15, 2026
ce8652b
feat(youtube/shares): migration + shares lib (snapshot, slug, HTML te…
genesiscz Jul 15, 2026
5282fc8
feat(youtube/server): shares CRUD routes + public share page
genesiscz Jul 15, 2026
1d4d655
feat(youtube/extension): share buttons + settings Shares management
genesiscz Jul 15, 2026
9fbb051
feat(youtube/presets): prompt_presets table + CRUD lib
genesiscz Jul 15, 2026
3069477
feat(youtube/presets): prompt injection + presets CRUD routes + prese…
genesiscz Jul 15, 2026
24bd2ad
feat(youtube/extension): Style preset picker in Summary + Ask, preset…
genesiscz Jul 15, 2026
6524a96
feat(youtube/extension): settings Presets section with edit/delete/ex…
genesiscz Jul 15, 2026
7c05da0
feat(youtube): artifact_access table, reuse pricing lib, one-time bac…
genesiscz Jul 15, 2026
14ae9ca
feat(youtube): reuse-priced summary routes — locked GET envelope, POS…
genesiscz Jul 15, 2026
806d181
feat(youtube-ext): locked-artifact envelope plumbing through messages…
genesiscz Jul 15, 2026
2bb177f
feat(youtube-ext): reuse unlock UI — Sparkles confirm variant, locked…
genesiscz Jul 15, 2026
a10f9b5
feat(youtube): qa chunk source tagging, comment thread chunker, polym…
genesiscz Jul 15, 2026
3c42643
feat(youtube): comments-aware qa indexing, merged retrieval with tran…
genesiscz Jul 15, 2026
651c3a1
feat(youtube): qa sources through route, 409 on unfetched comments, e…
genesiscz Jul 15, 2026
ffc226d
feat(youtube-ext): ask scope selector, comment author chips with jump…
genesiscz Jul 15, 2026
de94c61
feat(youtube): channel-ask candidate selection with FTS pre-filter an…
genesiscz Jul 15, 2026
147699e
feat(youtube): channel-scope ask — 10-diamond price, cross-video attr…
genesiscz Jul 15, 2026
b0d6945
feat(youtube-ext): channel ask scope UI, grouped per-video citations,…
genesiscz Jul 15, 2026
504eae1
feat(youtube): multi-video reports — reportSynthesize stage, reports …
genesiscz Jul 15, 2026
dd661b9
feat(youtube-ext): playlist report panel — generate confirm, polling …
genesiscz Jul 15, 2026
16c5b71
style(youtube): biome formatting sync after staged-fix pre-commit runs
genesiscz Jul 15, 2026
294d47b
fix(youtube): keep qa:channel whole in ledger reason grouping
genesiscz Jul 15, 2026
78858b4
feat(youtube): add latest-wins partial throttle helper
genesiscz Jul 15, 2026
4fc47c9
feat(youtube): stream structured summaries via streamObject with thro…
genesiscz Jul 15, 2026
5a09bde
feat(youtube-ext): thread streamed summary partials into the side panel
genesiscz Jul 15, 2026
920c38b
feat(youtube-ext): partial-tolerant summary rendering with skeletons …
genesiscz Jul 15, 2026
2f38a93
feat(youtube): anchor long-summary chapters to transcript timestamps …
genesiscz Jul 15, 2026
3561061
feat(youtube-ext): chapter tick overlay module for the player progres…
genesiscz Jul 15, 2026
dd9f83d
feat(youtube-ext): chapter ticks lifecycle + panel/content window bri…
genesiscz Jul 15, 2026
be01db4
feat(youtube-ext): chapter card seek pills + playing state synced to …
genesiscz Jul 15, 2026
f5ab3ab
feat(youtube): persist Deepgram speaker diarization + speaker-aware p…
genesiscz Jul 15, 2026
6d64a48
feat(youtube): video_speakers label table + PUT /videos/:id/speakers …
genesiscz Jul 15, 2026
42cc631
docs(youtube): reflect chapter startSec/endSec and segment speaker in…
genesiscz Jul 15, 2026
c43a5f8
feat(youtube-ext): editor-grade transcript search (counter, next/prev…
genesiscz Jul 15, 2026
360cf71
feat(youtube-ext): transcript follow mode synced to playback with man…
genesiscz Jul 15, 2026
d144f63
feat(youtube): speaker chips with inline rename wired through PUT /sp…
genesiscz Jul 15, 2026
2d66170
style(youtube): biome line-width formatting in summary-partials
genesiscz Jul 15, 2026
0e381a5
style(youtube): biome formatting after rebase re-integration
genesiscz Jul 15, 2026
6d6e6da
style(youtube): biome formatting after second rebase re-integration
genesiscz Jul 15, 2026
3049291
feat(youtube): output-language preference + lang plumbing through sum…
genesiscz Jul 15, 2026
282861a
feat(youtube): line-anchored transcript translation endpoint
genesiscz Jul 15, 2026
7840cf4
feat(youtube): generation + transcript language UI (extension)
genesiscz Jul 15, 2026
b681abf
feat(youtube): settings language section + Czech UI catalog
genesiscz Jul 15, 2026
a06ff53
feat(youtube): Audio TL;DR narration, cache/synthesis, Range-capable …
genesiscz Jul 15, 2026
087a7af
feat(youtube): Audio TL;DR mini player + exclusivity bridge
genesiscz Jul 15, 2026
dd78a66
fix(youtube): use \u0000 escapes instead of raw NUL bytes in audio ca…
genesiscz Jul 15, 2026
67b7540
fix(youtube-ext): don't inline-inject panel when #secondary is out-of…
genesiscz Jul 15, 2026
157d611
fix(youtube-ext): stack panel above the live chat, retreat off the pl…
genesiscz Jul 15, 2026
edf3f62
style(youtube-ext): biome one-line format for player selector
genesiscz Jul 15, 2026
9d68e6e
fix(youtube-ext): pin flex:0 0 auto so above-chat panel keeps natural…
genesiscz Jul 15, 2026
8b01f4c
fix(youtube): gate dev top-up endpoint behind YOUTUBE_ALLOW_DEV_TOPUP
genesiscz Jul 15, 2026
e895468
fix(youtube): enforce long-summary artifact access on audio routes
genesiscz Jul 15, 2026
c6740f4
fix(youtube): debit credits atomically before LLM/TTS work, refund on…
genesiscz Jul 15, 2026
19989f7
fix(youtube): review a11y/theme-token/logging batch for extension + s…
genesiscz Jul 15, 2026
9b50884
fix(youtube): per-video lang reset, interval follow mode, streamed ch…
genesiscz Jul 15, 2026
21056d2
fix(youtube): extension dev watcher — shared UI deps, posix paths, de…
genesiscz Jul 15, 2026
ef5bfda
fix(youtube): shared strict safeJsonBody with logging + full-segment …
genesiscz Jul 15, 2026
02db08d
fix(youtube): voice-aware audio URL, lang-aware estimate, preset null…
genesiscz Jul 15, 2026
6f64e57
fix(youtube): track QA jobs under a dedicated qa stage (was mislabele…
genesiscz Jul 15, 2026
d580ff2
fix(ask): make DetectedProvider.subscription required and populate it…
genesiscz Jul 15, 2026
3c524d9
fix(youtube): translate lines mapped by [#id] tags, not array position
genesiscz Jul 15, 2026
eea848f
fix(youtube): merged comment chunks keep every thread root for citations
genesiscz Jul 15, 2026
33eb63e
chore: align @types/jsdom with jsdom 29
genesiscz Jul 15, 2026
59b864f
style(youtube): biome formatting in qa.ts
genesiscz Jul 15, 2026
5eaf47d
fix(youtube): wire confirm dialog's live language into the estimate q…
genesiscz Jul 15, 2026
604675c
feat(ui): register WEB_SERVICES and matchProcess on all ports
genesiscz Jul 15, 2026
9cd2bde
feat(dev-dashboard/ports): batch resolve, kind classify, and identity…
genesiscz Jul 15, 2026
edc130e
feat(dev-dashboard): unified /api/live SSE bus for ports and pulse
genesiscz Jul 15, 2026
7beb84d
feat(dev-dashboard/ui): ports filters, sort, live stream, stable kind…
genesiscz Jul 15, 2026
5c25f43
style: biome format after ports/live commits
genesiscz Jul 15, 2026
67b89b5
feat(utils): expose @genesis/tools-utils pure export map
genesiscz Jul 15, 2026
d312eac
feat(github-merge): add --ff-only true fast-forward with stack retarget
genesiscz Jul 16, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .claude/docs/tool-template.md
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,7 @@ spinner.succeed("Done!");
8. **Add verbose/debug modes** for troubleshooting
9. **Use meaningful exit codes** (0 for success, 1+ for errors)
10. **Test with various input scenarios** including edge cases
11. **Multi-column inventory output** (lists of models, accounts, ports, …): use `@app/utils/table` port-style helpers (`createBoxTable`, `renderCliHeader`, `formatDotStatus`) + `out.println` — not clack `out.log.info` lines. See CLAUDE.md → *CLI inventory tables*. Keep `--json` via `out.result`.

### 5. Testing Your Tool

Expand Down
34 changes: 32 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ When creating a new tool and writing helper functions, check if the utility is *

- `src/utils/format.ts` - Formatting: `formatDuration()`, `formatBytes()`, `formatTokens()`, `formatNumber()`, `formatList()`, `formatTimestamp()`, `createStopwatch()`
- `src/utils/Stopwatch.ts` - High-res stopwatch class: `elapsed()`, `lap()`, `stamp()` (wall-clock + elapsed), `now()` (HH:MM:SS.mmm)
- `src/utils/table.ts` - Text table formatting
- `src/utils/table.ts` - CLI tables: `formatTable()` (plain padded), **`createBoxTable()` / `renderCliHeader()` / `formatDotStatus()`** (port-style boxed inventories via `cli-table3`)
- `src/utils/string.ts` - String utilities (glob matching, ANSI stripping)
- `src/utils/cli/executor.ts` - CLI helpers: `suggestCommand()`, `isInteractive()`, `buildCommand()`, `Executor`, `enhanceHelp()`
- `src/utils/storage/storage.ts` - Config & cache management
Expand Down Expand Up @@ -169,8 +169,9 @@ Most tools follow these common patterns:

- Support multiple output destinations: file, clipboard, stdout
- Use `clipboardy` for clipboard operations
- Use `chalk` for colored terminal output (but strip ANSI codes for non-TTY)
- Use `picocolors` (or `chalk`) for colored terminal output (but strip ANSI codes for non-TTY)
- Respect `--silent` and `--verbose` flags
- **Human inventory lists (models, accounts, ports, processes, …):** do **not** dump multi-column data via clack `out.log.info`. Use the port-style table helpers from `@app/utils/table` + `out.println` — see **CLI inventory tables** below.

**Process Execution**:

Expand Down Expand Up @@ -246,6 +247,35 @@ Two cleanly separated layers (the 2026-05 logger+out overhaul):
- **Every commander entrypoint** ends with `await runTool(program, { tool })` (from `@app/utils/cli`) — it owns `-v`/`--readme`/help registration, console-level resolution, and the `{tool}` log binding, then `parseAsync`. The subprocess **spawner** is `execTool` (renamed from the old `runTool`).
- **`scripts/ci/logging-guard.sh`** enforces this convention repo-wide in CI: no default/extension/relative-path/any-name import of the logger module (root `./tools` and `scripts/` included — not just `src/`), no bare `logger.*(SafeJSON.stringify(…))` result dumps, no reintroduced transitional shims, and that the browser-client isolation test exists. Browser-client trees never value-importing `@app/logger` is authoritatively enforced by `src/logger/client-isolation.test.ts`.
- **`@app/utils/cli/ui` — high-density CLI status.** For tools that emit many short status lines per command (e.g. `tools stash`), clack's `│ ◆ ●` box-drawing is the wrong texture. Import `{ ui }` from `@app/utils/cli/ui` to get plain stderr writes with chalk decoration (`ui.ok/info/warn/err/dim/header/kv/section/raw`). Use this INSTEAD of `out.log.*` for high-density status; keep `out.log.*` for clack-shaped task lifecycles. `out.print()` / `out.result()` are still the only writers to stdout for machine-readable output.
- **CLI inventory tables (port-style) — prefer this for multi-column human output.** Canonical helpers live in `@app/utils/table` (not reimplemented per tool). Reference UIs: `tools port`, `tools ai-proxy models`, `tools macos swap`.

| Need | API | Notes |
|---|---|---|
| Boxed inventory table | `createBoxTable(headers)` | `cli-table3` + shared box chars; `table.push(row)` then `out.println(table.toString())` |
| Title box | `renderCliHeader(title, subtitle)` | Cyan frame via `out.println` |
| Section + key rows | `renderCliSection` / `renderCliKeyRow` | Column legends, detail blocks |
| Status cell | `formatDotStatus("ok"\|"warn"\|"err"\|"dim", label)` | `● ok` / `● fail` coloring |
| Cell truncate | `truncateDisplay(value, max)` | Em dash for empty; `…` ellipsis |
| Plain padded table | `formatTable(rows, headers)` | Dense / non-TTY dumps without box borders |
| Machine-readable | `out.result(...)` + `--json` | Never put JSON through the table path |

Pattern:

```typescript
import { out } from "@app/logger";
import { suggestCommand } from "@app/utils/cli";
import { createBoxTable, formatDotStatus, renderCliHeader, renderCliSection } from "@app/utils/table";
import pc from "picocolors";

renderCliHeader("Proxy Models", "ids clients can call");
const table = createBoxTable(["PROXY ID", "PROBE"]);
table.push([pc.white(id), formatDotStatus("ok", "ok")]);
out.println(table.toString());
renderCliSection("Columns");
// footer: counts · Next/Debug via suggestCommand("tools <tool>", { replaceCommand: [...] })
```

**Do not** hand-roll `new Table({ chars: … })` or copy/paste box-drawing from `src/port/` — import from `@app/utils/table`. Keep domain coloring (framework names, etc.) in the tool's `display.ts`; keep the table chrome shared.

## Claude Agent SDK Types Reference

Expand Down
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,16 @@ Answer a question, then preserve the Q→A to the local question store so it can

Captured via the `question_answer` MCP tool, falling back to the `tools question record` CLI.

#### genesis-tools MCP server (`tools claude mcp`)

The plugin's own MCP server (stdio) exposes two capabilities: `question_answer` (the Q&A capture tool above) and `boards` (dev-dashboard annotation boards — `boards_list_boards`, `boards_wait_for_work`, `boards_compose_board`, etc.). Both are enabled by default. To restrict which capabilities are registered, set `GENESIS_TOOLS_MCP_CAPABILITIES` to a comma-delimited list of capability names in the server's environment (e.g. in `~/.claude.json`'s `mcpServers.genesis-tools.env`):

```bash
GENESIS_TOOLS_MCP_CAPABILITIES=question_answer,boards # both (default when unset)
GENESIS_TOOLS_MCP_CAPABILITIES=question_answer # only the Q&A tool
GENESIS_TOOLS_MCP_CAPABILITIES=boards # only boards tools
```

---

### Skill Details
Expand Down
24 changes: 23 additions & 1 deletion plugins/genesis-tools/skills/agents-talk/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,26 @@ done

> ⚠️ **Monitor only stdout, never stderr.** `login`'s stdout is the JSONL event stream. Stderr is for diagnostics (auto-registration notices, the resume-hint on exit, warnings). If you pipe with `2>&1` you'll see log lines in your event stream and the agent will treat them as malformed events. Correct form: `tools agents login --agent-name X | <pipeline>` — no `2>&1`. If using a Monitor harness directly, point it at stdout only.

## ⚠️ Idle teammates do NOT wake on agents-channel traffic (Claude Code)

Empirically verified 2026-07-13 (two live probe tests + teammate-transcript forensics):

- A teammate whose turn has ENDED (idle) is **not re-invoked** by Monitor events on its login stream, and the pending Monitor notification is **not injected at wake either** — transcript inspection showed no monitor-event entry while idle nor in the wake bundle. At best it trickles in mid-turn once the teammate is already active again (observed arriving AFTER the teammate had manually read the output file). The login background process stays alive and keeps writing events to its output file; the harness just never turns that into a wake for a subagent.
- Background-task completion (`login --once` exiting when a message arrives) does **not** wake an idle teammate either.
- The **only** channel that wakes an idle teammate is the harness-native `SendMessage` tool.
- The MAIN session is different: its Monitor events DO re-invoke it between turns. The asymmetry affects teammates only.
- Consequence for the woken teammate: it must actively drain — Read the login task's output file, or run `tools agents login --agent-name <me> --once` — because the missed events will never be replayed into its context by the harness.

**Dual-channel protocol (required whenever the recipient may be idle):**

1. Payload goes on the agents channel (durable, cursor-tracked, no loss):
`tools agents message --from lead --to researcher --body '...'`
2. Immediately follow with a harness wake nudge:
`SendMessage(to: "researcher", "agents-mail waiting — drain your stream")`
3. The woken teammate drains explicitly — Reads the login task's output file or runs `tools agents login --agent-name researcher --once` — then replies on the agents channel. (Do not wait for the Monitor notification: it was dropped, not queued.)

Never put the payload only in `SendMessage` (not durable, not cursor-tracked) and never rely on the agents channel alone to wake an idle teammate. A teammate that is mid-turn WILL receive Monitor events normally between tool calls — the nudge is only load-bearing for idle recipients, but since the sender can't know, always send it.

`login` writes received events to stdout as JSONL lines. Each line is one event you should react to.

```bash
Expand Down Expand Up @@ -122,7 +142,7 @@ Each event is a JSON line. The most important `type` values:

| | `--stream` (default, CC) | `--once` (any host) |
|---|---|---|
| Lifetime | Long-running, ~1h sanity cap | Returns when a message arrives or harness kills it |
| Lifetime | Long-running, ~8h sanity cap | Returns when a message arrives or harness kills it |
| Harness tool | `Monitor` follows stdout | Caller re-invokes in a loop |
| Resume after exit | Continues where it left off | Continues where it left off |
| Cost | One held process per agent | One short-lived call per receive |
Expand All @@ -147,6 +167,7 @@ You normally don't pass `--session` — it's automatic.
- **There's no separate register step.** `login --agent-name X` auto-registers X the first time it's called — just spawn the subagent and have it call `login` directly.
- **Don't message agents that aren't registered.** You'll get an error. Call `discover` if unsure.
- **Don't expect mid-tool-call interrupts.** Stream-mode `login` delivers between tool calls (via Monitor), `login --once` returns when next called. Neither preempts a running tool.
- **Don't expect an idle teammate to wake on an agents-channel message.** See the idle-teammates section above — pair every send to a possibly-idle teammate with a harness `SendMessage` nudge.
- **One main per session.** A second `login --agent-main` errors. Use a different `--agent-name` for additional coordinators.

## Quick reference
Expand All @@ -161,6 +182,7 @@ You normally don't pass `--session` — it's automatic.
| `tools agents message --from X --body '...'` | Broadcast (every peer except the sender) |
| `tools agents message --from X --reply 0001 --body '...'` | Reply (auto-routes to the original sender) |
| `tools agents message --from X --reply 0001` | Pure ack (no body) |
| `tools agents message --from X --to Y --body-file <path>` | Long/multi-section body — write it to a file first (avoids shell-quoting breaks from embedded `'`/`` ` ``/`$(...)` truncating `--body`) |

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Clarify the shell-quoting explanation.

Backticks and $(...) are not evaluated inside single-quoted shell arguments; an embedded apostrophe is the character that directly breaks that form. Reword this to avoid implying all three characters behave identically.

Suggested wording
-| `tools agents message --from X --to Y --body-file <path>` | Long/multi-section body — write it to a file first (avoids shell-quoting breaks from embedded `'`/`` ` ``/`$(...)` truncating `--body`) |
+| `tools agents message --from X --to Y --body-file <path>` | Long/multi-section body — write it to a UTF-8 file first (avoids shell-quoting issues with complex bodies) |
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
| `tools agents message --from X --to Y --body-file <path>` | Long/multi-section body — write it to a file first (avoids shell-quoting breaks from embedded `'`/`` ` ``/`$(...)` truncating `--body`) |
| `tools agents message --from X --to Y --body-file <path>` | Long/multi-section body — write it to a UTF-8 file first (avoids shell-quoting issues with complex bodies) |
🧰 Tools
🪛 SkillSpector (2.3.11)

[warning] 77: [MP2] Context Window Stuffing: Skill attempts to fill the context window with filler content, displacing legitimate instructions and safety constraints. This can degrade agent performance or bypass safety boundaries.

Remediation: Implement context-window management that detects and rejects padding or stuffing attempts. Prioritize system instructions over user-injected content.

(Memory Poisoning (MP2))


[warning] 78: [MP2] Context Window Stuffing: Skill attempts to fill the context window with filler content, displacing legitimate instructions and safety constraints. This can degrade agent performance or bypass safety boundaries.

Remediation: Implement context-window management that detects and rejects padding or stuffing attempts. Prioritize system instructions over user-injected content.

(Memory Poisoning (MP2))

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@plugins/genesis-tools/skills/agents-talk/SKILL.md` at line 164, Revise the
`tools agents message --from X --to Y --body-file <path>` table entry so its
shell-quoting explanation distinguishes embedded apostrophes, which break
single-quoted arguments, from backticks and `$(...)`, which are not evaluated
within them. Preserve the recommendation to use a file for long or multi-section
bodies.

| `tools agents discover` | List all agents in session |
| `tools agents listen` | Human-facing color-formatted feed follower (sees everything) |

Expand Down
23 changes: 17 additions & 6 deletions src/agents/commands/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { resolveSession } from "../lib/session-resolve";
import { readSlotPayload, releaseSlot, runStaleSweep, slotLockPath, tryAcquireSlot } from "../lib/slot-lock";
import type { AgentRecord, FeedEvent, SessionPaths, SlotLockPayload } from "../lib/types";

const ONE_HOUR_MS = 60 * 60 * 1000;
const LISTEN_CAP_MS = 8 * 60 * 60 * 1000;

const log = logger.child({ component: "agents:login" });

Expand Down Expand Up @@ -426,6 +426,12 @@ async function runLoginImpl(opts: LoginOpts): Promise<void> {
onShutdown(async (reason) => {
exitReason = reason;

// Release the PID lock BEFORE any feed I/O: if the process dies
// mid-drain (force-kill, lock timeout), the slot must not stay
// orphaned. Worst case of the reversed order is a same-agent relogin
// racing the final cursor write — duplicate delivery, never loss.
releaseSlot(lockPath);

try {
await drainPending(active);
} catch (err) {
Expand All @@ -438,7 +444,6 @@ async function runLoginImpl(opts: LoginOpts): Promise<void> {
log.warn({ err }, "logged_out emit failed during shutdown");
}

releaseSlot(lockPath);
emitResumeHint(active.record, mode);
});

Expand All @@ -451,23 +456,29 @@ async function runLoginImpl(opts: LoginOpts): Promise<void> {
const initialEmitted = await drainPending(active);

if (initialEmitted === 0) {
const deadline = Date.now() + ONE_HOUR_MS;
const deadline = Date.now() + LISTEN_CAP_MS;
await watchUntilDeadline(active, deadline, true);
}
} else {
const deadline = Date.now() + ONE_HOUR_MS;
const deadline = Date.now() + LISTEN_CAP_MS;
await watchUntilDeadline(active, deadline, false);
exitReason = "cap";
}
} finally {
releaseSlot(lockPath);

try {
await drainPending(active);
} catch (err) {
log.warn({ err }, "final drain failed");
}

await emitLoggedOut({ paths, record: active.record, reason: exitReason, mode });
releaseSlot(lockPath);
try {
await emitLoggedOut({ paths, record: active.record, reason: exitReason, mode });
} catch (err) {
log.warn({ err }, "logged_out emit failed on exit");
}

emitResumeHint(active.record, mode);
}
}
Expand Down
24 changes: 22 additions & 2 deletions src/agents/commands/message.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { readFileSync } from "node:fs";
import { logger, out } from "@app/logger";
import { SafeJSON } from "@app/utils/json";
import type { Command } from "commander";
Expand All @@ -16,12 +17,25 @@ interface MessageOpts {
from?: string;
to?: string;
body?: string;
bodyFile?: string;
reply?: string;
meta?: string;
private?: boolean;
session?: string;
}

function resolveBody(opts: MessageOpts): string | undefined {
if (opts.bodyFile) {
if (opts.body) {
throw new FriendlyError("--body and --body-file are mutually exclusive", "Pass only one.");
}

return readFileSync(opts.bodyFile, "utf8");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Normalize the file path and preserve friendly read errors.

The new path is passed directly to readFileSync. Resolve relative paths with node:path, and verify that runWithFriendlyErrors converts ENOENT/EACCES failures into a consistent CLI diagnostic; otherwise log the original error and rethrow a FriendlyError.

As per coding guidelines, src/**/*.ts file paths should be resolved to absolute paths and checked before use.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/agents/commands/message.ts` at line 33, Update the body-file handling
around readFileSync to resolve opts.bodyFile to an absolute path using node:path
before reading it. Ensure runWithFriendlyErrors consistently converts ENOENT and
EACCES read failures into the standard CLI diagnostic; for other failures, log
the original error and rethrow a FriendlyError.

Source: Coding guidelines

}
Comment on lines +27 to +34

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Use option-presence checks, not truthiness.

--body "" is still a supplied option, but if (opts.body) treats it as absent. Therefore --body "" --body-file body.txt bypasses mutual exclusion and silently sends the file. Use !== undefined for both options.

Proposed fix
-    if (opts.bodyFile) {
-        if (opts.body) {
+    if (opts.bodyFile !== undefined) {
+        if (opts.body !== undefined) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
function resolveBody(opts: MessageOpts): string | undefined {
if (opts.bodyFile) {
if (opts.body) {
throw new FriendlyError("--body and --body-file are mutually exclusive", "Pass only one.");
}
return readFileSync(opts.bodyFile, "utf8");
}
function resolveBody(opts: MessageOpts): string | undefined {
if (opts.bodyFile !== undefined) {
if (opts.body !== undefined) {
throw new FriendlyError("--body and --body-file are mutually exclusive", "Pass only one.");
}
return readFileSync(opts.bodyFile, "utf8");
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/agents/commands/message.ts` around lines 27 - 34, Update resolveBody to
use option-presence checks rather than truthiness for both opts.bodyFile and
opts.body. Treat an explicitly supplied empty --body value as present so
combining --body and --body-file always raises the existing FriendlyError.


return opts.body;
}

function parseMeta(raw: string | undefined): Record<string, unknown> {
if (!raw) {
return {};
Expand All @@ -37,7 +51,8 @@ function parseMeta(raw: string | undefined): Record<string, unknown> {
}

async function runMessageImpl(opts: MessageOpts): Promise<void> {
const hasBody = typeof opts.body === "string" && opts.body.length > 0;
const body = resolveBody(opts);
const hasBody = typeof body === "string" && body.length > 0;
const isAck = !hasBody && Boolean(opts.reply);

if (!hasBody && !isAck) {
Expand Down Expand Up @@ -94,7 +109,7 @@ async function runMessageImpl(opts: MessageOpts): Promise<void> {
from_agent_id: sender.agent_id,
from_agent_name: sender.agent_name,
to_agent_ids: toIds,
body: hasBody ? (opts.body as string) : "",
body: hasBody ? (body as string) : "",
meta,
private: Boolean(opts.private),
...(opts.reply ? { in_reply_to: opts.reply } : {}),
Expand All @@ -112,6 +127,7 @@ async function runMessageImpl(opts: MessageOpts): Promise<void> {
kind: opts.reply ? (hasBody ? "reply" : "ack") : isBroadcast ? "broadcast" : "direct",
in_reply_to: opts.reply ?? null,
recipients: isBroadcast ? "(all peers except sender)" : event.to_agent_ids,
body_length: event.body.length,
},
{ strict: true }
)
Expand Down Expand Up @@ -161,6 +177,10 @@ export function registerMessageCommand(program: Command): void {
.option("--from <token>", "Sender agent — name or id")
.option("--to <csv>", "Recipient agents — comma-separated names or ids; empty = broadcast")
.option("--body <text>", "Message body (omit + --reply for pure ack)")
.option(
"--body-file <path>",
"Read message body from a file instead of --body (avoids shell-quoting issues with long/multi-line bodies)"
)
Comment on lines +180 to +183

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Mention --body-file in the missing-body diagnostic.

The new option is accepted here, but the validation message at Lines 61-62 still says only --body is required and shows no file-based example. Update it to mention --body or --body-file.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/agents/commands/message.ts` around lines 180 - 183, Update the
missing-body validation diagnostic in the message command to state that either
--body or --body-file is required, and include a file-based usage example
alongside the existing body example. Leave the option definition and other
validation behavior unchanged.

.option("--reply <msg-id>", "Mark this as a reply to a previous message_id (auto-routes to original sender)")
.option("--meta <json>", "Optional JSON object")
.option("--private", "Mark as private (v1: stored, not enforced)")
Expand Down
36 changes: 21 additions & 15 deletions src/agents/lib/lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,29 @@ export type ShutdownHandler = (reason: ShutdownReason) => Promise<void> | void;

const handlers: ShutdownHandler[] = [];
let signalsInstalled = false;
let shuttingDown = false;

async function runHandlers(reason: ShutdownReason): Promise<void> {
if (shuttingDown) {
return;
let shutdownRun: Promise<void> | null = null;

// A single shared promise (not a boolean guard) so a second signal delivered
// mid-shutdown awaits the in-flight handlers instead of returning immediately
// and calling process.exit() while they're still running — that killed the
// process before releaseSlot(), orphaning the PID lock until an unrelated
// agent's stale-lock sweep reaped it.
function runHandlers(reason: ShutdownReason): Promise<void> {
if (!shutdownRun) {
shutdownRun = (async () => {
const ordered = [...handlers].reverse();

for (const handler of ordered) {
try {
await handler(reason);
} catch (err) {
log.warn({ err }, "shutdown handler threw");
}
}
})();
}

shuttingDown = true;
const ordered = [...handlers].reverse();

for (const handler of ordered) {
try {
await handler(reason);
} catch (err) {
log.warn({ err }, "shutdown handler threw");
}
}
return shutdownRun;
}
Comment on lines +11 to 34

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Shared-promise fix looks correct; add a regression test.

The synchronous assignment of shutdownRun before any await can interleave correctly prevents the race this replaces (a second signal short-circuiting past in-flight handlers). No functional issue found.

Since this fixes a subtle concurrency bug, consider adding a unit test (e.g., push two async handlers, call runHandlers twice concurrently, assert the second call awaits the same promise and handlers run exactly once in reverse order) to guard against regression.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/agents/lib/lifecycle.ts` around lines 11 - 34, The shared-promise
behavior in runHandlers lacks regression coverage for concurrent shutdown calls.
Add a unit test that registers two asynchronous handlers, invokes runHandlers
twice before completion, asserts both calls await the same in-flight promise,
and verifies handlers execute exactly once in reverse registration order.


function installSignals(): void {
Expand Down
19 changes: 19 additions & 0 deletions src/ai-proxy/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,25 @@ Two token sources, tried in order:
- `openaiSub.accountName` set → the named `openai-sub` account in `~/.genesis-tools/ai/config.json` (refreshed via Codex OAuth and persisted).
- `openaiSub.accountName` omitted → the Codex CLI's own cache (`~/.codex/auth.json`, read-only; run `codex login` to refresh it). Override the path with `openaiSub.codexAuthPath`.

### xAI API key

OpenAI-compatible passthrough to `https://api.x.ai/v1` (chat completions + responses). Detected when `XAI_API_KEY` / `X_AI_API_KEY` is set (`tools ai-proxy config detect` / `config init`). Catalog comes from live `GET /v1/models` (chat models only; image/video filtered), with a small static fallback if the request fails.

```json
{
"name": "work",
"provider": "xai-api-key",
"providerSlug": "xai",
"enabled": true,
"apiKeyEnv": "XAI_API_KEY",
"managementKeyEnv": "XAI_MANAGEMENT_KEY",
"teamId": "optional-team-id"
}
```

Model ids: `work/xai/grok-4.5`, `work/xai/grok-4.3`, …
Usage for this provider needs Management API credentials (`managementKeyEnv` + `teamId` / `XAI_TEAM_ID`); the inference key alone has no usage endpoint.

## Usage analytics

- **Subscription:** `tools ai-proxy usage --account genesiscz`
Expand Down
Loading
Loading