SLOPSHOPPER

triflux-mods

triflux 의 Claude Code mods: HUD band 와 서브에이전트 effort 정책, 리드 세션의 메모리 압박 감시

bandguardcommandtoastprompttool
★ 7v10.84.0MITupdated 2026-10-23tellang/triflux/mods/triflux
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · triflux-mods
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /tfx-pressure ⎿ triflux-mods: 사용법: /tfx-pressure on|off|status ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

English | 한국어

<img alt="triflux" src="docs/assets/logo-dark.svg" width="200">

<h3 align="center">CLI-first multi-model orchestration for Claude Code, Codex, and Antigravity</h3>

<a href="https://www.npmjs.com/package/triflux"><img src="https://img.shields.io/npm/v/triflux?style=flat-square&color=FFAF00&label=npm" alt="npm version"></a> <a href="https://www.npmjs.com/package/triflux"><img src="https://img.shields.io/npm/dm/triflux?style=flat-square&color=F5C242" alt="npm downloads"></a> <a href="https://github.com/tellang/triflux/stargazers"><img src="https://img.shields.io/github/stars/tellang/triflux?style=flat-square&color=FFAF00" alt="GitHub stars"></a> <img src="https://img.shields.io/badge/node-%3E%3D22-374151?style=flat-square" alt="Node >= 22"> <a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-374151?style=flat-square" alt="License: MIT"></a>

triflux is a Claude Code plugin and npm CLI that routes coding work across Claude, Codex, and Antigravity. You describe the task once with /tfx-auto; triflux picks the CLI lane (Codex by default), runs it through managed routes instead of ad-hoc shell commands, and can fan the work out to parallel workers, live Claude↔Codex sessions, or remote hosts. Parallel code changes use separate worktrees and one session per worktree. The tfx shell CLI covers setup, diagnostics, and team orchestration.

Install

npm install -g triflux   # postinstall runs the setup script
tfx doctor               # check CLIs, tmux, MCP, profiles, skills

npm 12 and newer block install scripts by default. Allow the setup script:

npm i -g triflux --allow-scripts=triflux

Setup registers the triflux marketplace and prints a mods installation hint. To install usage bands and subagent effort enforcement (Claude Code 2.1.287 or newer):

tfx setup --mods

Or install the Claude Code plugin from this repository's marketplace:

claude plugin marketplace add tellang/triflux
claude plugin install triflux@triflux

tfx doctor --fix repairs common drift; tfx doctor --json is for automation.

First steps

/tfx-auto "fix the failing auth tests"
/tfx-auto "review this change for trust-boundary issues" --mode consensus
/tfx-auto "finish the migration and verify it" --mode deep --retry ralph --max-iterations 10

Skills

Skills you invoke directly:

SkillUse
/tfx-autoFront door for implementing, fixing, reviewing, and parallel work. Behavior is set by flags (below).
/tfx-liveLive Claude↔Codex sessions: start/ask/wait/stop, peer relay, list-sessions.
/tfx-lead/tfx-lead <role> makes the session a role lead (dev lead, project lead) and renames it. The lead names and registers workers, then manages their context, briefs, cross review, merge and release. Memory pressure alerts are `/tfx-pressure on\off\status`.
/tfx-remoteRemote Claude Code sessions over SSH: start, list, reattach, send, readiness probe, monitor, stop.
/tfx-setupSetup: file sync, HUD, Codex and Antigravity profiles, MCP. tfx setup --mods installs mods.
/tfx-doctorDiagnose and repair.
/tfx-shiptriflux release flow (maintainers).
/tfx-wtWindows Terminal tabs and panes. tfx setup installs it on Windows only.

Internal lanes (marked internal: true; other skills and the router call them, but you can name them explicitly):

SkillUse
tfx-harnessMeta routing: returns which skill or path fits a request, without running it.
tfx-reviewCode review verdict (--quick for a lighter pass).
tfx-researchWeb research with cross-checked sources (--quick, --auto, --depth).

Use superpowers writing-plans for implementation plans, host deep-interview for requirements, and Claude Code’s built-in /goal for goals. Use /tfx-auto --mode deep for multi-model planning and execution. Manage Codex profiles directly in ~/.codex/<profile>.config.toml.

/tfx-auto flags

FlagValuesEffect
--modequick (default), deep, consensus, livedeep = plan → execute → verify loop; consensus = multi-CLI agreement; live = hand off to tfx-live peer
--shapeconsensus, debate, panelOutput shape for --mode consensus
--cliauto, codex, antigravity, claudeForce a CLI lane
--cli-settriad, no-antigravity, customConsensus participants
--parallel1, NN = local workers (tfx multi)
--retry0, 1 (default), ralph, auto-escalateralph = retry state machine with stuck detection; auto-escalate = move up the model chain
--max-iterationsNCap for ralph / auto-escalate (0 = unlimited)
--roundsN (default 4)Round trips for --mode live
--skill<name>Prepend skills/<name>/SKILL.md to the Codex/Antigravity prompt
--no-native-bridge-uiHide headless workers from the claude agents panel

The full contract, including --lead, --options, --experts, and conflict rules, lives in skills/tfx-auto/SKILL.md.

Models and profiles

Codex runs through named profiles; model IDs live in ~/.codex/<profile>.config.toml, and the role → profile map lives in scripts/lib/agent-route-policy.mjs. Codex and Antigravity family profiles select the newest available model at dispatch, setup, and update. Codex reads its local model cache and checks supported effort; Antigravity caches Argon models from agy models for one day. Flash and Pro are not selected automatically, and old flash* profile names resolve to argon_low. Claude keeps its existing aliases.

Pin a family in ~/.config/triflux/models.json, for example {"sol":"gpt-6-sol","argon":"gemini-4-argon"} (Windows: %APPDATA%\triflux). Without a usable catalog, resolution keeps the last result or the built-in default.

Profile / aliasLanes
astra_xhighArchitecture, planning, critique, debugging, security review, deep execution
astra_max, astra_ultraHardest single tasks (`TFX_CODEX_PROFILE=max\ultra); max is the first auto-escalate` step
sol_high / sol_medDefault implementation, review, verification, tests, docs / cleanup
luna_high / luna_lowBuild fixes, writing / latency-first lookups
argon_low / argon / argon_highAntigravity classification / generation / review
Claude fableFinal --retry auto-escalate step
Claude opus / sonnet / haikuMeta routing and planning gates / Claude-native QA and verification / fast exploration

Routing policy: .claude/rules/tfx-routing.md · escalation chain: .claude/rules/tfx-escalation-chain.md.

Shell CLI

CommandUse
tfx setup / tfx doctorSync files, HUD, MCP, profiles / diagnose and repair (--fix, --json)
tfx multiLocal multi-CLI team in tmux
tfx mcpManaged MCP registry: list, sync, add, remove
bash ~/.claude/scripts/tfx-route.sh code-reviewer "<instruction>"Send review to Codex (codex exec review via policy)
tfx list, tfx update, tfx versionInstalled skills, update, version
tfx-liveLive session bridge (same as the /tfx-live skill)

tfx <command> --help prints the exact arguments.

Runtime features

Live sessions. tfx-live drives Claude Code and Codex TUI sessions. Claude daemon targets (--short/--session-id) try UDS first and fall back to tmux when --session is also given; Codex ask queues the message through the app-server thread/queue/add API (shown in the TUI with a [from <sender>] first line) and falls back to tmux with a reported reason; UDS stays available with --transport uds --thread <id|auto>. peer relays between two sessions for --rounds. triflux's Codex hook records running Codex sessions under ~/.local/state/triflux/codex-sessions/, so tfx-live list-sessions --cli codex|claude also finds sessions you started yourself in tmux.

Long jobs. scripts/tfx-route.sh --async <agent> "<prompt>" returns a job id at once, which gets past Claude Code's 600-second Bash limit. Follow up with --job-status, --job-wait, and --job-result.

Headless workers. Workers from tfx-auto and tfx multi appear in the claude agents panel unless you pass --no-native-bridge-ui. Press Enter on a row to open the tmux pane the worker runs in.

Retry and escalation. --retry ralph loops until done or stuck (three identical failures). --retry auto-escalate steps from Codex astra_max to Claude fable; override the chain in .triflux/config/escalation-chain.json.

Machine profile. Setup records which CLIs this machine may use and its timeout policy in ~/.config/triflux/machine-profile.env. TFX_DISABLE_CODEX=1 or TFX_DISABLE_ANTIGRAVITY=1 removes a CLI from routing; if no allowed CLI is available the route fails instead of silently falling back. Details: .claude/rules/tfx-machine-profile.md.

Remote hosts. /tfx-remote reads hosts from ~/.config/triflux/hosts.json (Windows: %APPDATA%\triflux\hosts.json). Start a session with remote-spawn.mjs --host <host> --prompt "<request>". Options: skills/tfx-remote/SKILL.md.

Architecture

graph TD
    User([Claude Code prompt / shell]) --> Skills["/tfx-auto · /tfx-live · /tfx-remote"]
    User --> Lead["/tfx-lead"]
    User --> CLI[tfx CLI]
    Lead -->|"briefs, cross review, merge"| Live
    Skills --> Route[tfx-route.sh]
    Skills --> Live[tfx-live]
    CLI --> Team["tfx multi"]
    Route --> Codex[Codex CLI]
    Route --> Agy[Antigravity agy]
    Route --> Claude[Claude Code]
    Team -->|headless workers| Route
    Team --> Index[("results index: tfx-headless/*.results.json")]
    Team --> Rows["claude agents rows"]
    Rows -->|Enter| Room["worker tmux room"]
    Live -->|"codex queue, tmux fallback"| CodexTUI[Codex TUI sessions]
    Live -->|"UDS or tmux"| ClaudeTUI[Claude Code sessions]
    Route --> HUD[HUD]

Package layout and execution paths: ARCHITECTURE.md. Documentation map: docs/README.md.

Platforms

PlatformMultiplexerNotes
macOStmuxDefault path. Install coreutils (gtimeout) if you keep a positive hard ceiling.
LinuxtmuxSupported.
Windowspsmux + Windows TerminalSee below.

Windows. psmux (a tmux fork) runs PowerShell by default. Callers do not run wt.exe or raw psmux kill-session directly; tabs and panes go through the tfx-wt skill (set up only on Windows) and hub/team/wt-manager.mjs. Agent rules: .claude/rules/tfx-psmux.md.

Security and guards

LayerProtection
Managed routesCodex and Antigravity are called through tfx-route.sh, headless workers, or tfx, never through a bare codex exec or agy. This is a rule for callers; no hook enforces it.
MCP registryReplaces stale or unsupported MCP entries with managed ones.
ConsensusDeep and consensus runs report degraded or disputed results instead of hiding them.

Optional native peer adapter

triflux setup optionally approves only the dedicated ~/.claude/scripts/tfx-peer send wrapper for local Claude and Codex peers, without broad Bash or sandbox approval; ~ is a shell example, while Codex rules match the exact absolute path printed by setup. Claude reports written after its UDS write without a receiver ACK, while Codex sends a typed agent_message only to an eligible same-daemon thread; neither result proves model completion. See the tfx-live skill for setup trust limits, retry behavior, and revocation of the allow entry, rule, wrapper, and consent manifest.

Contributing

Node 22 or newer. See CONTRIBUTING.md for tests, lint, package boundaries, mirror and release checks, and state snapshots. Releases are automated: merging a version-bump commit to main runs release.yml after CI passes; it tags, creates the GitHub release, and publishes to npm through OIDC Trusted Publishing. Decisions are recorded in docs/adr/.

<sub>MIT License &middot; Made by <a href="https://github.com/tellang">tellang</a></sub>

Source 11 files
hooks/register.ts 28 lines
1import type { Register } from 'claude-code'
2
3import { registerAgentEffort } from './agent-effort.ts'
4import { registerCompactSnapshot } from './compact-snapshot.ts'
5import { registerControl } from './control.ts'
6import { registerHudBand } from './hud-band.tsx'
7import { registerIdleTeammates } from './idle-teammates.ts'
8import { type Holder, registerLeadRole } from './lead-role.ts'
9import { type Monitor, registerMemoryPressure } from './memory-pressure.ts'
10import { registerNativeMessage } from './native-message.ts'
11import { registerReportLimit } from './report-limit.ts'
12
13export const register: Register = (on, options) => {
14  registerHudBand(on, options)
15  registerAgentEffort(on)
16  registerNativeMessage(on)
17  // 압박 감시 상태를 /tfx-pressure 와 /tfx-lead 가 같이 본다.
18  const monitor: Monitor = { interactive: false, state: {} }
19  registerMemoryPressure(on, monitor)
20  // tfx_control 은 /tfx-lead 가 남긴 리드 표지가 있는 세션에서만 받는다.
21  const lead: Holder = {}
22  registerLeadRole(on, monitor, lead)
23  registerControl(on, lead)
24  registerCompactSnapshot(on, lead)
25  registerReportLimit(on, lead)
26  registerIdleTeammates(on, lead)
27}
28
hooks/agent-effort.ts 61 lines
1import type { On } from 'claude-code'
2
3type Effort = 'low' | 'medium' | 'high'
4
5// effort 없이 부른 서브에이전트는 부모 effort 를 물려받는다(2.1.292 실측). 탐색은 낮게, 판정은 높게 고정한다.
6const EFFORT_BY_AGENT: Record<string, Effort> = {
7  Explore: 'low',
8  'oh-my-claudecode:explore': 'low',
9  'general-purpose': 'medium',
10  'oh-my-claudecode:executor': 'medium',
11  'oh-my-claudecode:test-engineer': 'medium',
12  'oh-my-claudecode:writer': 'medium',
13  Plan: 'high',
14  'oh-my-claudecode:architect': 'high',
15  'oh-my-claudecode:analyst': 'high',
16  'oh-my-claudecode:critic': 'high',
17  'oh-my-claudecode:planner': 'high',
18  'oh-my-claudecode:code-reviewer': 'high',
19  'oh-my-claudecode:security-reviewer': 'high',
20  'oh-my-claudecode:verifier': 'high',
21  'oh-my-claudecode:debugger': 'high',
22  'oh-my-claudecode:tracer': 'high',
23}
24
25export function registerAgentEffort(on: On) {
26  const explicitCalls = new Set<string>()
27  const effortByAgentId = new Map<string, Effort>()
28
29  on('tool.call', { tool: 'Agent' }, async ($, e, next) => {
30    if (!e.effort) return next(e)
31    explicitCalls.add(e.tool_use_id)
32    try {
33      return await next(e)
34    } finally {
35      explicitCalls.delete(e.tool_use_id)
36    }
37  })
38
39  on('agent.spawn', async ($, e, next) => {
40    const spawned = await next(e)
41    const effort = EFFORT_BY_AGENT[e.subagentType]
42    // 호출자가 Agent 도구에 effort 를 직접 적었으면 그 값을 따른다.
43    if (spawned.agentId && effort && !e.fork && !explicitCalls.has(e.tool_use_id))
44      effortByAgentId.set(spawned.agentId, effort)
45    return spawned
46  })
47
48  // /clear 는 session.start 없이 새 세션으로 넘어가므로 여기서 비운다.
49  on('session.end', ($, e, next) => {
50    explicitCalls.clear()
51    effortByAgentId.clear()
52    return next(e)
53  })
54
55  on('turn.step', async function* ($, e, next) {
56    const effort = e.agentId ? effortByAgentId.get(e.agentId) : undefined
57    // effort 가 없는 모델(Haiku 등)은 건드리지 않는다.
58    return yield* next(effort && e.effort !== undefined ? { ...e, effort } : e)
59  })
60}
61
hooks/compact-snapshot.ts 64 lines
1import type { EngineInterface, On } from 'claude-code'
2
3import { type Holder, leadOf, leadSessionName } from './lead-role.ts'
4
5// 압축 지시에 붙이는 블록의 상한. 요약 예산을 블록이 다 쓰지 않게 한다.
6export const snapshotLimit = 2000
7export const workersPath = '.omc/lead/workers.md'
8
9const header = '[tfx 압축 스냅샷] 요약에 다음 항목을 반드시 남겨라. 압축 뒤 첫 턴에서 다시 읽지 않고 이어가기 위해서다.'
10
11// fallback 은 이 항목이 상한에 걸릴 때 대신 남기는 짧은 문장이다.
12type Item = { text: string; fallback?: string }
13
14const commonItems: Item[] = [
15  { text: '- 현재 작업 목표와 범위' },
16  { text: '- 결과 파일과 지시서 경로' },
17  { text: '- 남은 일과 다음 단계' },
18]
19
20async function workersTable($: EngineInterface): Promise<Item> {
21  try {
22    const text = await $.fs.read(`${await $.session.root()}/${workersPath}`)
23    const rows = text.split('\n').filter(line => line.trimStart().startsWith('|'))
24    if (rows.length)
25      return { text: `- 등록 워커(${workersPath} 의 표 그대로):\n${rows.join('\n')}`, fallback: `- 등록 워커는 ${workersPath} 를 다시 읽는다` }
26  } catch {
27    // 파일이 없으면 대화에서 뽑으라는 지시로 대신한다.
28  }
29  return { text: '- 등록 워커: 이름, CLI, 위치, 역할, 지시서 경로' }
30}
31
32// 높은 순위부터 놓는다. 상한을 넘으면 뒤에서부터 뺀다.
33async function leadItems($: EngineInterface, role: string, since: string): Promise<Item[]> {
34  return [
35    { text: `- 리드 역할: ${role}, 세션 이름: ${leadSessionName(role, Date.parse(since))}` },
36    { text: '- 인계 파일과 지시서 경로' },
37    await workersTable($),
38    { text: '- 열린 PR 번호와 리뷰 상태(리뷰어, 판정, 남은 지적)' },
39    { text: '- 남은 일과 사용자 결정(내린 것과 기다리는 것)' },
40  ]
41}
42
43function snapshotBlock(items: Item[]) {
44  const kept = [...items]
45  const lines = () => [header, ...kept.map(item => item.text)].join('\n')
46  while (kept.length && lines().length > snapshotLimit) {
47    const last = kept.pop()
48    // 표가 넘치면 표만 빼고 다시 읽으라는 문장은 남긴다.
49    if (last?.fallback) kept.push({ text: last.fallback })
50  }
51  return lines()
52}
53
54export function registerCompactSnapshot(on: On, lead: Holder) {
55  on('session.compact', async ($, e, next) => {
56    // 블록을 못 만들어도 압축은 막지 않는다.
57    const mark = e.agentId ? undefined : await leadOf($, lead).catch(() => undefined)
58    const block = snapshotBlock(mark ? await leadItems($, mark.role, mark.since) : commonItems)
59    // 사용자나 tfx_control 이 준 지시문을 앞에 그대로 두고 블록을 뒤에 붙인다.
60    const instructions = e.instructions?.trim() ? `${e.instructions}\n\n${block}` : block
61    return next({ ...e, instructions })
62  })
63}
64
hooks/control.ts 241 lines
1import type { EngineInterface, On, ToolCallResult } from 'claude-code'
2
3import { type Holder, leadOf, leadSessionName, sessionMark } from './lead-role.ts'
4
5export const controlTool = 'mcp__triflux-mods__tfx_control'
6// 받는 쪽 mod 가 알아보는 피어 메시지 표식. triflux mod 가 보낸, 본문 전체가 표식 한 줄인 피어 메시지만 본다.
7export const controlMarker = '[tfx-control]'
8// 받는 쪽이 저장한 자기를 띄운 리드 세션 ID. tfx-live start --lead-session 이 TFX_LEAD_SESSION_ID 로 넘긴다.
9const boundKey = 'tfx.control.lead.'
10
11const slashes = ['compact', 'clear', 'exit'] as const
12const actions = [...slashes, 'whoami', 'rebind'] as const
13type Slash = (typeof slashes)[number]
14type Action = (typeof actions)[number]
15type Request = { target?: string; action?: string; instructions?: string; then?: string; handoff?: string; lead?: string }
16type Delivered = Request & { from?: string; leadName?: string }
17type Bound = { lead: string }
18
19const description = [
20  '리드 세션 자신이나 리드가 띄운 세션에 /compact, /clear, /exit 를 건다. 모델은 내장 슬래시 명령을 직접 실행하지 못하므로 이 도구가 대신 실행한다.',
21  '/tfx-lead <역할> 을 실행한 리드 세션의 메인 대화에서만 받는다.',
22  'target: self(기본), claude:<이름>, codex:<tmux 세션>, agy:<tmux 세션>, subagent:<이름>. 지원하지 않는 조합은 이유와 대안을 오류로 돌려준다.',
23  'self 는 예약만 하고 실제 실행은 이 턴이 끝난 뒤다. 그러니 호출한 다음 응답을 짧게 마친다.',
24  'compact: instructions 는 요약 지시문, then 은 압축 뒤 넣을 다음 프롬프트.',
25  'clear: 전에 handoff 파일을 써 두고 경로를 넘기면 clear 뒤 그 파일을 읽으라는 줄과 then 을 차례로 넣는다.',
26  'exit: handoff 파일 경로가 필수다(tmux 로 보내는 Codex, agy, Claude 는 빼고). 사용자가 끝내라고 했거나 승계 세션이 인계 파일을 받기로 한 경우에만 쓴다.',
27  'whoami: 이 세션의 sessionId 와 name 을 돌려준다. tfx-live start --lead-session 에 넘긴다.',
28  'rebind: 승계 때 claude:<이름> 워커의 묶인 리드를 lead(새 리드 세션 ID)로 바꾼다. 지금 묶인 리드만 보낼 수 있다.',
29].join(' ')
30
31const inputSchema = {
32  type: 'object',
33  properties: {
34    target: { type: 'string', description: 'self, claude:<이름>, codex:<tmux 세션>, agy:<tmux 세션>, subagent:<이름>', default: 'self' },
35    action: { type: 'string', enum: actions },
36    instructions: { type: 'string', description: 'compact 지시문' },
37    then: { type: 'string', description: 'compact 나 clear 뒤 넣을 다음 프롬프트' },
38    handoff: { type: 'string', description: 'clear, exit 전에 써 둔 인계 파일 경로. self 와 피어 경로 Claude 의 exit 는 필수' },
39    lead: { type: 'string', description: 'rebind 의 새 리드 세션 ID' },
40  },
41  required: ['action'],
42}
43
44const subagentAlternative = '서브에이전트에는 슬래시 입력창이 없고 mod API 에도 서브에이전트를 압축하거나 멈추는 함수가 없다. 끝내기: 결과를 받은 뒤 닫는다(백그라운드는 TaskStop, 팀원은 tfx-lead 3절 끝난 팀원 닫기 절차). 문맥 줄이기: 요약을 넘겨 새 서브에이전트를 띄운다.'
45
46function errorText(error: unknown) {
47  return error instanceof Error ? error.message : String(error)
48}
49
50function followUp(action: Slash, e: Request) {
51  const lines = [action === 'clear' && e.handoff ? `인계 파일 ${e.handoff} 를 읽고 이어간다.` : '', e.then ?? '']
52  return lines.filter(Boolean).join('\n')
53}
54
55async function refuse($: EngineInterface, e: Request, agentId?: string) {
56  if (!actions.includes(e.action as Action)) return `action 은 ${actions.join(', ')} 중 하나다.`
57  if (agentId) return '이 도구는 리드 메인 대화 전용이다. 서브에이전트는 어떤 대상도 제어할 수 없다.'
58  const target = e.target ?? 'self'
59  if (e.action === 'whoami') return
60  if (e.action === 'rebind' && (!target.startsWith('claude:') || !e.lead)) return 'rebind 는 target claude:<이름> 과 lead(새 리드 세션 ID)가 필요하다.'
61  if (target === 'self' && e.action === 'exit' && !e.handoff) return 'exit 는 handoff 가 필요하다. 인계 파일을 먼저 쓰고 그 경로를 넘긴다.'
62  if (target.startsWith('subagent:')) return subagentAlternative
63  if (target !== 'self' && !/^(?:claude|codex|agy):./.test(target))
64    return `지원하지 않는 대상: ${target}. self, claude:<이름>, codex:<tmux 세션>, agy:<tmux 세션> 중 하나다.`
65  if (target.startsWith('agy:') && e.action === 'compact') return 'agy 는 compact 가 없다. clear 를 쓰거나 handoff 뒤 새 세션으로 넘긴다.'
66  if (target.startsWith('codex:') && e.action === 'compact' && e.instructions) return 'Codex compact 는 지시문을 받지 않는다. instructions 를 빼고 then 에 싣는다.'
67  if (e.handoff && !(await $.fs.exists(e.handoff))) return `인계 파일이 없다: ${e.handoff}. 먼저 쓴 뒤 다시 호출한다.`
68}
69
70function slash($: EngineInterface, action: Slash, e: Request) {
71  return $.command.run({ command: action, args: action === 'compact' ? (e.instructions ?? '') : '' })
72}
73
74// 리드 자기 세션: 실패와 뒤따름 문장은 리드 자신의 다음 턴 prompt 로 넣는다.
75async function run($: EngineInterface, action: Slash, e: Request) {
76  try {
77    await slash($, action, e)
78  } catch (error) {
79    await $.prompt.submit({ text: `[tfx_control] /${action} 실패: ${errorText(error)}. 사용자에게 /${action} 직접 입력을 요청한다.` })
80    return
81  }
82  const text = followUp(action, e)
83  if (action !== 'exit' && text) await $.prompt.submit({ text })
84}
85
86async function reply($: EngineInterface, from: string, text: string) {
87  const sent = await $.session.send({ to: { sessionId: from }, text })
88  if (!sent.isDelivered) await $.ui.toast(`${text} (리드에게 전달 실패: ${sent.reason})`)
89}
90
91// 받는 쪽 세션: 남의 문장이 사용자 프롬프트로 올라가지 않게 prompt.submit 은 쓰지 않는다.
92// 뒤따름 문장은 출처 머리말을 붙인 자기 세션 피어 메시지로 넣고, 결과는 보낸 리드에게 알린다.
93async function runReceived($: EngineInterface, action: Slash, e: Delivered & { from: string }) {
94  if (action === 'exit') {
95    if (!e.handoff) return reply($, e.from, '[tfx_control] /exit 거부: handoff 가 없다. 인계 파일을 쓰고 경로를 넘긴다.')
96    await reply($, e.from, `[tfx_control] /exit 실행: 인계 파일 ${e.handoff}`)
97  }
98  try {
99    await slash($, action, e)
100  } catch (error) {
101    return reply($, e.from, `[tfx_control] /${action} 실패: ${errorText(error)}.`)
102  }
103  if (action === 'exit') return
104  const text = followUp(action, e)
105  if (text) {
106    const message = `[tfx-control from ${e.leadName ?? e.from}] ${text}`
107    let reason: string | undefined
108    try {
109      const result = await $.process.run(['tfx-peer', 'self', '--session', await $.session.id(), '--message', message], { stdin: '', timeoutMs: 10_000 })
110      let status: string | undefined
111      try {
112        status = JSON.parse(result.stdout).status
113      } catch {
114        // 실패하면 stdout 이 비고 이유는 stderr 에 있다.
115      }
116      if (result.exitCode !== 0 || status !== 'written') reason = result.stderr.trim() || status || `exit ${result.exitCode}`
117    } catch (error) {
118      reason = errorText(error)
119    }
120    if (reason) return reply($, e.from, `[tfx_control] /${action} 완료, 뒤따름 문장 전달 실패: ${reason.slice(0, 200)}`)
121  }
122  await reply($, e.from, `[tfx_control] /${action} 완료`)
123}
124
125async function tfxLive($: EngineInterface, argv: string[]) {
126  const process = await $.process.run(['tfx-live', ...argv], { stdin: '', timeoutMs: 120_000, env: { CLAUDECODE: '1' } })
127  if (process.exitCode !== 0) throw new Error((process.stderr.trim() || process.stdout.trim() || `exit ${process.exitCode}`).slice(0, 500))
128  return process.stdout
129}
130
131async function controlTmux($: EngineInterface, cli: string, session: string, action: Slash, e: Request) {
132  // Claude 가 로컬 Claude 에 ask 하면 tfx-live 가 SendMessage 를 쓰라며 거부하므로 tmux 입력을 명시한다.
133  const ask = (prompt: string) => ['ask', '--cli', cli, '--session', session, '--prompt', prompt, '--no-wait', ...(cli === 'claude' ? ['--via-tmux'] : [])]
134  if (action === 'exit') await tfxLive($, ['stop', '--cli', cli, '--session', session])
135  else if (action === 'compact')
136    await tfxLive($, ['compact', '--cli', cli, '--session', session, ...(cli === 'claude' ? ['--if-busy', 'wait'] : []), ...(e.instructions ? ['--instructions', e.instructions] : []), ...(e.then ? ['--then', e.then] : []), '--no-wait'])
137  else {
138    await tfxLive($, ask(cli === 'codex' ? '/new' : '/clear'))
139    const text = followUp(action, e)
140    // Codex 기본 queue 는 /new 뒤에도 옛 thread 로 보내므로 tmux 로 새 대화에 넣는다.
141    if (text) await tfxLive($, [...ask(text), ...(cli === 'codex' ? ['--transport', 'tmux'] : [])])
142  }
143  return { result: `${cli}:${session} 에 tmux 로 ${action} 를 보냈다.` }
144}
145
146async function controlClaude($: EngineInterface, name: string, action: Exclude<Action, 'whoami'>, e: Request, leadName: string): Promise<ToolCallResult> {
147  // 묶기는 받는 쪽 mod 의 저장값이라 rebind 는 tmux 안이어도 피어 경로로 보낸다.
148  if (action !== 'rebind') {
149    const sessions: { session: string; name?: string }[] = JSON.parse(await tfxLive($, ['list-sessions', '--cli', 'claude'])).sessions ?? []
150    const tmux = sessions.find(entry => entry.name === name || entry.session === name)
151    if (tmux) return controlTmux($, 'claude', tmux.session, action, e)
152  }
153  const body: Delivered = { action, instructions: e.instructions, then: e.then, handoff: e.handoff, lead: e.lead, from: await $.session.id(), leadName }
154  const sent = await $.session.send({ to: name, text: `${controlMarker} ${JSON.stringify(body)}` })
155  if (!sent.isDelivered) return { deny: `claude:${name} 전송 실패: ${sent.reason}` }
156  return { result: `claude:${name} 에 표식 피어 메시지로 ${action} 를 보냈다. 전송만 확인, 실행 미확인(받는 쪽에서 "[tfx_control] /${action} 완료" 알림이 오면 실행됨). 알림이 오지 않으면 받는 쪽에 triflux mod 가 없다. 거부 알림이 오면 이 리드가 그 세션을 띄우지 않았다.` }
157}
158
159// 받는 쪽: 자기를 띄운 리드에게서 온 표식 메시지만 실행한다. 거부도 보낸 쪽에 알린다.
160async function receive($: EngineInterface, bound: Holder, body: Delivered & { from: string }) {
161  const mark = (await sessionMark($, boundKey, bound)) as Bound | undefined
162  if (!mark) return () => reply($, body.from, '[tfx_control] 거부: 이 세션은 리드가 띄운 세션이 아니다(TFX_LEAD_SESSION_ID 없음). tmux 안이면 tfx-live 로 제어한다.')
163  if (body.from !== mark.lead) return () => reply($, body.from, '[tfx_control] 거부: 이 세션을 띄운 리드가 아니다.')
164  if (body.action === 'rebind') {
165    const lead = body.lead
166    if (!lead) return () => reply($, body.from, '[tfx_control] rebind 거부: lead 가 없다.')
167    await $.store.set(boundKey + (await $.session.id()), { lead } satisfies Bound)
168    return () => reply($, body.from, `[tfx_control] rebind 완료: 새 리드 ${lead}`)
169  }
170  const action = body.action as Slash
171  return () => runReceived($, action, body)
172}
173
174export function registerControl(on: On, lead: Holder) {
175  const bound: Holder = {}
176  on('session.start', { isInteractive: true }, async ($, e, next) => {
177    await $.tool.register({ name: 'tfx_control', description, inputSchema, isDeferred: false })
178    const leadId = await $.env.get('TFX_LEAD_SESSION_ID')
179    if (leadId) {
180      const sessionId = await $.session.id()
181      await $.store.set(boundKey + sessionId, { lead: leadId } satisfies Bound)
182      bound.sessionId = sessionId
183      // 이 세션이 띄우는 하위 프로세스가 같은 리드에 묶이지 않게 지운다.
184      await $.env.set('TFX_LEAD_SESSION_ID', undefined)
185    }
186    return next(e)
187  })
188  on('session.end', { reason: ['prompt_input_exit', 'resume', 'logout', 'other'] }, async ($, e, next) => {
189    await $.store.delete(boundKey + e.sessionId)
190    if (bound.sessionId && bound.sessionId !== e.sessionId) await $.store.delete(boundKey + bound.sessionId)
191    bound.sessionId = undefined
192    return next(e)
193  })
194  on('tool.call', { tool: controlTool }, async ($, e) => {
195    const mark = await leadOf($, lead)
196    if (!mark) return { deny: '이 세션은 리드가 아니다. /tfx-lead <역할> 을 먼저 실행한다.' }
197    const request = e as Request
198    const reason = await refuse($, request, e.agentId)
199    if (reason) return { deny: reason }
200    const action = request.action as Action
201    const name = leadSessionName(mark.role, Date.parse(mark.since))
202    if (action === 'whoami') return { result: JSON.stringify({ sessionId: await $.session.id(), name }) }
203    const target = request.target ?? 'self'
204    const cli = target.split(':', 1)[0] ?? target
205    const targetName = target.slice(cli.length + 1)
206    if (cli === 'self') {
207      const own = action as Slash
208      // 이 훅이 도는 동안의 $.command.run 은 거부되므로 마지막 await 뒤에 타이머를 건다.
209      $.clock.after(0, () => run($, own, request)
210        .catch(error => $.ui.toast(`[tfx_control] /${own} 결과 알림 실패: ${errorText(error)}`)))
211      return { result: `/${own} 예약: 이 턴이 끝나면 실행한다. 응답을 짧게 마친다.` }
212    }
213    try {
214      if (cli !== 'claude') return await controlTmux($, cli, targetName, action as Slash, request)
215      return await controlClaude($, targetName, action, request, name)
216    } catch (error) {
217      const hint = cli === 'claude' ? '' : ` ${cli} 는 tmux 로 띄운 세션만 제어한다.`
218      return { deny: `${cli}:${targetName} ${action} 실패: ${errorText(error)}.${hint}` }
219    }
220  })
221  on('session.receive', async ($, e, next) => {
222    // 모델이 SendMessage 로 쓴 메시지에는 origin.plugin 이 없다. 표식을 흉내 낸 모델 메시지는 여기서 걸러진다.
223    if (e.origin.kind !== 'peer' || e.origin.plugin !== 'triflux-mods' || e.agentId) return next(e)
224    // 봉투 형식은 실측 전이라 trim 한 본문 전체가 표식 한 줄일 때만 맞춘다. 인용한 표식 줄은 실행하지 않는다.
225    const json = /^\[tfx-control\] (\{.*\})$/.exec(e.text.trim())?.[1]
226    if (!json) return next(e)
227    let body: Delivered
228    try {
229      body = JSON.parse(json)
230    } catch {
231      return next(e)
232    }
233    const { from, action } = body
234    if (!from || !(action === 'rebind' || slashes.includes(action as Slash))) return next(e)
235    const task = await receive($, bound, { ...body, from })
236    // 이 훅이 도는 동안의 $.command.run 은 거부되므로 마지막 await 뒤에 타이머를 건다.
237    $.clock.after(0, () => task().catch(error => $.ui.toast(`[tfx_control] ${action} 처리 실패: ${errorText(error)}`)))
238    return { consumed: 'tfx-control' }
239  })
240}
241
hooks/hud-band.tsx 192 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, On, PluginOptions } from 'claude-code'
3
4import type { BandRows, BandSpan } from '../types'
5
6const rows = atom({ plugin: 'triflux-mods', key: 'rows' } as const, null)
7
8// 'above' 는 statusLine HUD 의 c, x, a 행을 입력창 위 band 에 그리고, 'statusline' 은 statusLine 에 맡긴다.
9export type BandPosition = 'above' | 'statusline'
10
11const REFRESH_MS = 60_000
12const HUD_TIMEOUT_MS = 5_000
13// hud/constants.mjs BAND_HEADER. 10.56.0 이하 HUD 는 --band 를 몰라 이 줄이 없다.
14const BAND_HEADER = 'tfx-band 1'
15const NODE_CANDIDATES = ['node', '/opt/homebrew/bin/node', '/usr/local/bin/node']
16const NAMED_COLORS: Record<number, string> = {
17  30: 'black', 31: 'red', 32: 'green', 33: 'yellow', 34: 'blue', 35: 'magenta', 36: 'cyan', 37: 'white',
18  90: 'gray', 91: 'redBright', 92: 'greenBright', 93: 'yellowBright', 94: 'blueBright', 95: 'magentaBright',
19  96: 'cyanBright', 97: 'whiteBright',
20}
21
22function hex(r: number, g: number, b: number) {
23  return `#${[r, g, b].map(v => v.toString(16).padStart(2, '0')).join('')}`
24}
25
26function xterm256(n: number) {
27  if (n < 16) return NAMED_COLORS[n < 8 ? 30 + n : 82 + n]
28  if (n >= 232) return hex(8 + 10 * (n - 232), 8 + 10 * (n - 232), 8 + 10 * (n - 232))
29  const level = (v: number) => (v ? 55 + v * 40 : 0)
30  const i = n - 16
31  return hex(level(Math.floor(i / 36)), level(Math.floor(i / 6) % 6), level(i % 6))
32}
33
34function applySgr(style: Omit<BandSpan, 'text'>, params: string) {
35  const codes = params === '' ? [0] : params.split(';').map(Number)
36  let next = { ...style }
37  for (let i = 0; i < codes.length; i++) {
38    const code = codes[i]
39    if (code === 0) next = {}
40    else if (code === 1) next.bold = true
41    else if (code === 2) next.dim = true
42    else if (code === 22) next = { ...next, bold: false, dim: false }
43    else if (code === 39) next.color = undefined
44    else if (code === 38 && codes[i + 1] === 2) {
45      next.color = hex(codes[i + 2] ?? 0, codes[i + 3] ?? 0, codes[i + 4] ?? 0)
46      i += 4
47    } else if (code === 38 && codes[i + 1] === 5) {
48      next.color = xterm256(codes[i + 2] ?? 0)
49      i += 2
50    } else if (code !== undefined && NAMED_COLORS[code]) next.color = NAMED_COLORS[code]
51  }
52  return next
53}
54
55// HUD 의 ANSI 색 코드를 Text 조각으로 바꾼다. HUD 가 쓰는 SGR(굵게, 흐리게, 16/256/트루컬러)만 다룬다.
56export function parseAnsi(line: string): BandSpan[] {
57  const spans: BandSpan[] = []
58  const pattern = /\x1b\[([0-9;]*)m/g
59  let style: Omit<BandSpan, 'text'> = {}
60  let last = 0
61  for (let match = pattern.exec(line); match; match = pattern.exec(line)) {
62    if (match.index > last) spans.push({ text: line.slice(last, match.index), ...style })
63    style = applySgr(style, match[1] ?? '')
64    last = pattern.lastIndex
65  }
66  if (last < line.length) spans.push({ text: line.slice(last), ...style })
67  return spans
68}
69
70// statusLine 은 os.homedir() 를 쓴다. Windows 에는 HOME 이 없을 수 있다.
71async function homeDir($: EngineInterface) {
72  return (await $.env.get('HOME')) || (await $.env.get('USERPROFILE'))
73}
74
75// 실행 파일이 없을 때만 다음 node 를 시도한다. 시작한 뒤 멎었으면 같은 HUD 를 다시 돌려도 멎는다.
76async function runHud($: EngineInterface, hudPath: string, stdin: string, columns: number) {
77  for (const node of NODE_CANDIDATES) {
78    const startedAt = await $.clock.now()
79    try {
80      return await $.process.run([node, hudPath, '--band'], {
81        stdin,
82        env: { COLUMNS: String(columns) },
83        timeoutMs: HUD_TIMEOUT_MS,
84      })
85    } catch {
86      if ((await $.clock.now()) - startedAt >= HUD_TIMEOUT_MS) return null
87    }
88  }
89  return null
90}
91
92async function writeMarker($: EngineInterface, marker: string, content: string) {
93  try {
94    await $.fs.write(marker, content)
95  } catch {}
96}
97
98// 선택 기능이라 실패를 삼킨다. hook 오류가 쌓이면 mod 전체가 꺼진다.
99// 표식이 "all:" 이면 statusLine HUD 가 아무것도 그리지 않고, "off" 면 다 그린다(hud/hud-qos-status.mjs).
100async function refreshRows($: EngineInterface, position: BandPosition, columns: number) {
101  try {
102    const home = await homeDir($)
103    if (!home) return
104    const sessionId = await $.session.id()
105    const marker = `${home}/.claude/cache/triflux/claude-band/${sessionId}`
106    if (position === 'statusline') {
107      await writeMarker($, marker, 'off')
108      return
109    }
110    const { rateLimits, context } = await $.session.usage()
111    const stdin = JSON.stringify({
112      session_id: sessionId,
113      context_window: {
114        context_window_size: context.window,
115        used_percentage: context.percent,
116        current_usage: { total_tokens: context.tokens },
117      },
118      // statusLine 입력과 같은 모양(resets_at 은 epoch 초)으로 넘겨 HUD 가 한 경로로 읽는다.
119      rate_limits: Object.fromEntries(
120        rateLimits.map(w => [
121          w.kind,
122          { used_percentage: w.percentUsed, resets_at: w.resetsAt ? Math.floor(Date.parse(w.resetsAt) / 1000) : undefined },
123        ]),
124      ),
125    })
126    // TFX_HUD_PATH 는 설치본 대신 저장소의 HUD 를 돌려 볼 때 쓴다.
127    const hudPath = (await $.env.get('TFX_HUD_PATH')) || `${home}/.claude/hud/hud-qos-status.mjs`
128    const result = await runHud($, hudPath, stdin, columns)
129    const [header, ...body] = (result?.exitCode === 0 ? result.stdout : '').split('\n')
130    const lines = header === BAND_HEADER ? body.map(parseAnsi).filter(spans => spans.some(s => s.text.trim())) : []
131    // HUD 를 못 돌리거나 --band 를 모르면 band 를 비우고 statusLine 이 그리게 둔다.
132    const snapshot: BandRows | null = lines.length > 0 ? { columns, lines } : null
133    await update($, rows, () => snapshot)
134    await writeMarker($, marker, snapshot ? `all:${await $.clock.now()}` : 'off')
135  } catch {
136    // 이전 all 표식이 남으면 band 도 statusLine 도 비게 된다.
137    try {
138      await update($, rows, () => null)
139      const home = await homeDir($)
140      if (home) await writeMarker($, `${home}/.claude/cache/triflux/claude-band/${await $.session.id()}`, 'off')
141    } catch {}
142  }
143}
144
145export function registerHudBand(on: On, options: PluginOptions) {
146  const position: BandPosition = options.position === 'statusline' ? 'statusline' : 'above'
147  // 다음 갱신 때 HUD 에 넘길 터미널 폭. band 를 그릴 때마다 맞춘다.
148  let columns = 120
149
150  on('session.start', async ($, e, next) => {
151    await refreshRows($, position, columns)
152    // 남은 시간 표시와 Codex, Antigravity 캐시 갱신을 응답 없이도 따라간다.
153    if (position === 'above') $.clock.every(REFRESH_MS, () => refreshRows($, position, columns))
154    return next(e)
155  })
156
157  // 응답이 끝날 때와 사용률이 바뀔 때 발생한다(공식 문서의 session.measure).
158  on('session.measure', async ($, e, next) => {
159    const result = await next(e)
160    await refreshRows($, position, columns)
161    return result
162  })
163
164  if (position === 'statusline') return
165
166  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
167    // bodyColumns 는 오른쪽 5칸을 뺀 폭이라 HUD 가 보는 터미널 폭으로 되돌린다.
168    columns = e.props.bodyColumns + 5
169    const snapshot = await read($, rows)
170    if (e.props.hasSurvey || !snapshot) return next(e)
171
172    const { Box, Text } = $.ui.resolve(e)
173    // band 는 모든 mods 가 같이 쓴다. 뒤에 오는 mods 가 그린 것도 아래에 남긴다.
174    const others = await next(e)
175    // statusLine 처럼 두 칸 들여 쓰고, 폭이 줄면 다음 갱신 전까지 끝을 자른다.
176    return (
177      <Box flexDirection="column">
178        {snapshot.lines.map(spans => (
179          <Text wrap="truncate-end">
180            {[{ text: '  ' }, ...spans].map(s => (
181              <Text color={s.color} bold={s.bold} dimColor={s.dim}>
182                {s.text}
183              </Text>
184            ))}
185          </Text>
186        ))}
187        {others}
188      </Box>
189    )
190  })
191}
192
hooks/idle-teammates.ts 128 lines
1import type { AgentInfo, EngineInterface, On, Timer } from 'claude-code'
2
3import { type Holder, leadOf, sessionMark } from './lead-role.ts'
4import { notifyLead } from './memory-pressure.ts'
5
6// 팀원이 쉬기 시작한 때를 알리는 이벤트가 터미널 pane 팀원에는 없어 명단을 2분마다 잰다.
7export const sweepMs = 120_000
8export const noticeMs = 600_000
9
10type Idle = { since: number; names: string[]; noticedAt?: number; isShutdownSent?: boolean }
11export type Sweeper = { timer?: Timer; isSweeping?: boolean; idle: Map<string, Idle>; keep: Holder }
12
13const keepPrefix = 'tfx.keep.'
14
15// 리드가 일부러 남겨 둔 팀원 이름. /clear 뒤에는 리드 표지처럼 새 세션 ID 로 옮긴다.
16async function keptNames($: EngineInterface, keep: Holder) {
17  return ((await sessionMark($, keepPrefix, keep)) as string[] | undefined) ?? []
18}
19
20// 터미널 pane 팀원은 id 가 팀 주소(--agent-id 값)이고, pane 이 닫혀도 명단에 idle 로 남는다. 그래서 살아 있는 pane 의 주소를 모은다.
21async function paneAgentIds($: EngineInterface) {
22  if (!(await $.env.get('TMUX'))) return
23  try {
24    const result = await $.process.run(['tmux', 'list-panes', '-a', '-F', '#{pane_start_command}'], { stdin: '', timeoutMs: 10_000 })
25    if (result.exitCode !== 0) return
26    const ids = new Set<string>()
27    for (const line of result.stdout.split('\n')) {
28      const id = /--agent-id\s+['"]?([^\s'"]+)/.exec(line)?.[1]
29      if (id) ids.add(id)
30    }
31    return ids
32  } catch {
33    return
34  }
35}
36
37function isOpen(agent: AgentInfo, panes: Set<string> | undefined) {
38  if (agent.status !== 'idle' || !agent.name || agent.parentId) return false
39  return !(panes && agent.id === agent.teammateId && !panes.has(agent.id))
40}
41
42async function shutdown($: EngineInterface, agent: AgentInfo) {
43  try {
44    const result = await $.tool.call({ tool: 'SendMessage', to: agent.name, message: { type: 'shutdown_request',
45      reason: '[tfx-lead] 결과를 보낸 뒤 20분째 쉬고 있다. 남은 일이 없으면 승인하고, 리드에게서 받을 일이 남았으면 그 이유로 거절한다.' } })
46    if (result.deny || result.isError) return `${agent.name}: ${result.deny ?? result.text ?? '오류'}`
47  } catch (error) {
48    return `${agent.name}: ${error instanceof Error ? error.message : String(error)}`
49  }
50}
51
52export async function sweep($: EngineInterface, lead: Holder, sweeper: Sweeper) {
53  const { idle } = sweeper
54  // 리드 표지가 없는 세션의 팀원은 사용자가 직접 다루므로 건드리지 않는다.
55  if (!(await leadOf($, lead))) {
56    idle.clear()
57    return
58  }
59  const now = await $.clock.now()
60  const panes = await paneAgentIds($)
61  const open = (await $.agent.list()).filter(agent => isOpen(agent, panes))
62  for (const id of idle.keys()) if (!open.some(agent => agent.id === id)) idle.delete(id)
63  for (const agent of open) if (!idle.has(agent.id)) idle.set(agent.id, { since: now, names: [agent.name!, agent.teammateId ?? agent.id] })
64  const overdue = open.filter(agent => now - idle.get(agent.id)!.since >= noticeMs)
65  const kept = overdue.length ? await keptNames($, sweeper.keep) : []
66  const isKept = (agent: AgentInfo) => kept.includes(agent.name!)
67  if (overdue.some(agent => idle.get(agent.id)!.noticedAt === undefined)) {
68    const names = overdue.map(agent => `${agent.name} ${Math.floor((now - idle.get(agent.id)!.since) / 60_000)}분${isKept(agent) ? '(유지)' : ''}`)
69    for (const agent of overdue) idle.get(agent.id)!.noticedAt ??= now
70    await notifyLead($, `[tfx-lead] 결과를 보내고 쉬는 팀원 ${overdue.length}개가 열려 있다: ${names.join(', ')}. 결과를 받았으면 tfx-lead 3절 "끝난 팀원 닫기"대로 닫는다. 10분 더 열려 있으면 mod 가 팀원에게 종료를 요청한다. 남길 팀원은 /tfx-keep <이름>.`, () => true)
71  }
72  // 알린 뒤 10분이 더 지난 팀원에게만 종료를 요청한다. 거절할 수 있게 강제 종료는 하지 않는다.
73  const failures: string[] = []
74  for (const agent of overdue) {
75    const state = idle.get(agent.id)!
76    if (!agent.teammateId || isKept(agent) || state.isShutdownSent || now - state.noticedAt! < noticeMs) continue
77    state.isShutdownSent = true
78    const failure = await shutdown($, agent)
79    if (failure) failures.push(failure)
80  }
81  if (failures.length) await notifyLead($, `[tfx-lead] 팀원 종료 요청 실패: ${failures.join('; ').slice(0, 500)}. 직접 닫는다.`, () => true)
82}
83
84export function registerIdleTeammates(on: On, lead: Holder) {
85  const sweeper: Sweeper = { idle: new Map(), keep: {} }
86  on('session.start', { isInteractive: true }, async ($, e, next) => {
87    sweeper.timer?.cancel()
88    sweeper.idle.clear()
89    await $.command.register({ name: 'tfx-keep', description: '끝난 팀원 종료 요청에서 뺄 팀원: <이름> [off]', argumentHint: '<이름> [off]' })
90    sweeper.timer = $.clock.every(sweepMs, async () => {
91      if (sweeper.isSweeping) return
92      sweeper.isSweeping = true
93      try {
94        await sweep($, lead, sweeper)
95      } catch {
96        // 한 번 잰 것이 실패해도 다음 주기에 다시 잰다.
97      } finally {
98        sweeper.isSweeping = false
99      }
100    })
101    return next(e)
102  })
103  on('session.end', { reason: ['prompt_input_exit', 'resume', 'logout', 'other'] }, async ($, e, next) => {
104    await $.store.delete(keepPrefix + e.sessionId)
105    if (sweeper.keep.sessionId && sweeper.keep.sessionId !== e.sessionId) await $.store.delete(keepPrefix + sweeper.keep.sessionId)
106    sweeper.keep.sessionId = undefined
107    return next(e)
108  })
109  on('command.run', { command: 'tfx-keep' }, async ($, e) => {
110    const [name, off] = e.args.trim().split(/\s+/)
111    const kept = await keptNames($, sweeper.keep)
112    if (!name) return { text: `유지 팀원: ${kept.length ? kept.join(', ') : '없음'}. 사용법: /tfx-keep <이름> [off]` }
113    const next = off === 'off' ? kept.filter(entry => entry !== name) : [...new Set([...kept, name])]
114    const sessionId = await $.session.id()
115    await $.store.set(keepPrefix + sessionId, next)
116    sweeper.keep.sessionId = sessionId
117    return { text: `유지 팀원: ${next.length ? next.join(', ') : '없음'}` }
118  })
119  // 리드가 직접 다시 일을 시키면 2분 주기를 기다리지 않고 그 팀원의 유휴 시계를 지운다.
120  // mod 자신의 shutdown_request 는 plugin 출처라 여기서 빠진다.
121  on('tool.call', { tool: 'SendMessage' }, async ($, e, next) => {
122    if (!e.agentId && next.origin.plugin === 'engine' && typeof e.to === 'string') {
123      for (const [id, state] of sweeper.idle) if (state.names.includes(e.to)) sweeper.idle.delete(id)
124    }
125    return next(e)
126  })
127}
128
hooks/lead-role.ts 69 lines
1import type { EngineInterface, On } from 'claude-code'
2
3import { enablePressure, type Monitor } from './memory-pressure.ts'
4
5const datePrefix = /^\d{1,2}\.\d{1,2} /
6
7export function leadSessionName(role: string, now: number) {
8  if (datePrefix.test(role)) return role
9  const date = new Date(now)
10  return `${date.getMonth() + 1}.${date.getDate()} ${role}`
11}
12
13// 이 프로세스에서 표지를 남긴 세션 ID. /clear 뒤 표지를 새 ID 로 옮길 때 쓴다.
14export type Holder = { sessionId?: string }
15export type LeadMark = { role: string; since: string }
16
17const leadKey = (sessionId: string) => 'tfx.lead.' + sessionId
18
19// 세션 ID 로 묶인 표지를 읽는다. /clear 는 같은 프로세스에서 세션 ID 만 바꾸므로 옛 ID 의 표지를 새 ID 로 옮긴다.
20export async function sessionMark($: EngineInterface, prefix: string, holder: Holder) {
21  const sessionId = await $.session.id()
22  const mark = await $.store.get(prefix + sessionId)
23  if (mark || !holder.sessionId || holder.sessionId === sessionId) return mark
24  const moved = await $.store.get(prefix + holder.sessionId)
25  if (!moved) return
26  await $.store.set(prefix + sessionId, moved)
27  await $.store.delete(prefix + holder.sessionId)
28  holder.sessionId = sessionId
29  return moved
30}
31
32export async function leadOf($: EngineInterface, lead: Holder) {
33  return (await sessionMark($, 'tfx.lead.', lead)) as LeadMark | undefined
34}
35
36export function registerLeadRole(on: On, monitor: Monitor, lead: Holder) {
37  for (const isInteractive of [true, false]) {
38    on('session.start', { isInteractive }, async ($, e, next) => {
39      await $.command.register({ name: 'tfx-lead', description: '이 세션에 역할 리드를 맡긴다: <역할>', argumentHint: '<역할>' })
40      return next(e)
41    })
42  }
43  // resume 한 세션은 /tfx-lead 를 다시 실행해야 리드가 된다. /clear 는 표지를 옮기므로 지우지 않는다.
44  on('session.end', { reason: ['prompt_input_exit', 'resume', 'logout', 'other'] }, async ($, e, next) => {
45    await $.store.delete(leadKey(e.sessionId))
46    if (lead.sessionId && lead.sessionId !== e.sessionId) await $.store.delete(leadKey(lead.sessionId))
47    lead.sessionId = undefined
48    return next(e)
49  })
50  on('command.run', { command: 'tfx-lead' }, async ($, e) => {
51    const role = e.args.trim()
52    if (!role) return { text: '사용법: /tfx-lead <역할>' }
53    const now = await $.clock.now()
54    const name = leadSessionName(role, now)
55    const sessionId = await $.session.id()
56    await $.store.set(leadKey(sessionId), { role, since: new Date(now).toISOString() } satisfies LeadMark)
57    lead.sessionId = sessionId
58    const pressure = await enablePressure($, monitor)
59    // 호스트는 이 훅이 도는 동안의 $.command.run 을 타이머에서 부른 것까지 거부한다.
60    // 그래서 마지막 await 뒤에 타이머를 걸어 훅이 끝난 다음에 rename 이 돌게 한다.
61    $.clock.after(0, () => $.command.run({ command: 'rename', args: name })
62      .catch(() => $.ui.toast(`이름 변경 실패: /rename ${name} 을 직접 실행`)))
63    return {
64      text: `이름 변경 요청: ${name}. ${pressure}`,
65      context: [`이 세션의 리드 역할은 ${role.replace(datePrefix, '')}이다. tfx-lead 스킬을 로드해 그 절차를 따른다.`],
66    }
67  })
68}
69
hooks/memory-pressure.ts 199 lines
1import type { EngineInterface, On, Timer } from 'claude-code'
2
3type PressureLevel = 1 | 2 | 4
4
5export type PressureState = {
6  confirmed?: PressureLevel
7  candidate?: PressureLevel
8  sampledAt?: number
9  lastValid?: { level: PressureLevel; sampledAt: number }
10}
11
12export function advancePressure(state: PressureState, level: PressureLevel | null, now: number): {
13  state: PressureState
14  transition?: { prev: PressureLevel; level: PressureLevel }
15} {
16  const next: PressureState = { ...state, sampledAt: now, candidate: undefined }
17  if (level === null) return { state: next }
18  next.lastValid = { level, sampledAt: now }
19  if (state.confirmed === undefined) return { state: { ...next, confirmed: level } }
20  if (state.sampledAt !== undefined && now - state.sampledAt > 5000) return { state: next }
21  if (level === state.confirmed) return { state: next }
22  if (level !== state.candidate) return { state: { ...next, candidate: level } }
23  return { state: { ...next, confirmed: level }, transition: { prev: state.confirmed, level } }
24}
25
26export type Monitor = {
27  interactive: boolean
28  platform?: Promise<boolean>
29  state: PressureState
30  active?: { sessionId: string; reading: boolean; submitting: boolean; timer?: Timer; notice?: { level: PressureLevel; at: number } }
31}
32
33function isMacOS($: EngineInterface, monitor: Monitor) {
34  monitor.platform ??= $.process.run(['uname', '-s'])
35    .then(result => result.exitCode === 0 && result.stdout.trim() === 'Darwin')
36    .catch(() => false)
37  return monitor.platform
38}
39
40// $.prompt.submit 은 세션이 쉴 때만 턴을 연다. 피어 메시지는 도는 턴 안에도 닿으므로 먼저 자기 세션에 보낸다.
41export async function notifyLead($: EngineInterface, text: string, isActive: () => boolean) {
42  let reason: string
43  try {
44    const sessionId = await $.session.id()
45    const result = await $.process.run(['tfx-peer', 'self', '--session', sessionId, '--message', text], { stdin: '', timeoutMs: 10_000 })
46    let data: { status?: string; error?: string } = {}
47    try {
48      data = JSON.parse(result.stdout)
49    } catch {
50      // 실패하면 stdout 이 비어 있고 이유는 stderr 에 있다.
51    }
52    if (result.exitCode === 0 && data.status === 'written') return
53    reason = data.status ? `${data.status}${data.error ? `, ${data.error}` : ''}` : result.stderr || `exit ${result.exitCode}`
54  } catch (error) {
55    reason = error instanceof Error ? error.message : String(error)
56  }
57  // 보내는 사이 /tfx-pressure off 나 세션 종료로 감시가 꺼졌으면 폴백하지 않는다.
58  if (!isActive()) return
59  // 스택이나 긴 출력이 프롬프트에 그대로 들어가지 않게 한 줄로 자른다.
60  reason = reason.replace(/\s+/g, ' ').trim().slice(0, 200)
61  await $.prompt.submit({ text: `${text}\n피어 메시지 전송이 실패해 턴이 끝난 뒤 도착하는 prompt.submit 으로 보냈다 (${reason}).` })
62}
63
64function stopMemoryPressure(monitor: Monitor) {
65  monitor.active?.timer?.cancel()
66  monitor.active = undefined
67}
68
69function startMemoryPressure($: EngineInterface, monitor: Monitor, sessionId: string) {
70  if (!monitor.interactive || monitor.active?.sessionId === sessionId) return
71  stopMemoryPressure(monitor)
72  monitor.state = {}
73  const current: NonNullable<Monitor['active']> = { sessionId, reading: false, submitting: false }
74  monitor.active = current
75  current.timer = $.clock.every(2000, async () => {
76    if (current.reading) return
77    current.reading = true
78    try {
79      const sessionId = await $.session.id()
80      const key = 'tfx.pressure.' + current.sessionId
81      const lead = await $.store.get(key)
82      if (!lead) {
83        if (monitor.active === current) stopMemoryPressure(monitor)
84        return
85      }
86      if (sessionId !== current.sessionId) {
87        await $.store.set('tfx.pressure.' + sessionId, lead)
88        await $.store.delete(key)
89        current.sessionId = sessionId
90      }
91      let level: PressureLevel | null = null
92      try {
93        const result = await $.process.run(['sysctl', '-n', 'kern.memorystatus_vm_pressure_level'])
94        const value = result.stdout.trim()
95        if (result.exitCode === 0 && (value === '1' || value === '2' || value === '4')) {
96          level = Number(value) as PressureLevel
97        }
98      } catch {
99        // 실패한 측정도 unknown 표본으로 보내 연속 후보를 끊는다.
100      }
101      const now = await $.clock.now()
102      if (monitor.active !== current) return
103      const result = advancePressure(monitor.state, level, now)
104      monitor.state = result.state
105      if (result.transition) {
106        const { prev, level } = result.transition
107        // critical 로 오를 때만 턴을 연다. 나머지 전이는 다음 요청에 한 줄로 붙이고, 그 사이 또 바뀌면 마지막 상태로 덮는다.
108        if (level !== 4) current.notice = { level, at: now }
109        else {
110          current.notice = undefined
111          // 앞서 보낸 critical 알림이 아직 도착하지 않았으면 그것이 리드를 깨운다.
112          if (current.submitting) return
113          current.submitting = true
114          const text = `[memory-pressure] 압박 단계가 ${prev} 에서 4 로 올랐다. 현재 4 critical (${new Date(now).toISOString()}). tfx-lead 스킬 "압박 변화 대응" 절의 critical 행을 지금 실행하라.`
115          notifyLead($, text, () => monitor.active === current)
116            .catch(() => {})
117            .finally(() => { current.submitting = false })
118        }
119      }
120    } finally {
121      current.reading = false
122    }
123  })
124}
125
126// /tfx-pressure on 과 /tfx-lead <역할> 이 같이 쓴다.
127export async function enablePressure($: EngineInterface, monitor: Monitor) {
128  if (!monitor.interactive) return '메모리 압박 감시는 대화형 세션에서만 지원'
129  if (!await isMacOS($, monitor)) return '메모리 압박 감시는 macOS 에서만 지원'
130  const sessionId = await $.session.id()
131  await $.store.set('tfx.pressure.' + sessionId, { since: new Date(await $.clock.now()).toISOString() })
132  startMemoryPressure($, monitor, sessionId)
133  return '메모리 압박 감시: on'
134}
135
136function takeNotice(monitor: Monitor) {
137  const active = monitor.active
138  const notice = active?.notice
139  if (!active || !notice) return
140  active.notice = undefined
141  return `메모리 압박: 현재 ${notice.level}(${new Date(notice.at).toISOString()}, 1 normal 2 warn 4 critical)`
142}
143
144export function registerMemoryPressure(on: On, monitor: Monitor) {
145  // 같은 이벤트를 필터 없이 등록하면 HUD 훅과 겹쳐 로드가 거부된다. isInteractive 로 나눠 둘 다 받는다.
146  for (const isInteractive of [true, false]) {
147    on('session.start', { isInteractive }, async ($, e, next) => {
148      monitor.interactive = e.isInteractive
149      stopMemoryPressure(monitor)
150      monitor.state = {}
151      await $.command.register({ name: 'tfx-pressure', description: '메모리 압박 감시: on|off|status' })
152      const sessionId = await $.session.id()
153      if (monitor.interactive && await $.store.get('tfx.pressure.' + sessionId) && await isMacOS($, monitor)) {
154        startMemoryPressure($, monitor, sessionId)
155      }
156      return next(e)
157    })
158  }
159  on('session.end', { reason: ['prompt_input_exit', 'resume', 'logout', 'other'] }, async ($, e, next) => {
160    await $.store.delete('tfx.pressure.' + e.sessionId)
161    return next(e)
162  })
163  // prompt.attachment 는 엔진이 만든 주입만 고칠 수 있어 새 줄을 더하지 못한다. 리드의 다음 요청은 새 입력이나 도구 결과로 나가므로 그 둘의 context 에 붙인다.
164  on('prompt.submit', async ($, e, next) => {
165    const notice = takeNotice(monitor)
166    return next(notice ? { ...e, context: [...(e.context ?? []), notice] } : e)
167  })
168  on('tool.call', async ($, e, next) => {
169    const result = await next(e)
170    // 서브에이전트의 도구 결과와 플러그인이 직접 호출한 결과의 context 는 리드 모델이 읽지 않으니 다음 기회로 남긴다.
171    if (next.origin.plugin !== 'engine' || e.agentId !== undefined || result.deny !== undefined) return result
172    const notice = takeNotice(monitor)
173    return notice ? { ...result, context: [...(result.context ?? []), notice] } : result
174  })
175  on('command.run', { command: 'tfx-pressure' }, async ($, e) => {
176    const sessionId = await $.session.id()
177    const key = 'tfx.pressure.' + sessionId
178    switch (e.args.trim()) {
179      case 'on':
180        return { text: await enablePressure($, monitor) }
181      case 'off': {
182        // /clear 직후면 등록이 아직 옛 ID 키에 있을 수 있어 둘 다 지운다.
183        const activeId = monitor.active?.sessionId
184        stopMemoryPressure(monitor)
185        await $.store.delete(key)
186        if (activeId && activeId !== sessionId) await $.store.delete('tfx.pressure.' + activeId)
187        return { text: '메모리 압박 감시: off' }
188      }
189      case 'status': {
190        const lead = await $.store.get(key)
191        const sample = monitor.state.lastValid
192        return { text: `압박 감시: ${lead ? 'on' : 'off'}. 마지막 유효 표본: ${sample ? `${sample.level} (${new Date(sample.sampledAt).toISOString()})` : '없음'}. 마지막 확정 단계: ${monitor.state.confirmed ?? '없음'}.` }
193      }
194      default:
195        return { text: '사용법: /tfx-pressure on|off|status' }
196    }
197  })
198}
199
hooks/native-message.ts 135 lines
1import type { EngineInterface, On, ProcessRunInit, ToolCallResult } from 'claude-code'
2
3type PeerTarget = { cli: string; name: string; target?: string | null }
4type SendResult = {
5  ok: boolean
6  to?: PeerTarget
7  transport?: string
8  status?: string
9  reason?: string
10  error?: string
11  candidates?: PeerTarget[]
12}
13
14function structuredMessage(message: string) {
15  try {
16    const parsed = JSON.parse(message)
17    return parsed !== null && typeof parsed === 'object'
18  } catch {
19    return false
20  }
21}
22
23function missingRecipient(result: ToolCallResult<'SendMessage'>) {
24  const body = result.result
25  if (!result.isError && !(body && typeof body === 'object' && 'success' in body && body.success === false)) return false
26  const text = result.text ?? (typeof body === 'string' ? body : body && typeof body === 'object' && 'message' in body && typeof body.message === 'string' ? body.message : '')
27  return /no (?:agent|session|recipient) (?:named|found|with\b)|(?:agent|session|recipient)\b[^\n]*\b(?:not found|does not exist|doesn't exist)|unknown (?:agent|session|recipient)/i.test(text)
28}
29
30async function processOptions($: EngineInterface): Promise<ProcessRunInit> {
31  const pid = await $.env.get('CLAUDE_PID')
32  return { stdin: '', timeoutMs: 30_000, env: { CLAUDECODE: '1', ...(pid ? { CLAUDE_PID: pid } : {}) } }
33}
34
35function sendFailure(error: unknown, attempted: boolean, returned: boolean) {
36  const detail = error instanceof Error ? error.message : String(error)
37  const code = error && typeof error === 'object' && 'code' in error ? String(error.code) : ''
38  // 시작 실패를 증명하지 못하면 timeout 등으로 이미 전달됐을 수 있다.
39  const uncertain = attempted && (returned || !/\b(?:ENOENT|EACCES|ENOEXEC)\b/.test(`${code} ${detail}`))
40  return {
41    uncertain,
42    answer: { deny: uncertain
43      ? `결과 불명. 이미 들어갔을 수 있으니 재전송하지 말고 상대 회신을 확인하라 (${detail}).`
44      : `전송 실패: ${detail}.` },
45  }
46}
47
48async function send($: EngineInterface, to: string, message: string) {
49  let attempted = false
50  let returned = false
51  try {
52    const options = await processOptions($)
53    attempted = true
54    const process = await $.process.run(['tfx-live', 'send', '--to', to, '--message', message, '--no-wait'], options)
55    returned = true
56    if (process.isStdoutTruncated) throw new Error('tfx-live output truncated')
57    const data: SendResult = JSON.parse(process.stdout)
58    if (!data || typeof data.ok !== 'boolean') throw new Error('Invalid tfx-live send result')
59    if (data.ok && process.exitCode === 0) {
60      if (!data.to || typeof data.to.cli !== 'string' || typeof data.to.name !== 'string' || typeof data.transport !== 'string')
61        throw new Error('Invalid tfx-live send target')
62      return { answer: { result: `${data.to.cli}:${data.to.name} 세션에 ${data.transport} 경로로 넣었다 (${data.status ?? 'sent'}).` } }
63    }
64    const candidates = (data.candidates ?? []).map(candidate => `${candidate.cli}:${candidate.name}${candidate.target ? ` (${candidate.target})` : ''}`)
65    return {
66      answer: { deny: `전송 실패: ${data.reason ?? `exit ${process.exitCode}`}${data.error ? `, ${data.error}` : ''}. 후보: ${candidates.length ? candidates.join(', ') : '없음'}.` },
67    }
68  } catch (error) {
69    return sendFailure(error, attempted, returned)
70  }
71}
72
73async function sendPeer($: EngineInterface, to: string, message: string) {
74  let attempted = false
75  let returned = false
76  try {
77    const options = await processOptions($)
78    attempted = true
79    const process = await $.process.run(['tfx-peer', 'send', '--to', to, '--message', message], options)
80    returned = true
81    if (process.isStdoutTruncated) throw new Error('tfx-peer output truncated')
82    if (process.exitCode === 1 && !process.stdout.trim())
83      return { deny: `전송 실패: ${process.stderr.trim() || 'exit 1'}.` }
84    let data: { status: string; error?: string }
85    try {
86      data = JSON.parse(process.stdout)
87    } catch (error) {
88      throw new Error(process.stderr.trim() || (error instanceof Error ? error.message : String(error)))
89    }
90    if (!data || !['written', 'sent', 'partial', 'unknown'].includes(data.status)) throw new Error('Invalid tfx-peer send result')
91    if (process.exitCode === 0 && (data.status === 'written' || data.status === 'sent'))
92      return { result: `${to} 세션에 native peer 경로로 넣었다 (${data.status}).` }
93    if (data.status === 'partial' || data.status === 'unknown')
94      return { deny: `결과 불명. 이미 들어갔을 수 있으니 재전송하지 말고 상대 회신을 확인하라 (${data.status}${data.error ? `, ${data.error}` : ''}).` }
95    return { deny: `전송 실패: exit ${process.exitCode}${data.error ? `, ${data.error}` : ''}.` }
96  } catch (error) {
97    return sendFailure(error, attempted, returned).answer
98  }
99}
100
101export function registerNativeMessage(on: On) {
102  on('tool.call', { tool: 'SendMessage' }, async ($, e, next) => {
103    if (typeof e.to !== 'string' || typeof e.message !== 'string' || structuredMessage(e.message)) return next(e)
104    if (/^codex:/i.test(e.to)) return sendPeer($, `codex:${e.to.slice(6)}`, e.message)
105    if (/^(?:agy|antigravity):/i.test(e.to)) return (await send($, e.to, e.message)).answer
106    const original = await next(e)
107    if (!missingRecipient(original) || /^(?:claude|codex):/i.test(e.to)) return original
108    const sent = await send($, `agy:${e.to}`, e.message)
109    return ('uncertain' in sent && sent.uncertain) || !('deny' in sent.answer) ? sent.answer : original
110  })
111
112  on('tool.call', { tool: 'ListAgents' }, async ($, e, next) => {
113    const original = await next(e)
114    if (original.deny || original.isError || typeof original.result?.listing !== 'string') return original
115    try {
116      const rows: string[] = []
117      for (const cli of ['codex', 'agy']) {
118        const process = await $.process.run(['tfx-live', 'list-sessions', '--cli', cli], { stdin: '', timeoutMs: 10_000 })
119        if (process.exitCode !== 0 || process.isStdoutTruncated) return original
120        const data = JSON.parse(process.stdout)
121        if (!data?.ok || !Array.isArray(data.sessions)) return original
122        for (const session of data.sessions) {
123          const name = session.name || session.panes?.[0]?.name || session.session
124          if (typeof name === 'string' && name) rows.push(`${cli}:${name}`)
125        }
126      }
127      if (!rows.length) return original
128      // ref 와 text 를 남기면 core 가 원래 표시를 재사용하므로 바꾼 결과를 다시 그리게 한다.
129      return { result: { ...original.result, listing: `${original.result.listing}\n\n${rows.join('\n')}` }, context: original.context, isReadOnly: original.isReadOnly }
130    } catch {
131      return original
132    }
133  })
134}
135
hooks/report-limit.ts 95 lines
1import type { EngineInterface, On } from 'claude-code'
2
3import { type Holder, leadOf } from './lead-role.ts'
4
5export const reportLimit = 4000
6const headLength = 800
7const pathLimit = 20
8
9// /, ./, ~/ 로 시작하는 낱말만 후보로 본다. 버전 문자열(10.82.1/10.82.3)이나 낱말 사이 빗금(Codex/agy)은 여기서 빠진다.
10const candidatePattern = /(?<![^\s'"`(\[<])(?:~\/|\.\/|\/)[^\s'"`<>()\[\]{},]+/gu
11// 경로 끝에 붙은 문장부호와 한글 조사는 떼고 판정한다.
12const trailing = /(?:[.,;:!?)]|을|를|은|는|이|가|에|에서|의|로|으로|와|과|도)+$/u
13const knownDir = /(?:^|\/)(?:\.omc|docs|scripts|tests|hud|mods|bin|packages)(?:\/|$)/
14const extension = /\/[^/]*[^/.]\.[A-Za-z0-9]{1,8}$/
15
16export function filePaths(text: string) {
17  const paths = new Set<string>()
18  for (const [candidate] of text.matchAll(candidatePattern)) {
19    const path = candidate.replace(trailing, '')
20    if (/^[~./\d]+$/.test(path)) continue
21    if (extension.test(path) || knownDir.test(path)) paths.add(path)
22  }
23  return [...paths]
24}
25
26type Shortened = { kind: 'keep' } | { kind: 'warn'; total: number } | { kind: 'cut'; text: string }
27
28// 리드 규칙상 결과 원문은 파일에 있으므로, 경로가 보일 때만 자른다. 경로가 없으면 원문을 잃으니 자르지 않는다.
29// report 는 남길 본문, whole 은 길이를 재고 경로를 찾을 전체 글이다.
30export function shorten(report: string, whole = report): Shortened {
31  if (whole.length <= reportLimit) return { kind: 'keep' }
32  const paths = filePaths(whole)
33  if (!paths.length) return { kind: 'warn', total: whole.length }
34  const listed = paths.slice(0, pathLimit).map(path => `- ${path}`)
35  if (paths.length > pathLimit) listed.push(`- 외 ${paths.length - pathLimit}개`)
36  return { kind: 'cut', text: `${report.slice(0, headLength)}\n\n(중략)\n파일 경로:\n${listed.join('\n')}\n원문 ${whole.length}자, 결과 파일 참조` }
37}
38
39type Block = { type: string; [field: string]: unknown }
40
41// text 블록과 tool_result 안의 글을 차례로 visit 에 넘긴다. null 을 돌려받은 text 블록은 뺀다.
42function mapTexts(content: readonly Block[], visit: (text: string) => string | null): Block[] {
43  const mapped: Block[] = []
44  for (const block of content) {
45    if (block.type === 'text' && typeof block.text === 'string') {
46      const text = visit(block.text)
47      if (text !== null) mapped.push({ ...block, text })
48    } else if (block.type === 'tool_result' && typeof block.content === 'string') {
49      mapped.push({ ...block, content: visit(block.content) ?? '' })
50    } else if (block.type === 'tool_result' && Array.isArray(block.content)) {
51      mapped.push({ ...block, content: mapTexts(block.content as Block[], visit) })
52    } else {
53      mapped.push(block)
54    }
55  }
56  return mapped
57}
58
59// 하네스가 붙이는 agentId, usage 같은 짧은 블록은 살리고 긴 본문 블록들을 하나로 줄인다.
60export function shortenContent(content: readonly Block[]): Shortened & { content?: Block[] } {
61  const texts: string[] = []
62  mapTexts(content, text => (texts.push(text), text))
63  const long = texts.filter(text => text.length > headLength)
64  if (!long.length) return { kind: 'keep' }
65  const result = shorten(long.join('\n'), texts.join('\n'))
66  if (result.kind !== 'cut') return result
67  let first = true
68  return { ...result, content: mapTexts(content, text => text.length <= headLength ? text : first ? ((first = false), result.text) : null) }
69}
70
71async function warn($: EngineInterface, source: string, total: number) {
72  await $.ui.toast(`[tfx-lead] ${source} ${total}자가 상한 ${reportLimit}자를 넘었지만 파일 경로가 없어 자르지 않았다. 결과는 파일로 받는다.`)
73}
74
75export function registerReportLimit(on: On, lead: Holder) {
76  // 이 plugin 의 다른 session.receive 훅에 matcher 가 없어 겹치지 않게 origin 으로 좁힌다.
77  on('session.receive', { origin: { kind: /^peer(?:-send-message)?$/ } }, async ($, e, next) => {
78    if (e.agentId || e.text.length <= reportLimit || !(await leadOf($, lead))) return next(e)
79    const result = shorten(e.text)
80    if (result.kind === 'cut') return next({ ...e, text: result.text })
81    if (result.kind === 'warn') await warn($, '피어 메시지', result.total)
82    return next(e)
83  })
84  // 서브에이전트 결과는 포그라운드면 Agent 도구 결과로, 백그라운드면 작업 알림으로 리드 대화에 들어온다.
85  on('session.append', async ($, e, next) => {
86    const isHandback = e.origin.kind === 'task-notification' || (e.origin.kind === 'tool' && e.origin.tool === 'Agent')
87    if (e.agentId || !isHandback) return next(e)
88    const result = shortenContent(e.message.content)
89    if (result.kind === 'keep' || !(await leadOf($, lead))) return next(e)
90    if (result.content) return next({ ...e, message: { ...e.message, content: result.content } })
91    if (result.kind === 'warn') await warn($, '서브에이전트 결과', result.total)
92    return next(e)
93  })
94}
95
types/index.d.ts 11 lines
1export type BandSpan = { text: string; color?: string; bold?: boolean; dim?: boolean }
2
3// statusLine HUD 가 --band 로 그린 줄들. columns 는 그때 넘긴 폭이다.
4export type BandRows = { columns: number; lines: BandSpan[][] }
5
6declare module 'claude-code' {
7  interface PluginState {
8    'triflux-mods': { rows: BandRows | null }
9  }
10}
11