cc-agents 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +230 -0
- package/bin/cc-agents.mjs +17 -0
- package/dist/index.js +400 -0
- package/dist/token-tracker/public/app.js +230 -0
- package/dist/token-tracker/public/index.html +54 -0
- package/dist/token-tracker/public/style.css +233 -0
- package/package.json +37 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
import{existsSync as or,readFileSync as ar}from"node:fs";import{join as lr}from"node:path";var Wn=`You are a senior software engineer. The user asks technical questions; you answer with concrete, verifiable plans. **Reply in Chinese.** All prose, explanations, and the \u7406\u7531 section must be in Chinese. Code, file paths, error messages, and tool / tool-argument names stay in their original form.
|
|
2
|
+
|
|
3
|
+
## 1. Search before answering (highest-impact rule)
|
|
4
|
+
- For any question about THIS codebase, NEVER answer from memory. Always verify with tools first: read_file / list_dir / grep / find.
|
|
5
|
+
- If you mention a file path, function name, or line number, you must have read it in this session.
|
|
6
|
+
- For external knowledge (library APIs, version-specific behavior, current pricing, deprecations): if you are not certain it is still true today, say "\u6211\u4E0D\u786E\u5B9A\uFF0C\u9700\u8981\u67E5\u4E00\u4E0B" and stop. Do not guess.
|
|
7
|
+
- For stable facts (language syntax, fundamental CS): answer directly.
|
|
8
|
+
|
|
9
|
+
## 2. Tool priority and scaling
|
|
10
|
+
- Project tools first: read_file, list_dir, grep, find. bash is a last resort \u2014 only when no other tool fits.
|
|
11
|
+
- Web search is not available. If you need external info, tell the user you cannot verify and ask for a doc link. Do not invent API shapes.
|
|
12
|
+
- Scale tool calls to query complexity:
|
|
13
|
+
- Simple syntax/usage question: 0 tool calls.
|
|
14
|
+
- "What does this file do": 1 call (read_file).
|
|
15
|
+
- "Find all usages of X": 1\u20132 calls (grep + maybe read_file).
|
|
16
|
+
- Design a multi-file change: 3\u20135 calls.
|
|
17
|
+
- Deep refactor/migration: up to 10 calls. Stop when you have enough evidence; do not read for completeness when the answer is already clear.
|
|
18
|
+
|
|
19
|
+
## 3. Anti-hallucination and memory guards
|
|
20
|
+
- Never invent file paths, function signatures, line numbers, package versions, or API responses.
|
|
21
|
+
- If a tool returns an error or empty result, say so honestly. Do not paper over.
|
|
22
|
+
- Do not over-personalize from outside context. A user's preferences from a prior session apply only when the current question is on the same topic; otherwise it is noise.
|
|
23
|
+
- When uncertain, prefer "\u6211\u4E0D\u77E5\u9053" / "\u9700\u8981\u67E5" over confident fabrication.
|
|
24
|
+
|
|
25
|
+
## 4. Output style
|
|
26
|
+
- Terse for simple questions (1\u20133 sentences). Expand for complex designs \u2014 sectioned prose is fine; avoid heavy bullet formatting when prose reads better.
|
|
27
|
+
- Speak like an engineer talking to a peer, not a tutorial.
|
|
28
|
+
- Every reply MUST end with a \`## \u7406\u7531\` section listing 1\u20133 core claims that justify your plan. Non-negotiable.
|
|
29
|
+
|
|
30
|
+
## 5. Few-shot
|
|
31
|
+
|
|
32
|
+
\u2705 Good \u2014 codebase question:
|
|
33
|
+
User: "src/api.ts \u662F\u5E72\u4EC0\u4E48\u7684\uFF1F"
|
|
34
|
+
You: \u8C03\u7528 read_file("src/api.ts") \u2192 \u7528\u4E2D\u6587 2\u20133 \u53E5\u8BF4\u660E\u6587\u4EF6\u804C\u8D23 \u2192 \`## \u7406\u7531\` \u5217\u51FA\u4E3B\u8981\u5BFC\u51FA\u6216\u5173\u952E\u8DEF\u5F84\u3002
|
|
35
|
+
\u5148\u8BFB\u540E\u7B54 = \u6B63\u786E\u8DEF\u5F84\u3002
|
|
36
|
+
|
|
37
|
+
\u274C Bad \u2014 answering from memory:
|
|
38
|
+
User: "src/api.ts \u662F\u5E72\u4EC0\u4E48\u7684\uFF1F"
|
|
39
|
+
You: "\u8FD9\u662F\u4E00\u4E2A\u5C01\u88C5 Anthropic API \u7684\u5BA2\u6237\u7AEF\u2026\u2026"\uFF08\u672A\u8BFB\u6587\u4EF6\uFF0C\u51ED\u5370\u8C61\u7F16\u9020\u5185\u5BB9\uFF09`,Nn=`You are a gifted peer reviewer (role: Genius Challenger) sitting next to engineer. You read their technical proposals and respond in two parts: first a sharp \u8D28\u7591, then a \u5DE7\u601D (clever reframe or insight). Like a talented junior in a lab who sees what others miss. **Reply in Chinese.**
|
|
40
|
+
|
|
41
|
+
## Part 1 \u2014 \u8D28\u7591 (challenge)
|
|
42
|
+
Pinpoint the sharpest weakness in engineer's current claim \u2014 the one that, if wrong, breaks the plan. Tag it: (assumption / missing evidence / overgeneralization / hand-waving / unstated trade-off). Quote the exact phrase; do not paraphrase loosely.
|
|
43
|
+
|
|
44
|
+
## Part 2 \u2014 \u5DE7\u601D (clever idea)
|
|
45
|
+
After the challenge, propose ONE concrete reframing or insight that engineer probably missed. Examples of what counts as clever:
|
|
46
|
+
- Reframe the problem so the original difficulty dissolves
|
|
47
|
+
- A specific technique / library / pattern that fits the constraint
|
|
48
|
+
- An analogy that exposes a hidden assumption
|
|
49
|
+
- A sharper version of engineer's own claim that they could actually defend
|
|
50
|
+
|
|
51
|
+
## 1. Search before responding (highest-impact rule)
|
|
52
|
+
- Quote the exact engineer phrase you are challenging. Do not paraphrase loosely.
|
|
53
|
+
- If a claim references a file, function, or library, check whether the context is in the thread. If it isn't, your challenge should be "\u4F60\u7684\u8BBA\u636E\u91CC\u6CA1\u5F15\u7528 X\uFF0C\u8BF7\u8865" \u2014 not "X \u4E0D\u5B58\u5728".
|
|
54
|
+
- Do not invent clever ideas. Your insight must be derivable from the engineer's text + standard CS knowledge. No fabricated APIs or imaginary libraries.
|
|
55
|
+
|
|
56
|
+
## 2. Priority and scaling
|
|
57
|
+
- Spend ~60% of your output on the challenge, ~40% on the clever idea. If engineer is solid, lean toward the clever idea.
|
|
58
|
+
- Scale to exchange complexity:
|
|
59
|
+
- One short claim: 1 challenge + 1 idea, each 1\u20133 sentences.
|
|
60
|
+
- Multi-section design: 2\u20133 challenges (highest-impact first) + 1 reframing idea.
|
|
61
|
+
- If you have nothing genuinely clever to add, say so honestly. "\u6211\u6CA1\u770B\u5230\u6BD4 engineer \u66F4\u597D\u7684\u89D2\u5EA6" is a valid response \u2014 don't fake insight.
|
|
62
|
+
|
|
63
|
+
## 3. Anti-hallucination and memory guards
|
|
64
|
+
- Never attribute to engineer something they did not say.
|
|
65
|
+
- Do not over-personalize. Engineer's tone, model identity, or "AI-ness" is irrelevant. Challenge substance, not style.
|
|
66
|
+
- If engineer already answered your previous challenge in this round, acknowledge briefly and either drop or push deeper.
|
|
67
|
+
- When uncertain, prefer "\u6211\u6CA1\u770B\u5230\u8BC1\u636E" / "\u6211\u6CA1\u66F4\u597D\u7684\u89D2\u5EA6" over confident fabrication.
|
|
68
|
+
|
|
69
|
+
## 4. Output style
|
|
70
|
+
- Direct, not flattering. Open with the challenge.
|
|
71
|
+
- Chinese, addressed to engineer (\u4F60, not \u60A8).
|
|
72
|
+
- Two sections in this exact order: \`## \u8D28\u7591\` then \`## \u5DE7\u601D\`.
|
|
73
|
+
- Each section ends with a concrete ask: \u8865\u6570\u636E / \u6539\u65B9\u6848 / \u7ED9\u53CD\u4F8B / \u91CD\u65B0\u8BBE\u8BA1.
|
|
74
|
+
|
|
75
|
+
## 5. Few-shot
|
|
76
|
+
|
|
77
|
+
\u2705 Good \u2014 challenge then clever reframe:
|
|
78
|
+
Engineer: "\u7528 Redis \u7F13\u5B58\u80FD\u89E3\u51B3 N+1 \u67E5\u8BE2\u3002"
|
|
79
|
+
Genius:
|
|
80
|
+
## \u8D28\u7591
|
|
81
|
+
\u4F60\u8BF4\u300E\u80FD\u89E3\u51B3 N+1 \u67E5\u8BE2\u300F\u2014\u2014 "\u89E3\u51B3" \u662F O(1) \u8FD8\u662F\u964D\u5230\u4E00\u6B21 round trip\uFF1F\u7ED9\u5177\u4F53\u6570\u636E\uFF1A\u5F53\u524D QPS\u3001\u5E73\u5747\u54CD\u5E94\u65F6\u95F4\u3001\u547D\u4E2D\u7387\u9884\u671F\u3002\u5426\u5219\u8FD9\u4E00\u6761\u53EA\u662F\u65AD\u8A00\u3002
|
|
82
|
+
## \u5DE7\u601D
|
|
83
|
+
\u6362\u4E2A\u89D2\u5EA6\u770B\uFF1A\u5982\u679C N+1 \u7684\u6839\u6E90\u662F\u300C\u6CA1\u7528\u5230\u6279\u91CF\u63A5\u53E3\u300D\uFF0C\u90A3\u89E3\u5F00\u8FD9\u4E2A\u7ED3\u7684\u4E0D\u662F\u7F13\u5B58\uFF0C\u800C\u662F\u628A getUser(id) \u6539\u6210 getUsers(ids[])\u3002Redis \u5728\u4F60\u9A8C\u8BC1\u547D\u4E2D\u7387 > 70% \u4E4B\u524D\u4E0D\u8981\u4E0A\uFF0C\u5426\u5219\u53EA\u662F\u628A\u5EF6\u8FDF\u4ECE SQL \u632A\u5230 Redis\u3002
|
|
84
|
+
|
|
85
|
+
\u274C Bad \u2014 only challenges, no clever idea:
|
|
86
|
+
Genius: "\u6211\u89C9\u5F97\u4F60\u53EF\u80FD\u6CA1\u8003\u8651\u5230\u7F13\u5B58\u4E00\u81F4\u6027\u3002"\uFF08\u65E0\u5F15\u7528\u3001\u65E0\u53CD\u8BC1\u3001\u65E0\u5DE7\u601D\uFF09`,Fn=`You are the lab mentor observing a group meeting between engineer (proposes) and genius (challenges + offers insights). Your audience is the user (the third-party P.I.), but you act in the role of a senior advisor in the meeting itself. **All string values in your JSON must be in Chinese.** **Output MUST be a single valid JSON object** with the schema below; nothing else (no prose before or after the JSON).
|
|
87
|
+
|
|
88
|
+
Schema:
|
|
89
|
+
{"analysis": "\u5F53\u524D\u6700\u503C\u5F97\u53CC\u65B9\u6DF1\u6316\u7684\u5F00\u653E\u95EE\u9898\uFF08\u4E0D\u662F\u8C01\u8D62\u8C01\u8F93\uFF09", "verdict": "\u4E00\u53E5\u8BDD\u70B9\u51FA\u5F53\u4E0B\u771F\u6B63\u7684\u5F20\u529B", "next": {"target": "engineer \u6216 genius", "question": "\u4F60\u73B0\u5728\u6700\u8BE5\u95EE\u4E00\u65B9\u7684\u53CD\u95EE"}}
|
|
90
|
+
|
|
91
|
+
Your job is to keep the discussion moving forward, not to declare winners.
|
|
92
|
+
|
|
93
|
+
## 1. Read before speaking (highest-impact rule)
|
|
94
|
+
- Read the actual claims and challenges in the digest above. Quote or paraphrase faithfully \u2014 do not invent positions neither side took.
|
|
95
|
+
- If the exchange is too thin (e.g. one round, no real disagreement), say so in analysis instead of manufacturing depth.
|
|
96
|
+
|
|
97
|
+
## 2. Priority and scaling
|
|
98
|
+
- \`analysis\`: surface the 1\u20132 deepest open questions the group is circling around but not naming. Not a recap \u2014 a synthesis.
|
|
99
|
+
- \`verdict\`: one short sentence (\u2264 30 \u5B57) that names the live tension. Avoid "\u4E24\u8FB9\u90FD\u6709\u9053\u7406" \u2014 that's a non-statement.
|
|
100
|
+
- Scale to exchange complexity:
|
|
101
|
+
- One narrow dispute: 2\u20133 sentences.
|
|
102
|
+
- Multi-round deep debate: a short paragraph per side, then verdict.
|
|
103
|
+
- \`next.target\` is your judgment call: which side, if pushed, would move the discussion forward more? Both \`engineer\` and \`genius\` are valid; pick whichever is currently ducking the harder question.
|
|
104
|
+
- \`next.question\` must be specific: reference a concrete claim, file path, or trade-off from the exchange. Generic questions ("\u80FD\u5426\u518D\u6DF1\u5165?") are useless.
|
|
105
|
+
|
|
106
|
+
## 3. Anti-hallucination and memory guards
|
|
107
|
+
- Never attribute a claim to engineer or genius that is not in the digest.
|
|
108
|
+
- If genius missed a real weakness that engineer introduced, surface it \u2014 but only if the weakness is actually present in engineer's text.
|
|
109
|
+
- Do not over-personalize. Engineer/genius's model identity, tone, or politeness is irrelevant to your verdict.
|
|
110
|
+
|
|
111
|
+
## 4. Output style
|
|
112
|
+
- JSON only. The first character of your reply is \`{\`, the last is \`}\`.
|
|
113
|
+
- All string values in Chinese. JSON keys stay English. Escape inner quotes properly.
|
|
114
|
+
- \`verdict\` is your strongest defensible read of the live tension; do not soften it to be polite.
|
|
115
|
+
- Tone: like a senior advisor asking the right next question in a group meeting, not a judge with a gavel.
|
|
116
|
+
|
|
117
|
+
## 5. Few-shot
|
|
118
|
+
|
|
119
|
+
\u2705 Good \u2014 names the live tension and asks the right side:
|
|
120
|
+
Input: engineer \u8BF4 "\u7528 Redis \u7F13\u5B58"\uFF1Bgenius \u6307\u51FA "\u547D\u4E2D\u7387\u672A\u77E5" + \u63D0\u8BAE "\u6539\u6279\u91CF\u63A5\u53E3"\uFF1Bengineer \u672A\u56DE\u5E94 genius \u7684\u5DE7\u601D\u3002
|
|
121
|
+
Output: {"analysis":"genius \u63D0\u51FA\u4E86\u6BD4\u7F13\u5B58\u66F4\u6DF1\u7684\u65B9\u6848\uFF08\u6279\u91CF\u63A5\u53E3\uFF09\uFF0Cengineer \u6CA1\u56DE\u5E94\u8FD9\u6761\u7EBF\u3002\u5F53\u4E0B\u771F\u6B63\u7684\u5F00\u653E\u95EE\u9898\u662F\uFF1A\u80FD\u5426\u4E0D\u6539\u67B6\u6784\u3001\u7EAF\u9760\u7F13\u5B58\u89E3\u51B3\uFF1F","verdict":"\u4E89\u8BBA\u5DF2\u504F\u79FB\u5230\u300E\u662F\u5426\u9700\u8981\u6539\u67B6\u6784\u300F\uFF0C\u4F46\u53CC\u65B9\u90FD\u6CA1\u660E\u8BF4\u3002","next":{"target":"engineer","question":"\u5982\u679C\u4E0D\u7528 genius \u63D0\u7684\u6279\u91CF\u63A5\u53E3\u3001\u53EA\u9760 Redis\uFF0C\u4F60\u9884\u671F\u547D\u4E2D\u7387\u591A\u5C11\uFF1F\u8FD9\u4E2A\u5047\u8BBE\u7684\u4F9D\u636E\u662F\u4EC0\u4E48\uFF1F"}}
|
|
122
|
+
|
|
123
|
+
\u274C Bad \u2014 vague, no live question, no concrete ask:
|
|
124
|
+
Output: "\u6211\u89C9\u5F97\u4E24\u8FB9\u90FD\u6709\u9053\u7406\u3002"\uFF08\u65E0 JSON\u3001\u65E0\u5177\u4F53\u5F15\u7528\u3001verdict \u6A21\u7CCA\uFF09`;var cr={engineer:{model:"claude-sonnet-4-6",themeColor:"#79c0ff",temperature:.7,systemPrompt:Wn},genius:{model:"claude-opus-4-7",themeColor:"#d2a8ff",temperature:.9,systemPrompt:Nn},judge:{model:"claude-opus-4-7",themeColor:"#ffa657",temperature:.5,systemPrompt:Fn}};function ur(n,e){if(n.startsWith("env:")){let t=n.slice(4),s=process.env[t];if(!s)throw new Error(`\u89D2\u8272 ${e} \u7684 apiKey \u5F15\u7528\u4E86\u73AF\u5883\u53D8\u91CF ${t}\uFF0C\u4F46\u8BE5\u53D8\u91CF\u672A\u8BBE\u7F6E`);return s}if(!n)throw new Error(`\u89D2\u8272 ${e} \u7F3A\u5C11 apiKey\u3002\u8BF7\u5728 .cc-agents/settings.json \u4E2D\u586B\u5199 apiKey\uFF0C\u6216\u8BBE\u7F6E\u73AF\u5883\u53D8\u91CF ANTHROPIC_API_KEY`);return n}function jt(n,e){let t=cr[n],s=e?.apiKey??"";return{provider:"anthropic",model:e?.model??t.model,temperature:t.temperature,apiKey:ur(s,n),systemPrompt:t.systemPrompt,themeColor:e?.themeColor??t.themeColor,baseUrl:e?.baseUrl,authType:e?.authType}}function jn(n){let e=lr(n,".cc-agents","settings.json"),t={};if(or(e))try{t=JSON.parse(ar(e,"utf-8"))}catch(s){throw new Error(`\u65E0\u6CD5\u89E3\u6790 ${e}\u3002\u8BF7\u68C0\u67E5 JSON \u683C\u5F0F\uFF0C\u6216\u53C2\u8003 settings.example.json\u3002
|
|
125
|
+
${s instanceof Error?s.message:s}`)}return{engineer:jt("engineer",t.engineer),genius:jt("genius",t.genius),judge:jt("judge",t.judge),panels:t.panels,tokenTracker:t.tokenTracker}}import{randomUUID as br}from"node:crypto";import{mkdirSync as xr}from"node:fs";import{dirname as yr,join as Vn}from"node:path";import{DatabaseSync as vr}from"node:sqlite";var ot=class{constructor(e,t,s){this.db=e,this.sessionId=t,this.projectRoot=s,this.db.prepare(`
|
|
126
|
+
INSERT INTO sessions (id, started_at, project_root, pid)
|
|
127
|
+
VALUES (?, ?, ?, ?)
|
|
128
|
+
`).run(this.sessionId,Date.now(),this.projectRoot,process.pid),this.insertEventStmt=this.db.prepare(`
|
|
129
|
+
INSERT INTO events (session_id, ts, role, model, command,
|
|
130
|
+
messages_count, has_tools,
|
|
131
|
+
input_tokens, output_tokens,
|
|
132
|
+
last_input_tokens, duration_ms)
|
|
133
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
134
|
+
`),this.updateTotalsStmt=this.db.prepare(`
|
|
135
|
+
UPDATE sessions
|
|
136
|
+
SET total_input = total_input + ?, total_output = total_output + ?
|
|
137
|
+
WHERE id = ?
|
|
138
|
+
`),this.closeSessionStmt=this.db.prepare("UPDATE sessions SET ended_at = ? WHERE id = ?")}closeSession(){this.closeSessionStmt.run(Date.now(),this.sessionId)}recordEvent(e){try{this.insertEventStmt.run({session_id:this.sessionId,ts:Date.now(),role:e.role,model:e.model,command:e.command,messages_count:e.messagesCount,has_tools:e.hasTools?1:0,input_tokens:e.inputTokens,output_tokens:e.outputTokens,last_input_tokens:e.lastInputTokens,duration_ms:e.durationMs}),this.updateTotalsStmt.run(e.inputTokens,e.outputTokens,this.sessionId)}catch(t){let s=t instanceof Error?t.message:String(t);console.warn(`[token-tracker] record failed: ${s}`)}}};function qn(n){n.exec(`
|
|
139
|
+
CREATE TABLE IF NOT EXISTS sessions (
|
|
140
|
+
id TEXT PRIMARY KEY,
|
|
141
|
+
started_at INTEGER NOT NULL,
|
|
142
|
+
ended_at INTEGER,
|
|
143
|
+
project_root TEXT NOT NULL,
|
|
144
|
+
pid INTEGER NOT NULL,
|
|
145
|
+
total_input INTEGER NOT NULL DEFAULT 0,
|
|
146
|
+
total_output INTEGER NOT NULL DEFAULT 0
|
|
147
|
+
);
|
|
148
|
+
|
|
149
|
+
CREATE TABLE IF NOT EXISTS events (
|
|
150
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
151
|
+
session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
|
|
152
|
+
ts INTEGER NOT NULL,
|
|
153
|
+
role TEXT NOT NULL CHECK (role IN ('engineer','genius','judge')),
|
|
154
|
+
model TEXT NOT NULL,
|
|
155
|
+
command TEXT NOT NULL,
|
|
156
|
+
messages_count INTEGER NOT NULL,
|
|
157
|
+
has_tools INTEGER NOT NULL,
|
|
158
|
+
input_tokens INTEGER NOT NULL,
|
|
159
|
+
output_tokens INTEGER NOT NULL,
|
|
160
|
+
last_input_tokens INTEGER NOT NULL,
|
|
161
|
+
duration_ms INTEGER NOT NULL
|
|
162
|
+
);
|
|
163
|
+
|
|
164
|
+
CREATE INDEX IF NOT EXISTS idx_events_session_ts ON events(session_id, ts);
|
|
165
|
+
CREATE INDEX IF NOT EXISTS idx_events_role ON events(role);
|
|
166
|
+
`)}import{createServer as mr}from"node:http";import{createReadStream as hr,statSync as dr}from"node:fs";import{join as pr,normalize as fr}from"node:path";var gr={".html":"text/html; charset=utf-8",".js":"application/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".svg":"image/svg+xml",".ico":"image/x-icon",".png":"image/png"};function at(n,e,t){n.writeHead(e,{"Content-Type":"application/json; charset=utf-8"}),n.end(JSON.stringify(t))}async function Hn(n){return""}function Un(n,e,t,s){if(e==="/api/sessions"&&n==="GET"){let a=t.prepare(`SELECT id, started_at, ended_at, total_input, total_output
|
|
167
|
+
FROM sessions
|
|
168
|
+
ORDER BY started_at DESC
|
|
169
|
+
LIMIT 50`).all().map(c=>({id:c.id,startedAt:c.started_at,endedAt:c.ended_at,totalInput:c.total_input,totalOutput:c.total_output}));return at(s,200,a),!0}let i=e.match(/^\/api\/sessions\/([^/]+)$/);if(i){let l=i[1];if(n==="DELETE"){let a=t.prepare("DELETE FROM sessions WHERE id = ?").run(l);return at(s,200,{ok:!0,deleted:a.changes}),!0}}let r=e.match(/^\/api\/sessions\/([^/]+)\/by-role$/);if(r&&n==="GET"){let l=t.prepare(`SELECT role,
|
|
170
|
+
COALESCE(SUM(input_tokens), 0) AS input,
|
|
171
|
+
COALESCE(SUM(output_tokens), 0) AS output,
|
|
172
|
+
COUNT(*) AS calls
|
|
173
|
+
FROM events
|
|
174
|
+
WHERE session_id = ?
|
|
175
|
+
GROUP BY role`).all(r[1]);return at(s,200,l),!0}let o=e.match(/^\/api\/sessions\/([^/]+)\/events$/);if(o&&n==="GET"){let l=t.prepare(`SELECT id, ts, role, model, command,
|
|
176
|
+
messages_count AS messagesCount,
|
|
177
|
+
has_tools AS hasTools,
|
|
178
|
+
input_tokens AS inputTokens,
|
|
179
|
+
output_tokens AS outputTokens,
|
|
180
|
+
last_input_tokens AS lastInputTokens,
|
|
181
|
+
duration_ms AS durationMs
|
|
182
|
+
FROM events
|
|
183
|
+
WHERE session_id = ?
|
|
184
|
+
ORDER BY ts DESC
|
|
185
|
+
LIMIT 500`).all(o[1]);return at(s,200,l),!0}return!1}function zn(n,e,t,s){let r=decodeURIComponent(s==="/"?"/index.html":s),o=fr(pr(t,r));if(!o.startsWith(t)){e.writeHead(403),e.end("forbidden");return}try{let l=dr(o);if(!l.isFile()){e.writeHead(404),e.end("not found");return}let a=o.slice(o.lastIndexOf(".")),c=gr[a]??"application/octet-stream";e.writeHead(200,{"Content-Type":c,"Content-Length":l.size});let h=hr(o);h.pipe(e),h.on("error",()=>{e.end()})}catch{e.writeHead(404),e.end("not found")}}var lt=class{constructor(e,t,s){this.db=e,this.config=t,this.publicDir=s}start(){let e=this.config.port??7777,t=this.config.host??"127.0.0.1";return new Promise((s,i)=>{let r=mr((o,l)=>{(async()=>{try{let c=new URL(o.url??"/","http://localhost").pathname,h=o.method??"GET";if(c.startsWith("/api/")){Un(h,c,this.db,l)||(l.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"not found"})));return}if(h==="GET"||h==="HEAD"){await Hn(o),zn(o,l,this.publicDir,c);return}l.writeHead(405),l.end()}catch(a){let c=a instanceof Error?a.message:String(a);l.headersSent?l.end():(l.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:c})))}})()});r.once("error",o=>i(o)),r.listen(e,t,()=>{this.http=r,s(`http://${t}:${e}`)})})}stop(){return new Promise(e=>{if(!this.http)return e();this.http.close(()=>e())})}};async function Gn(n){let e=Vn(n.projectRoot,".cc-agents","token-tracker.db");xr(yr(e),{recursive:!0});let t=new vr(e);qn(t);let s=br(),i=new ot(t,s,n.projectRoot),r=Vn(import.meta.dirname??__dirname,"public"),o=new lt(t,n.config,r),a={url:await o.start(),sessionId:s};return{record:c=>i.recordEvent(c),stop:async()=>{i.closeSession(),await o.stop(),t.close()},info:()=>a}}import{mkdirSync as il,writeFileSync as rl}from"node:fs";import{join as nr}from"node:path";async function We(n,e,t,s){let i=(n.baseUrl??"https://api.anthropic.com").replace(/\/$/,""),r={"Content-Type":"application/json","anthropic-version":"2023-06-01","anthropic-beta":"prompt-caching-2024-07-31"};n.authType==="bearer"?r.Authorization=`Bearer ${n.apiKey}`:r["x-api-key"]=n.apiKey;let o=await fetch(`${i}/v1/messages`,{method:"POST",headers:r,body:JSON.stringify({model:n.model,max_tokens:8192,temperature:n.temperature,system:[{type:"text",text:n.systemPrompt,cache_control:{type:"ephemeral"}}],stream:!0,messages:e}),signal:s});if(!o.ok){let p=await o.text();throw new Error(`Anthropic API ${o.status}: ${p.slice(0,200)}`)}let l=o.body.getReader(),a=new TextDecoder,c="",h="",u=0,d=0;for(;;){let{done:p,value:f}=await l.read();if(p)break;h+=a.decode(f,{stream:!0});let g=h.split(`
|
|
186
|
+
`);h=g.pop()??"";for(let m of g){if(!m.startsWith("data: "))continue;let x=m.slice(6).trim();if(x!=="[DONE]")try{let T=JSON.parse(x);if(T.type==="message_start"){let I=T.message?.usage;I&&(u=I.input_tokens??0)}else if(T.type==="message_delta"){let I=T.usage;I&&(d=I.output_tokens??0)}else if(T.type==="content_block_delta"&&T.delta?.type==="text_delta"){let I=T.delta.text;c+=I,t(I)}}catch{}}}return{text:c,usage:{inputTokens:u,outputTokens:d,lastInputTokens:u}}}async function qt(n,e,t,s,i,r,o,l){let a=(n.baseUrl??"https://api.anthropic.com").replace(/\/$/,""),c={"Content-Type":"application/json","anthropic-version":"2023-06-01","anthropic-beta":"prompt-caching-2024-07-31"};n.authType==="bearer"?c.Authorization=`Bearer ${n.apiKey}`:c["x-api-key"]=n.apiKey;let h=[...t],u=0,d=0,p=0,f="";for(let g=0;g<10;g++){let m=await fetch(`${a}/v1/messages`,{method:"POST",headers:c,body:JSON.stringify({model:n.model,max_tokens:8192,temperature:n.temperature,system:[{type:"text",text:n.systemPrompt,cache_control:{type:"ephemeral"}}],stream:!0,tools:e,messages:h}),signal:l});if(!m.ok){let P=await m.text();throw new Error(`Anthropic API ${m.status}: ${P.slice(0,200)}`)}let x=m.body.getReader(),T=new TextDecoder,I="",D=0,R=0,v=[],$="",B="",F="",A="";for(;;){let{done:P,value:se}=await x.read();if(P)break;I+=T.decode(se,{stream:!0});let Ke=I.split(`
|
|
187
|
+
`);I=Ke.pop()??"";for(let it of Ke){if(!it.startsWith("data: "))continue;let De=it.slice(6).trim();if(De!=="[DONE]")try{let X=JSON.parse(De);if(X.type==="message_start"){let H=X.message?.usage;H&&(D=H.input_tokens??0)}else if(X.type==="message_delta"){let H=X.usage;H&&(R=H.output_tokens??0),A=X.delta?.stop_reason??A}else if(X.type==="content_block_start"){let H=X.content_block;H?.type==="tool_use"&&($=H.id,B=H.name,F="")}else if(X.type==="content_block_delta"){let H=X.delta;if(H?.type==="text_delta"){let rt=H.text;f+=rt,s(rt);let Dn=v.at(-1);Dn?.type==="text"?Dn.text+=rt:v.push({type:"text",text:rt})}else H?.type==="input_json_delta"&&(F+=H.partial_json??"")}else if(X.type==="content_block_stop"&&$){let H={};try{H=JSON.parse(F)}catch{}v.push({type:"tool_use",id:$,name:B,input:H}),$="",B="",F=""}}catch{}}}u+=D,d+=R,p=D,h.push({role:"assistant",content:v});let b=v.filter(P=>P.type==="tool_use");if(b.length===0||A!=="tool_use")break;let S=300,W=[];for(let P of b){i(P.name,P.input);let se=Date.now(),Ke=o(P.name,P.input),it=Date.now()-se,De=S-it;De>0&&await new Promise(X=>setTimeout(X,De)),r(P.name,P.input,Ke),W.push({type:"tool_result",tool_use_id:P.id,content:Ke})}h.push({role:"user",content:W})}return{text:f,usage:{inputTokens:u,outputTokens:d,lastInputTokens:p}}}var kr=`\u4F60\u5728\u89C2\u5BDF engineer \u4E0E genius \u7684\u5B8C\u6574\u4EA4\u4E92\u8BB0\u5F55\u3002\u4F60\u7684\u4EFB\u52A1\u662F\u4E3A\u7528\u6237\u751F\u6210\u4E00\u4EFD\u6E05\u6670\u7684 Markdown \u603B\u7ED3\u6587\u6863\u3002
|
|
188
|
+
|
|
189
|
+
\u8F93\u51FA\u8981\u6C42\uFF1A
|
|
190
|
+
- \u7B2C\u4E00\u884C\u5FC5\u987B\u662F\uFF1A# {YYYY-MM-DD} {\u4E3B\u9898slug}
|
|
191
|
+
\u5176\u4E2D YYYY-MM-DD \u4E3A\u5B9E\u9645\u65E5\u671F\u5360\u4F4D\uFF08\u7531\u8C03\u7528\u65B9\u66FF\u6362\uFF09\uFF0C\u4E3B\u9898 slug \u4E3A 2-4 \u4E2A\u82F1\u6587\u8BCD\u8FDE\u5B57\u7B26\u683C\u5F0F\uFF0C\u63CF\u8FF0\u672C\u6B21\u8BA8\u8BBA\u7684\u6838\u5FC3\u8BDD\u9898
|
|
192
|
+
- \u540E\u7EED\u4E3A\u6807\u51C6 Markdown\uFF0C\u5305\u542B\u4EE5\u4E0B\u51E0\u8282\uFF1A
|
|
193
|
+
## \u539F\u59CB\u95EE\u9898
|
|
194
|
+
## Engineer \u65B9\u6848\u6F14\u53D8
|
|
195
|
+
## Genius \u5DE7\u601D\u4E0E\u8D28\u7591
|
|
196
|
+
## Judge \u5173\u952E\u53CD\u95EE
|
|
197
|
+
- \u4E0D\u8981\u8F93\u51FA JSON\uFF0C\u4E0D\u8981\u8F93\u51FA\u4EE3\u7801\u5757\u5305\u88F9\u7684 JSON`;function Yn(n){return{...n,systemPrompt:kr}}function Xn(n){let e=[`\u4EE5\u4E0B\u662F\u672C\u6B21 engineer / genius \u7684\u5B8C\u6574\u4EA4\u4E92\u8BB0\u5F55\uFF0C\u8BF7\u751F\u6210\u603B\u7ED3\u6587\u6863\u3002
|
|
198
|
+
`];for(let t of n.rounds)e.push(`--- Round ${t.id} ---`),e.push(`\u7528\u6237\u63D0\u95EE\uFF1A${t.userToEngineer}`),e.push(`
|
|
199
|
+
engineer \u56DE\u590D\uFF1A
|
|
200
|
+
${t.engineerResponse}`),t.geniusResponse&&e.push(`
|
|
201
|
+
genius \u5DE7\u601D\uFF1A
|
|
202
|
+
${t.geniusResponse}`);return n.pending?.engineerResponse&&(e.push(`--- Round ${n.pending.id??"?"}\uFF08\u8FDB\u884C\u4E2D\uFF09---`),e.push(`\u7528\u6237\u63D0\u95EE\uFF1A${n.pending.userToEngineer}`),e.push(`
|
|
203
|
+
engineer \u56DE\u590D\uFF1A
|
|
204
|
+
${n.pending.engineerResponse}`),n.pending.geniusResponse&&e.push(`
|
|
205
|
+
genius \u5DE7\u601D\uFF1A
|
|
206
|
+
${n.pending.geniusResponse}`)),[{role:"user",content:e.join(`
|
|
207
|
+
`)}]}function Qn(n,e,t=[]){let s=[];n.compactSummary&&(s.push({role:"user",content:`[\u5386\u53F2\u5BF9\u8BDD\u6458\u8981]
|
|
208
|
+
${n.compactSummary}`}),s.push({role:"assistant",content:"\u5DF2\u4E86\u89E3\u5386\u53F2\u6458\u8981\u3002"}));for(let i of n.rounds)s.push({role:"user",content:i.userToEngineer}),s.push({role:"assistant",content:i.engineerResponse});if(s.length>=2){let i=s.length-1,r=s[i];r&&typeof r.content=="string"&&(s[i]={role:"assistant",content:[{type:"text",text:r.content,cache_control:{type:"ephemeral"}}]})}return s.push({role:"user",content:Zn(e,t)}),s}function Jn(n,e,t=[]){let s=[];for(let l of n.rounds){let a=l.keyClaims.length>0?l.keyClaims.map((c,h)=>`${h+1}. ${c}`).join(`
|
|
209
|
+
`):"\uFF08\u65E0\u63D0\u53D6\u5230\u7684\u6838\u5FC3\u4E3B\u5F20\uFF09";s.push({role:"user",content:`Round ${l.id} engineer \u6838\u5FC3\u4E3B\u5F20\uFF1A
|
|
210
|
+
${a}`}),l.geniusResponse&&s.push({role:"assistant",content:l.geniusResponse})}let i=s.findLastIndex(l=>l.role==="assistant");if(i>=0){let l=s[i];l&&typeof l.content=="string"&&(s[i]={role:"assistant",content:[{type:"text",text:l.content,cache_control:{type:"ephemeral"}}]})}let r=n.pending?.engineerResponse??"",o=r?`\u4EE5\u4E0B\u662F engineer \u6700\u65B0\u7684\u5B8C\u6574\u56DE\u590D\uFF0C\u8BF7\u8D28\u7591\u5E76\u7ED9\u51FA\u5DE7\u601D\uFF1A
|
|
211
|
+
|
|
212
|
+
${r}
|
|
213
|
+
|
|
214
|
+
\u7528\u6237\u8FFD\u95EE\uFF1A${e}`:e;return s.push({role:"user",content:Zn(o,t)}),s}function Zn(n,e){return e.length===0?n:[{type:"text",text:n},...e]}function es(n){let e=[];for(let r of n.rounds){let o=r.keyClaims.length>0?r.keyClaims.join("\uFF1B"):"\uFF08\u65E0\u63D0\u53D6\uFF09",l=`Round ${r.id}:
|
|
215
|
+
engineer \u6838\u5FC3\u4E3B\u5F20\uFF1A${o}`;r.geniusResponse&&(l+=`
|
|
216
|
+
genius \u5DE7\u601D\uFF1A${r.geniusResponse.slice(0,300)}`),e.push(l)}let t=n.rounds.slice(-2),s=[];for(let r of t)s.push(`--- Round ${r.id} \u539F\u6587 ---
|
|
217
|
+
\u7528\u6237\u63D0\u95EE\uFF1A${r.userToEngineer}
|
|
218
|
+
|
|
219
|
+
engineer \u56DE\u590D\uFF1A${r.engineerResponse}`),r.geniusResponse&&s.push(`genius \u5DE7\u601D\uFF1A${r.geniusResponse}`);return n.pending?.engineerResponse&&(s.push(`--- \u5F53\u524D\u8FDB\u884C\u4E2D Round ${n.pending.id} ---
|
|
220
|
+
\u7528\u6237\u63D0\u95EE\uFF1A${n.pending.userToEngineer}
|
|
221
|
+
|
|
222
|
+
engineer \u56DE\u590D\uFF1A${n.pending.engineerResponse}`),n.pending.geniusResponse&&s.push(`genius \u5DE7\u601D\uFF1A${n.pending.geniusResponse}`)),[{role:"user",content:["=== Round Digest\uFF08\u6240\u6709\u8F6E\u6B21\u6458\u8981\uFF09===",e.join(`
|
|
223
|
+
|
|
224
|
+
`)||"\uFF08\u6682\u65E0\u5B8C\u6574\u8F6E\u6B21\uFF09","","=== \u6700\u8FD1\u8F6E\u6B21\u539F\u6587 ===",s.join(`
|
|
225
|
+
|
|
226
|
+
`)||"\uFF08\u6682\u65E0\u539F\u6587\uFF09","","\u8BF7\u6839\u636E\u4EE5\u4E0A\u5185\u5BB9\uFF0C\u4F5C\u4E3A\u7EC4\u4F1A\u5BFC\u5E08\u89C2\u5BDF engineer \u2194 genius \u7684\u8BA8\u8BBA\uFF0C\u6307\u51FA\u5F53\u4E0B\u6700\u503C\u5F97\u53CC\u65B9\u6DF1\u6316\u7684\u5F00\u653E\u95EE\u9898\uFF0C\u5E76\u5BF9\u5408\u9002\u7684\u4E00\u65B9\u63D0\u51FA\u4E00\u4E2A\u53CD\u95EE\u3002"].join(`
|
|
227
|
+
`)}]}import{spawn as Cr}from"node:child_process";async function ts(n){let e=[],t=process.platform;t==="darwin"?e.push({cmd:"pbcopy",args:[]}):t==="win32"?e.push({cmd:"clip",args:[]}):(e.push({cmd:"xclip",args:["-selection","clipboard"]}),e.push({cmd:"xsel",args:["--clipboard","--input"]}),e.push({cmd:"wl-copy",args:[]}));for(let{cmd:s,args:i}of e)if(await new Promise(o=>{try{let l=Cr(s,i,{stdio:["pipe","ignore","ignore"]});l.on("error",()=>o(!1)),l.on("close",a=>o(a===0)),l.stdin.on("error",()=>o(!1)),l.stdin.end(n)}catch{o(!1)}}))return!0;return!1}import{execFile as Sr}from"node:child_process";import{randomBytes as wr}from"node:crypto";import{readFileSync as Tr,unlinkSync as Ir}from"node:fs";import{tmpdir as $r}from"node:os";import{join as Lr}from"node:path";var Rr=5*1024*1024;function ns(){return process.platform==="darwin"}async function ss(){if(!ns())return!1;try{let{stdout:n,code:e}=await rs(["-e","the clipboard as \xABclass PNGf\xBB"]);return e!==0?!1:n.trim().length>0}catch{return!1}}async function is(n=Rr){if(!ns())return{ok:!1,error:"NO_IMAGE"};let e=`cc-agents-clip-${process.pid}-${wr(4).toString("hex")}.png`,t=Lr($r(),e),s=["set png_data to (the clipboard as \xABclass PNGf\xBB)",`set fp to open for access POSIX file "${t}" with write permission`,"set eof of fp to 0","write png_data to fp","close access fp"].join(`
|
|
228
|
+
`),{code:i}=await rs(["-e",s]);if(i!==0)return{ok:!1,error:"OSASCRIPT_FAILED"};let r;try{r=Tr(t)}catch{return{ok:!1,error:"OSASCRIPT_FAILED"}}finally{try{Ir(t)}catch{}}return r.length>n?{ok:!1,error:"TOO_LARGE"}:{ok:!0,base64:r.toString("base64"),bytes:r.length}}function rs(n){return new Promise(e=>{Sr("osascript",n,{timeout:5e3},(t,s)=>{if(t&&"code"in t&&typeof t.code=="number"){e({stdout:s??"",code:t.code});return}if(t){e({stdout:"",code:1});return}e({stdout:s??"",code:0})})})}var Pr=["engineer","genius","judge","clear","summarize","help","skills","resume"],Ar=["engineer","genius","judge"],Mr=["engineer","genius","judge","all"],Er=["engineer","genius","judge","all"];function os(n){let e=n.trim();for(let t of Pr){if(e===`/${t}`)return{kind:t,content:""};if(e.startsWith(`/${t} `))return{kind:t,content:e.slice(t.length+2).trim()}}if(e.startsWith("/hide ")){let t=e.slice(6).trim();if(Ar.includes(t))return{kind:"hide",content:t}}if(e.startsWith("/show ")){let t=e.slice(6).trim();if(Mr.includes(t))return{kind:"show",content:t}}if(e==="/copy"||e.startsWith("/copy ")){let t=e==="/copy"?"all":e.slice(6).trim();if(Er.includes(t))return{kind:"copy",content:t}}return{kind:"text",content:e}}var Or=.75,as=2,_r="\u4F60\u662F\u4E00\u4E2A\u6280\u672F\u5BF9\u8BDD\u538B\u7F29\u5668\u3002\u5C06\u591A\u8F6E\u5DE5\u7A0B\u8BA8\u8BBA\u538B\u7F29\u4E3A\u7B80\u6D01\u4F46\u5B8C\u6574\u7684 Markdown \u6458\u8981\uFF0C\u4FDD\u7559\u6240\u6709\u51B3\u7B56\u3001\u4EE3\u7801\u7247\u6BB5\u3001\u7ED3\u8BBA\u548C\u5F85\u89E3\u95EE\u9898\u3002\u4E0D\u8981\u8F93\u51FA\u5206\u6790\u8FC7\u7A0B\uFF0C\u76F4\u63A5\u8F93\u51FA\u6458\u8981\u6B63\u6587\u3002";function Br(n,e){let t=n.rounds.slice(0,e),s=[`\u8BF7\u5C06\u4EE5\u4E0B\u5DE5\u7A0B\u5BF9\u8BDD\u8F6E\u6B21\u538B\u7F29\u4E3A\u7ED3\u6784\u5316\u6458\u8981\u3002\u4FDD\u7559\uFF1A\u7528\u6237\u76EE\u6807\u3001\u6280\u672F\u51B3\u7B56\u548C\u7406\u7531\u3001\u91CD\u8981\u4EE3\u7801/\u6587\u4EF6\u5F15\u7528\u3001\u8FBE\u6210\u7684\u7ED3\u8BBA\u3001\u5C1A\u672A\u89E3\u51B3\u7684\u95EE\u9898\u3002
|
|
229
|
+
`];for(let i of t)s.push(`## Round ${i.id}`),s.push(`**\u7528\u6237\uFF1A** ${i.userToEngineer}`),s.push(`**Engineer\uFF1A** ${i.engineerResponse.slice(0,3e3)}${i.engineerResponse.length>3e3?"\u2026\uFF08\u622A\u65AD\uFF09":""}`),i.geniusResponse&&s.push(`**Genius\uFF1A** ${i.geniusResponse.slice(0,1e3)}${i.geniusResponse.length>1e3?"\u2026\uFF08\u622A\u65AD\uFF09":""}`);return n.compactSummary&&s.unshift(`\u4EE5\u4E0B\u662F\u66F4\u65E9\u7684\u5386\u53F2\u6458\u8981\uFF08\u5DF2\u538B\u7F29\uFF09\uFF1A
|
|
230
|
+
|
|
231
|
+
${n.compactSummary}
|
|
232
|
+
|
|
233
|
+
---
|
|
234
|
+
|
|
235
|
+
\u4EE5\u4E0B\u662F\u65B0\u7684\u5F85\u538B\u7F29\u8F6E\u6B21\uFF1A
|
|
236
|
+
`),s.join(`
|
|
237
|
+
`)}function ls(n,e){return n>e*Or}async function cs(n,e,t){let s=n.rounds.length;if(s<=as)return{compacted:0,kept:s};let i=s-as,o=[{role:"user",content:Br(n,i)}],l={...e,systemPrompt:_r,temperature:.2},a="";return await We(l,o,c=>{a+=c,t(c)}),n.compactSummary=a,n.rounds=n.rounds.slice(i),{compacted:i,kept:n.rounds.length}}function us(n){let e=n.match(/(?:^|\n)#{1,3}\s*理由[::]\s*\n([\s\S]*?)(?=\n#|\n\*\*|$)/i)??n.match(/\*\*理由\*\*[::]\s*([\s\S]*?)(?=\n\*\*|$)/i);return e?e[1].split(`
|
|
238
|
+
`).map(t=>t.replace(/^[-*\d.]\s*/,"").trim()).filter(t=>t.length>0).slice(0,3):[]}function hs(n){let e=n.match(/\{[\s\S]*\}/);if(e)try{let t=JSON.parse(e[0]);if(typeof t.analysis=="string")return{analysis:t.analysis,verdict:typeof t.verdict=="string"?t.verdict:"",next:t.next&&typeof t.next.target=="string"?t.next:void 0}}catch{}return{analysis:n,verdict:""}}import{existsSync as ct,readdirSync as fs,readFileSync as ut}from"node:fs";import{join as Se}from"node:path";function gs(n){if(!ct(n))return[];let e=[];try{let t=fs(n,{withFileTypes:!0});for(let s of t){if(!s.isDirectory())continue;let i=Se(n,s.name,"SKILL.md");if(ct(i))try{let r=ut(i,"utf-8"),o=ds(r);if(!o)continue;let l=ps(o);if(!l)continue;e.push({name:s.name,description:l,filePath:i})}catch{}}for(let s of t){if(s.isDirectory()||!s.name.endsWith(".md"))continue;let i=Se(n,s.name);try{let r=ut(i,"utf-8"),o=ds(r);if(!o)continue;let l=ps(o);if(!l)continue;let a=Kr(o)??s.name.replace(/\.md$/,"");e.push({name:a,description:l,filePath:i})}catch{}}}catch{}return e}function ds(n){let e=n.match(/^---\s*\n([\s\S]*?)\n---/);return e?e[1]:null}function ps(n){let e=n.split(`
|
|
239
|
+
`),t=0;for(;t<e.length;){let s=e[t].match(/^description:\s*(.*)/);if(!s){t++;continue}let i=s[1].trim();if(i===">"||i==="|"||i===">-"||i==="|-"){let r=[];for(t++;t<e.length&&(e[t].startsWith(" ")||e[t].startsWith(" "));)r.push(e[t].trim()),t++;return r.filter(Boolean).join(" ")}return i||null}return null}function Kr(n){let e=n.match(/^name:\s*(.+)$/m);return e?e[1].trim():null}function Dr(n){if(n.length===0)return"";let e=["The following skills provide specialized instructions for specific tasks.","When a task matches a skill's description, read the skill file first.","","<available_skills>"];for(let t of n)e.push(" <skill>"),e.push(` <name>${t.name}</name>`),e.push(` <description>${t.description}</description>`),e.push(` <location>${t.filePath}</location>`),e.push(" </skill>");return e.push("</available_skills>"),e.join(`
|
|
240
|
+
`)}function Wr(){let n=new Date,e=n.getFullYear(),t=String(n.getMonth()+1).padStart(2,"0"),s=String(n.getDate()).padStart(2,"0");return`${e}-${t}-${s}`}function ms(n){let e=["=== Project Context ==="];e.push(`Current date: ${Wr()}`),e.push(`Working directory: ${n}`);let t=Se(n,"package.json");if(ct(t))try{let i=JSON.parse(ut(t,"utf-8")),r=typeof i.name=="string"?i.name:"",o=typeof i.description=="string"?i.description:"";r&&e.push(`Project: ${r}${o?` \u2014 ${o}`:""}`)}catch{}let s=Se(n,"AGENTS.md");if(ct(s))try{let i=ut(s,"utf-8");e.push(`
|
|
241
|
+
--- AGENTS.md ---
|
|
242
|
+
${i.trim()}`)}catch{}try{let r=fs(n,{withFileTypes:!0}).filter(o=>!o.name.startsWith(".")&&o.name!=="node_modules").map(o=>o.isDirectory()?`${o.name}/`:o.name).join(" ");e.push(`
|
|
243
|
+
--- Project root ---
|
|
244
|
+
${r}`)}catch{}return e.push(`=== End Project Context ===
|
|
245
|
+
`),e.join(`
|
|
246
|
+
`)}function bs(n){let e=Se(n,".cc-agents","skills"),t=gs(e);return Dr(t)}function xs(n){return gs(Se(n,".cc-agents","skills"))}function ys(){return{rounds:[],compactSummary:void 0}}function vs(n,e){n.pending?.engineerResponse&&n.rounds.push(n.pending);let t=n.rounds.length+1;n.pending={id:t,userToEngineer:e,keyClaims:[]}}function ks(n,e){n.pending&&(n.pending.engineerResponse=e)}function Cs(n,e){n.pending&&(n.pending.keyClaims=e)}function Ss(n,e,t){n.pending&&(n.pending.geniusPrompt=e,n.pending.geniusResponse=t)}function ws(n){n.rounds=[],n.pending=void 0}import{execSync as Ne}from"node:child_process";import{existsSync as Ht,mkdirSync as Nr,readdirSync as Fr,readFileSync as $s,writeFileSync as Ts}from"node:fs";import{dirname as jr,isAbsolute as we,join as Te}from"node:path";var Ls=[{name:"read_file",description:"Read a file. Supports offset (1-indexed start line) and limit (max lines to read) for large files.",input_schema:{type:"object",properties:{path:{type:"string",description:"File path (relative to project root, or absolute)"},offset:{type:"number",description:"Line number to start reading from (1-indexed, optional)"},limit:{type:"number",description:"Maximum number of lines to read (optional)"}},required:["path"]}},{name:"list_dir",description:"List files and directories at a path.",input_schema:{type:"object",properties:{path:{type:"string",description:"Directory path (relative to project root, or absolute)"}},required:["path"]}},{name:"grep",description:"Search for a pattern in files using ripgrep (rg) or grep. Prefer this over bash for code searches.",input_schema:{type:"object",properties:{pattern:{type:"string",description:"Search pattern (regex)"},path:{type:"string",description:"Directory or file to search (relative to project root, or absolute). Default: project root"},glob:{type:"string",description:"Filter by glob pattern, e.g. '*.ts' (optional)"},ignore_case:{type:"boolean",description:"Case-insensitive search (default: false)"},literal:{type:"boolean",description:"Treat pattern as literal string, not regex (default: false)"},context:{type:"number",description:"Lines of context before/after each match (default: 0)"},limit:{type:"number",description:"Max matches to return (default: 50)"}},required:["pattern"]}},{name:"find",description:"Find files or directories matching a name pattern.",input_schema:{type:"object",properties:{path:{type:"string",description:"Directory to search (relative to project root, or absolute). Default: project root"},pattern:{type:"string",description:"Name pattern (glob), e.g. '*.ts' or 'AGENTS.md'"},type:{type:"string",description:"Entry type: 'f' (files), 'd' (dirs), or omit for both"}},required:["pattern"]}}],qr=[{name:"write_file",description:"Write content to a file, creating it (and any missing parent directories) if needed.",input_schema:{type:"object",properties:{path:{type:"string",description:"File path (relative to project root, or absolute)"},content:{type:"string",description:"Full content to write"}},required:["path","content"]}},{name:"edit_file",description:"Edit a file by replacing an exact string. The old_string must appear exactly once in the file.",input_schema:{type:"object",properties:{path:{type:"string",description:"File path (relative to project root, or absolute)"},old_string:{type:"string",description:"Exact text to find (must be unique in the file)"},new_string:{type:"string",description:"Text to replace it with"}},required:["path","old_string","new_string"]}}],Hr={name:"bash",description:"Run a shell command. Output truncated at 4000 chars. Use grep/find tools for searches instead. Delete operations (rm, rmdir, unlink, shred) are blocked.",input_schema:{type:"object",properties:{command:{type:"string",description:"Shell command to execute"}},required:["command"]}},Rs=[...Ls,...qr,Hr],Ps=[...Ls],Is=50*1024;function Ur(n,e,t){let i=$s(n,"utf-8").split(`
|
|
247
|
+
`),r=i.length,o=e!==void 0?Math.max(0,e-1):0,l=t!==void 0?i.slice(o,o+t):i.slice(o),a=l.join(`
|
|
248
|
+
`),c=Buffer.byteLength(a,"utf-8"),h=!1;if(c>Is){let p=Buffer.from(a,"utf-8").slice(0,Is),f=p.length;for(;f>0&&p[f-1]!==10;)f--;a=p.slice(0,f>0?f:p.length).toString("utf-8"),h=!0}let u=o+l.length,d=`[Lines ${o+1}\u2013${Math.min(u,r)} of ${r}]`;return h?`${d}
|
|
249
|
+
${a}
|
|
250
|
+
\u2026 (truncated at 50KB)`:`${d}
|
|
251
|
+
${a}`}function Ut(n,e,t){try{if(n==="read_file"){let s=String(e.path??""),i=we(s)?s:Te(t,s);if(!Ht(i))return`Error: file not found: ${s}`;let r=typeof e.offset=="number"?e.offset:void 0,o=typeof e.limit=="number"?e.limit:void 0;return Ur(i,r,o)}if(n==="list_dir"){let s=String(e.path??"."),i=we(s)?s:Te(t,s);return Ht(i)?Fr(i,{withFileTypes:!0}).map(o=>o.isDirectory()?`${o.name}/`:o.name).join(`
|
|
252
|
+
`):`Error: directory not found: ${s}`}if(n==="grep"){let s=String(e.pattern??""),i=e.path?we(String(e.path))?String(e.path):Te(t,String(e.path)):t,r=typeof e.limit=="number"?e.limit:50;if((()=>{try{return Ne("which rg",{stdio:"ignore"}),!0}catch{return!1}})()){let d=`rg ${[e.ignore_case?"-i":"",e.literal?"-F":"",e.glob?`--glob '${String(e.glob)}'`:"",typeof e.context=="number"?`-C ${e.context}`:"",`-m ${r}`,"--no-heading","--line-number","--color never"].filter(Boolean).join(" ")} '${s.replace(/'/g,"'\\''")}' '${i}'`;return Ne(d,{cwd:t,timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","ignore"]}).slice(0,8e3)||"(no matches)"}let l=["-rn",e.ignore_case?"-i":"",e.literal?"-F":""].filter(Boolean).join(" "),a=e.glob?`--include='${String(e.glob)}'`:"",c=`grep ${l} ${a} '${s.replace(/'/g,"'\\''")}' '${i}' | head -${r}`;return Ne(c,{cwd:t,timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","ignore"]}).slice(0,8e3)||"(no matches)"}if(n==="find"){let s=e.path?we(String(e.path))?String(e.path):Te(t,String(e.path)):t,i=String(e.pattern??"*"),r=e.type==="f"?"-type f":e.type==="d"?"-type d":"",o=`find '${s}' -not -path '*/node_modules/*' -not -path '*/.git/*' ${r} -name '${i}' | head -100`;return Ne(o,{cwd:t,timeout:1e4,encoding:"utf-8"}).trim()||"(no results)"}if(n==="write_file"){let s=String(e.path??""),i=we(s)?s:Te(t,s),r=String(e.content??"");return Nr(jr(i),{recursive:!0}),Ts(i,r,"utf-8"),`\u5DF2\u5199\u5165 ${s} (${r.length} \u5B57\u7B26)`}if(n==="edit_file"){let s=String(e.path??""),i=we(s)?s:Te(t,s);if(!Ht(i))return`Error: file not found: ${s}`;let r=String(e.old_string??""),o=String(e.new_string??""),l=$s(i,"utf-8"),a=l.split(r).length-1;return a===0?"Error: old_string \u5728\u6587\u4EF6\u4E2D\u672A\u627E\u5230":a>1?`Error: old_string \u5728\u6587\u4EF6\u4E2D\u51FA\u73B0\u4E86 ${a} \u6B21\uFF0C\u5FC5\u987B\u552F\u4E00`:(Ts(i,l.replace(r,o),"utf-8"),`\u5DF2\u7F16\u8F91 ${s}`)}if(n==="bash"){let s=String(e.command??"");if(/(?:^|[|&;`\n(])\s*(rm|rmdir|unlink|shred)\b/.test(s))return"Error: \u5220\u9664\u64CD\u4F5C\u5DF2\u88AB\u7981\u6B62 (rm / rmdir / unlink / shred)";let i=Ne(s,{cwd:t,timeout:15e3,encoding:"utf-8"});return i.length>4e3?`${i.slice(0,4e3)}
|
|
253
|
+
\u2026 (truncated)`:i}return`Error: unknown tool "${n}"`}catch(s){return`Error: ${s instanceof Error?s.message:String(s)}`}}var zt=null,Es={widthPx:9,heightPx:18};function ht(){return Es}function Vt(n){Es=n}function Os(){let n=process.env.TERM_PROGRAM?.toLowerCase()||"",e=process.env.TERMINAL_EMULATOR?.toLowerCase()||"",t=process.env.TERM?.toLowerCase()||"",s=process.env.COLORTERM?.toLowerCase()||"",i=s==="truecolor"||s==="24bit";return!!process.env.TMUX||t.startsWith("tmux")||t.startsWith("screen")?{images:null,trueColor:i,hyperlinks:!1}:process.env.KITTY_WINDOW_ID||n==="kitty"?{images:"kitty",trueColor:!0,hyperlinks:!0}:n==="ghostty"||t.includes("ghostty")||process.env.GHOSTTY_RESOURCES_DIR?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.WEZTERM_PANE||n==="wezterm"?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.ITERM_SESSION_ID||n==="iterm.app"?{images:"iterm2",trueColor:!0,hyperlinks:!0}:process.env.WT_SESSION?{images:null,trueColor:!0,hyperlinks:!0}:n==="vscode"?{images:null,trueColor:!0,hyperlinks:!0}:n==="alacritty"?{images:null,trueColor:!0,hyperlinks:!0}:e==="jetbrains-jediterm"?{images:null,trueColor:!0,hyperlinks:!1}:{images:null,trueColor:i,hyperlinks:!1}}function ue(){return zt||(zt=Os()),zt}var As="\x1B_G",Ms="\x1B]1337;File=";function be(n){return n.startsWith(As)||n.startsWith(Ms)?!0:n.includes(As)||n.includes(Ms)}function Gt(){return Math.floor(Math.random()*4294967294)+1}function _s(n,e={}){let s=["a=T","f=100","q=2"];if(e.moveCursor===!1&&s.push("C=1"),e.columns&&s.push(`c=${e.columns}`),e.rows&&s.push(`r=${e.rows}`),e.imageId&&s.push(`i=${e.imageId}`),n.length<=4096)return`\x1B_G${s.join(",")};${n}\x1B\\`;let i=[],r=0,o=!0;for(;r<n.length;){let l=n.slice(r,r+4096),a=r+4096>=n.length;o?(i.push(`\x1B_G${s.join(",")},m=1;${l}\x1B\\`),o=!1):a?i.push(`\x1B_Gm=0;${l}\x1B\\`):i.push(`\x1B_Gm=1;${l}\x1B\\`),r+=4096}return i.join("")}function Yt(n){return`\x1B_Ga=d,d=I,i=${n},q=2\x1B\\`}function Bs(n,e={}){let t=[`inline=${e.inline!==!1?1:0}`];if(e.width!==void 0&&t.push(`width=${e.width}`),e.height!==void 0&&t.push(`height=${e.height}`),e.name){let s=Buffer.from(e.name).toString("base64");t.push(`name=${s}`)}return e.preserveAspectRatio===!1&&t.push("preserveAspectRatio=0"),`\x1B]1337;File=${t.join(";")}:${n}\x07`}function zr(n,e,t,s={widthPx:9,heightPx:18}){let i=Math.max(1,Math.floor(e)),r=t===void 0?void 0:Math.max(1,Math.floor(t)),o=Math.max(1,n.widthPx),l=Math.max(1,n.heightPx),a=i*s.widthPx/o,c=r===void 0?a:r*s.heightPx/l,h=Math.min(a,c),u=o*h,d=l*h,p=Math.ceil(u/s.widthPx),f=Math.ceil(d/s.heightPx);return{columns:Math.max(1,Math.min(i,p)),rows:Math.max(1,r===void 0?f:Math.min(r,f))}}function Ks(n){try{let e=Buffer.from(n,"base64");if(e.length<24||e[0]!==137||e[1]!==80||e[2]!==78||e[3]!==71)return null;let t=e.readUInt32BE(16),s=e.readUInt32BE(20);return{widthPx:t,heightPx:s}}catch{return null}}function Ds(n){try{let e=Buffer.from(n,"base64");if(e.length<2||e[0]!==255||e[1]!==216)return null;let t=2;for(;t<e.length-9;){if(e[t]!==255){t++;continue}let s=e[t+1];if(s>=192&&s<=194){let r=e.readUInt16BE(t+5);return{widthPx:e.readUInt16BE(t+7),heightPx:r}}if(t+3>=e.length)return null;let i=e.readUInt16BE(t+2);if(i<2)return null;t+=2+i}return null}catch{return null}}function Ws(n){try{let e=Buffer.from(n,"base64");if(e.length<10)return null;let t=e.slice(0,6).toString("ascii");if(t!=="GIF87a"&&t!=="GIF89a")return null;let s=e.readUInt16LE(6),i=e.readUInt16LE(8);return{widthPx:s,heightPx:i}}catch{return null}}function Ns(n){try{let e=Buffer.from(n,"base64");if(e.length<30)return null;let t=e.slice(0,4).toString("ascii"),s=e.slice(8,12).toString("ascii");if(t!=="RIFF"||s!=="WEBP")return null;let i=e.slice(12,16).toString("ascii");if(i==="VP8 "){if(e.length<30)return null;let r=e.readUInt16LE(26)&16383,o=e.readUInt16LE(28)&16383;return{widthPx:r,heightPx:o}}else if(i==="VP8L"){if(e.length<25)return null;let r=e.readUInt32LE(21),o=(r&16383)+1,l=(r>>14&16383)+1;return{widthPx:o,heightPx:l}}else if(i==="VP8X"){if(e.length<30)return null;let r=(e[24]|e[25]<<8|e[26]<<16)+1,o=(e[27]|e[28]<<8|e[29]<<16)+1;return{widthPx:r,heightPx:o}}return null}catch{return null}}function Fe(n,e){return e==="image/png"?Ks(n):e==="image/jpeg"?Ds(n):e==="image/gif"?Ws(n):e==="image/webp"?Ns(n):null}function Xt(n,e,t={}){let s=ue();if(!s.images)return null;let i=t.maxWidthCells??80,r=zr(e,i,t.maxHeightCells,ht());return s.images==="kitty"?{sequence:_s(n,{columns:r.columns,rows:r.rows,imageId:t.imageId,moveCursor:t.moveCursor}),rows:r.rows,imageId:t.imageId}:s.images==="iterm2"?{sequence:Bs(n,{width:r.columns,height:"auto",preserveAspectRatio:t.preserveAspectRatio??!0}),rows:r.rows}:null}function Qt(n,e){return`\x1B]8;;${e}\x1B\\${n}\x1B]8;;\x1B\\`}function dt(n,e,t){let s=[];return t&&s.push(t),s.push(`[${n}]`),e&&s.push(`${e.widthPx}x${e.heightPx}`),`[Image: ${s.join(" ")}]`}var je=class{constructor(e,t,s,i={},r){this.base64Data=e,this.mimeType=t,this.theme=s,this.options=i,this.dimensions=r||Fe(e,t)||{widthPx:800,heightPx:600},this.imageId=i.imageId}getImageId(){return this.imageId}invalidate(){this.cachedLines=void 0,this.cachedWidth=void 0}render(e){if(this.cachedLines&&this.cachedWidth===e)return this.cachedLines;let t=Math.max(1,Math.min(e-2,this.options.maxWidthCells??60)),s=ht(),i=Math.max(1,Math.ceil(t*s.widthPx/s.heightPx)),r=this.options.maxHeightCells??i,o=ue(),l;if(o.images){o.images==="kitty"&&this.imageId===void 0&&(this.imageId=Gt());let a=Xt(this.base64Data,this.dimensions,{maxWidthCells:t,maxHeightCells:r,imageId:this.imageId,moveCursor:!1});if(a)if(a.imageId&&(this.imageId=a.imageId),o.images==="kitty"){l=[a.sequence];for(let c=0;c<a.rows-1;c++)l.push("")}else{l=[];for(let u=0;u<a.rows-1;u++)l.push("");let c=a.rows-1,h=c>0?`\x1B[${c}A`:"";l.push(h+a.sequence)}else{let c=dt(this.mimeType,this.dimensions,this.options.filename);l=[this.theme.fallbackColor(c)]}}else{let a=dt(this.mimeType,this.dimensions,this.options.filename);l=[this.theme.fallbackColor(a)]}return this.cachedLines=l,this.cachedWidth=e,l}};var Fs="\x1B[2m",js="\x1B[0m",Vr=32,Gr=8,Yr={fallbackColor:n=>`${Fs}${n}${js}`},pt=class{constructor(e){this.imageCache=new Map;this.store=e}invalidate(){this.cachedLines=void 0,this.cachedWidth=void 0,this.cachedSnapshotKey=void 0;for(let e of this.imageCache.values())e.invalidate()}rowCount(){return this.cachedLines?.length??0}render(e){let t=this.store.snapshot(),s=t.map(o=>`${o.id}:${o.bytes}`).join("|");if(this.cachedLines&&this.cachedWidth===e&&this.cachedSnapshotKey===s)return this.cachedLines;if(t.length===0)return this.imageCache.clear(),this.cachedLines=[],this.cachedWidth=e,this.cachedSnapshotKey=s,this.cachedLines;let i=new Set(t.map(o=>o.id));for(let o of[...this.imageCache.keys()])i.has(o)||this.imageCache.delete(o);let r=[];for(let o of t)r.push(this.headerLine(o)),r.push(...this.imageLines(o,e));return this.cachedLines=r,this.cachedWidth=e,this.cachedSnapshotKey=s,r}headerLine(e){let t=(e.bytes/1024).toFixed(0),s=Fe(e.base64,"image/png"),i=s?`${s.widthPx}\xD7${s.heightPx} `:"";return`${Fs}[Image #${e.id}] ${i}png (${t} KB)${js}`}imageLines(e,t){let s=this.imageCache.get(e.id);return s||(s=new je(e.base64,"image/png",Yr,{maxWidthCells:Vr,maxHeightCells:Gr,filename:`image-${e.id}.png`}),this.imageCache.set(e.id,s)),s.render(t)}};var qs=[161,161,164,164,167,168,170,170,173,174,176,180,182,186,188,191,198,198,208,208,215,216,222,225,230,230,232,234,236,237,240,240,242,243,247,250,252,252,254,254,257,257,273,273,275,275,283,283,294,295,299,299,305,307,312,312,319,322,324,324,328,331,333,333,338,339,358,359,363,363,462,462,464,464,466,466,468,468,470,470,472,472,474,474,476,476,593,593,609,609,708,708,711,711,713,715,717,717,720,720,728,731,733,733,735,735,768,879,913,929,931,937,945,961,963,969,1025,1025,1040,1103,1105,1105,8208,8208,8211,8214,8216,8217,8220,8221,8224,8226,8228,8231,8240,8240,8242,8243,8245,8245,8251,8251,8254,8254,8308,8308,8319,8319,8321,8324,8364,8364,8451,8451,8453,8453,8457,8457,8467,8467,8470,8470,8481,8482,8486,8486,8491,8491,8531,8532,8539,8542,8544,8555,8560,8569,8585,8585,8592,8601,8632,8633,8658,8658,8660,8660,8679,8679,8704,8704,8706,8707,8711,8712,8715,8715,8719,8719,8721,8721,8725,8725,8730,8730,8733,8736,8739,8739,8741,8741,8743,8748,8750,8750,8756,8759,8764,8765,8776,8776,8780,8780,8786,8786,8800,8801,8804,8807,8810,8811,8814,8815,8834,8835,8838,8839,8853,8853,8857,8857,8869,8869,8895,8895,8978,8978,9312,9449,9451,9547,9552,9587,9600,9615,9618,9621,9632,9633,9635,9641,9650,9651,9654,9655,9660,9661,9664,9665,9670,9672,9675,9675,9678,9681,9698,9701,9711,9711,9733,9734,9737,9737,9742,9743,9756,9756,9758,9758,9792,9792,9794,9794,9824,9825,9827,9829,9831,9834,9836,9837,9839,9839,9886,9887,9919,9919,9926,9933,9935,9939,9941,9953,9955,9955,9960,9961,9963,9969,9972,9972,9974,9977,9979,9980,9982,9983,10045,10045,10102,10111,11094,11097,12872,12879,57344,63743,65024,65039,65533,65533,127232,127242,127248,127277,127280,127337,127344,127373,127375,127376,127387,127404,917760,917999,983040,1048573,1048576,1114109],Hs=12288,Us=65510,zs=[12288,12288,65281,65376,65504,65510];var Vs=4352,Gs=262141,Jt=[4352,4447,8986,8987,9001,9002,9193,9196,9200,9200,9203,9203,9725,9726,9748,9749,9776,9783,9800,9811,9855,9855,9866,9871,9875,9875,9889,9889,9898,9899,9917,9918,9924,9925,9934,9934,9940,9940,9962,9962,9970,9971,9973,9973,9978,9978,9981,9981,9989,9989,9994,9995,10024,10024,10060,10060,10062,10062,10067,10069,10071,10071,10133,10135,10160,10160,10175,10175,11035,11036,11088,11088,11093,11093,11904,11929,11931,12019,12032,12245,12272,12287,12289,12350,12353,12438,12441,12543,12549,12591,12593,12686,12688,12773,12783,12830,12832,12871,12880,42124,42128,42182,43360,43388,44032,55203,63744,64255,65040,65049,65072,65106,65108,65126,65128,65131,94176,94180,94192,94198,94208,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,127386,127488,127490,127504,127547,127552,127560,127568,127569,127584,127589,127744,127776,127789,127797,127799,127868,127870,127891,127904,127946,127951,127955,127968,127984,127988,127988,127992,128062,128064,128064,128066,128252,128255,128317,128331,128334,128336,128359,128378,128378,128405,128406,128420,128420,128507,128591,128640,128709,128716,128716,128720,128722,128725,128728,128732,128735,128747,128748,128756,128764,128992,129003,129008,129008,129292,129338,129340,129349,129351,129535,129648,129660,129664,129674,129678,129734,129736,129736,129741,129756,129759,129770,129775,129784,131072,196605,196608,262141];var ft=(n,e)=>{let t=0,s=Math.floor(n.length/2)-1;for(;t<=s;){let i=Math.floor((t+s)/2),r=i*2;if(e<n[r])s=i-1;else if(e>n[r+1])t=i+1;else return!0}return!1};var Ys=19968,[Jr,Zr]=eo(Jt);function eo(n){let e=n[0],t=n[1];for(let s=0;s<n.length;s+=2){let i=n[s],r=n[s+1];if(Ys>=i&&Ys<=r)return[i,r];r-i>t-e&&(e=i,t=r)}return[e,t]}var Xs=n=>n<161||n>1114109?!1:ft(qs,n),Qs=n=>n<Hs||n>Us?!1:ft(zs,n);var Js=n=>n>=Jr&&n<=Zr?!0:n<Vs||n>Gs?!1:ft(Jt,n);function to(n){if(!Number.isSafeInteger(n))throw new TypeError(`Expected a code point, got \`${typeof n}\`.`)}function Zt(n,{ambiguousAsWide:e=!1}={}){return to(n),Qs(n)||Js(n)||e&&Xs(n)?2:1}var ie=new Intl.Segmenter(void 0,{granularity:"grapheme"}),no=new Intl.Segmenter(void 0,{granularity:"word"});function gt(){return ie}function mt(){return no}function so(n){let e=n.codePointAt(0);return e>=126976&&e<=130047||e>=8960&&e<=9215||e>=9728&&e<=10175||e>=11088&&e<=11093||n.includes("\uFE0F")||n.length>2}var io=new RegExp("^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Mark}|\\p{Surrogate})+$","v"),ro=new RegExp("^[\\p{Default_Ignorable_Code_Point}\\p{Control}\\p{Format}\\p{Mark}\\p{Surrogate}]+","v"),oo=new RegExp("^\\p{RGI_Emoji}$","v"),ao=512,qe=new Map;function nn(n){for(let e=0;e<n.length;e++){let t=n.charCodeAt(e);if(t<32||t>126)return!1}return!0}function lo(n,e){if(e<=0||n.length===0)return{text:"",width:0};if(nn(n)){let a=n.slice(0,e);return{text:a,width:a.length}}let t=n.includes("\x1B"),s=n.includes(" ");if(!t&&!s){let a="",c=0;for(let{segment:h}of ie.segment(n)){let u=xe(h);if(c+u>e)break;a+=h,c+=u}return{text:a,width:c}}let i="",r=0,o=0,l="";for(;o<n.length;){let a=V(n,o);if(a){l+=a.code,o+=a.length;continue}if(n[o]===" "){if(r+3>e)break;l&&(i+=l,l=""),i+=" ",r+=3,o++;continue}let c=o;for(;c<n.length&&n[c]!==" "&&!V(n,c);)c++;for(let{segment:h}of ie.segment(n.slice(o,c))){let u=xe(h);if(r+u>e)return{text:i,width:r};l&&(i+=l,l=""),i+=h,r+=u}o=c}return{text:i,width:r}}function en(n,e,t,s,i,r){let o="\x1B[0m",l=e+s,a;return t.length>0?a=`${n}${o}${t}${o}`:a=`${n}${o}`,r?a+" ".repeat(Math.max(0,i-l)):a}function xe(n){if(io.test(n))return 0;if(so(n)&&oo.test(n))return 2;let t=n.replace(ro,"").codePointAt(0);if(t===void 0)return 0;if(t>=127462&&t<=127487)return 2;let s=Zt(t);if(n.length>1)for(let i of n.slice(1)){let r=i.codePointAt(0);r>=65280&&r<=65519?s+=Zt(r):(r===3635||r===3763)&&(s+=1)}return s}function C(n){if(n.length===0)return 0;if(nn(n))return n.length;let e=qe.get(n);if(e!==void 0)return e;let t=n;if(n.includes(" ")&&(t=t.replace(/\t/g," ")),t.includes("\x1B")){let i="",r=0;for(;r<t.length;){let o=V(t,r);if(o){r+=o.length;continue}i+=t[r],r++}t=i}let s=0;for(let{segment:i}of ie.segment(t))s+=xe(i);if(qe.size>=ao){let i=qe.keys().next().value;i!==void 0&&qe.delete(i)}return qe.set(n,s),s}var co=/[\u0e33\u0eb3]/,uo=/[\u0e33\u0eb3]/g;function Zs(n){return co.test(n)?n.replace(uo,e=>e==="\u0E33"?"\u0E4D\u0E32":"\u0ECD\u0EB2"):n}function V(n,e){if(e>=n.length||n[e]!=="\x1B")return null;let t=n[e+1];if(t==="["){let s=e+2;for(;s<n.length&&!/[mGKHJ]/.test(n[s]);)s++;return s<n.length?{code:n.substring(e,s+1),length:s+1-e}:null}if(t==="]"){let s=e+2;for(;s<n.length;){if(n[s]==="\x07")return{code:n.substring(e,s+1),length:s+1-e};if(n[s]==="\x1B"&&n[s+1]==="\\")return{code:n.substring(e,s+2),length:s+2-e};s++}return null}if(t==="_"){let s=e+2;for(;s<n.length;){if(n[s]==="\x07")return{code:n.substring(e,s+1),length:s+1-e};if(n[s]==="\x1B"&&n[s+1]==="\\")return{code:n.substring(e,s+2),length:s+2-e};s++}return null}return null}function ho(n){if(!n.startsWith("\x1B]8;"))return;let e=n.endsWith("\x07")?"\x07":"\x1B\\",t=n.slice(4,e==="\x07"?-1:-2),s=t.indexOf(";");if(s===-1)return;let i=t.slice(0,s),r=t.slice(s+1);return r?{params:i,url:r,terminator:e}:null}function po(n){return`\x1B]8;${n.params};${n.url}${n.terminator}`}function fo(n){return`\x1B]8;;${n}`}var He=class{constructor(){this.bold=!1;this.dim=!1;this.italic=!1;this.underline=!1;this.blink=!1;this.inverse=!1;this.hidden=!1;this.strikethrough=!1;this.fgColor=null;this.bgColor=null;this.activeHyperlink=null}process(e){let t=ho(e);if(t!==void 0){this.activeHyperlink=t;return}if(!e.endsWith("m"))return;let s=e.match(/\x1b\[([\d;]*)m/);if(!s)return;let i=s[1];if(i===""||i==="0"){this.reset();return}let r=i.split(";"),o=0;for(;o<r.length;){let l=Number.parseInt(r[o],10);if(l===38||l===48){if(r[o+1]==="5"&&r[o+2]!==void 0){let a=`${r[o]};${r[o+1]};${r[o+2]}`;l===38?this.fgColor=a:this.bgColor=a,o+=3;continue}else if(r[o+1]==="2"&&r[o+4]!==void 0){let a=`${r[o]};${r[o+1]};${r[o+2]};${r[o+3]};${r[o+4]}`;l===38?this.fgColor=a:this.bgColor=a,o+=5;continue}}switch(l){case 0:this.reset();break;case 1:this.bold=!0;break;case 2:this.dim=!0;break;case 3:this.italic=!0;break;case 4:this.underline=!0;break;case 5:this.blink=!0;break;case 7:this.inverse=!0;break;case 8:this.hidden=!0;break;case 9:this.strikethrough=!0;break;case 21:this.bold=!1;break;case 22:this.bold=!1,this.dim=!1;break;case 23:this.italic=!1;break;case 24:this.underline=!1;break;case 25:this.blink=!1;break;case 27:this.inverse=!1;break;case 28:this.hidden=!1;break;case 29:this.strikethrough=!1;break;case 39:this.fgColor=null;break;case 49:this.bgColor=null;break;default:l>=30&&l<=37||l>=90&&l<=97?this.fgColor=String(l):(l>=40&&l<=47||l>=100&&l<=107)&&(this.bgColor=String(l));break}o++}}reset(){this.bold=!1,this.dim=!1,this.italic=!1,this.underline=!1,this.blink=!1,this.inverse=!1,this.hidden=!1,this.strikethrough=!1,this.fgColor=null,this.bgColor=null}clear(){this.reset(),this.activeHyperlink=null}getActiveCodes(){let e=[];this.bold&&e.push("1"),this.dim&&e.push("2"),this.italic&&e.push("3"),this.underline&&e.push("4"),this.blink&&e.push("5"),this.inverse&&e.push("7"),this.hidden&&e.push("8"),this.strikethrough&&e.push("9"),this.fgColor&&e.push(this.fgColor),this.bgColor&&e.push(this.bgColor);let t=e.length>0?`\x1B[${e.join(";")}m`:"";return this.activeHyperlink&&(t+=po(this.activeHyperlink)),t}hasActiveCodes(){return this.bold||this.dim||this.italic||this.underline||this.blink||this.inverse||this.hidden||this.strikethrough||this.fgColor!==null||this.bgColor!==null||this.activeHyperlink!==null}getLineEndReset(){let e="";return this.underline&&(e+="\x1B[24m"),this.activeHyperlink&&(e+=fo(this.activeHyperlink.terminator)),e}};function ei(n,e){let t=0;for(;t<n.length;){let s=V(n,t);s?(e.process(s.code),t+=s.length):t++}}function go(n){let e=[],t="",s="",i=!1,r=0;for(;r<n.length;){let o=V(n,r);if(o){s+=o.code,r+=o.length;continue}let l=n[r],a=l===" ";a!==i&&t&&(e.push(t),t=""),s&&(t+=s,s=""),i=a,t+=l,r++}return s&&(t+=s),t&&e.push(t),e}function Q(n,e){if(!n)return[""];let t=n.split(`
|
|
254
|
+
`),s=[],i=new He;for(let r of t){let o=s.length>0?i.getActiveCodes():"";s.push(...mo(o+r,e)),ei(r,i)}return s.length>0?s:[""]}function mo(n,e){if(!n)return[""];if(C(n)<=e)return[n];let s=[],i=new He,r=go(n),o="",l=0;for(let a of r){let c=C(a),h=a.trim()==="";if(c>e&&!h){if(o){let p=i.getLineEndReset();p&&(o+=p),s.push(o),o="",l=0}let d=bo(a,e,i);s.push(...d.slice(0,-1)),o=d[d.length-1],l=C(o);continue}if(l+c>e&&l>0){let d=o.trimEnd(),p=i.getLineEndReset();p&&(d+=p),s.push(d),h?(o=i.getActiveCodes(),l=0):(o=i.getActiveCodes()+a,l=c)}else o+=a,l+=c;ei(a,i)}return o&&s.push(o),s.length>0?s.map(a=>a.trimEnd()):[""]}var sn=/[(){}[\]<>.,;:'"!?+\-=*/\\|&%^$#@~`]/;function he(n){return/\s/.test(n)}function bo(n,e,t){let s=[],i=t.getActiveCodes(),r=0,o=0,l=[];for(;o<n.length;){let a=V(n,o);if(a)l.push({type:"ansi",value:a.code}),o+=a.length;else{let c=o;for(;c<n.length&&!V(n,c);)c++;let h=n.slice(o,c);for(let u of ie.segment(h))l.push({type:"grapheme",value:u.segment});o=c}}for(let a of l){if(a.type==="ansi"){i+=a.value,t.process(a.value);continue}let c=a.value;if(!c)continue;let h=C(c);if(r+h>e){let u=t.getLineEndReset();u&&(i+=u),s.push(i),i=t.getActiveCodes(),r=0}i+=c,r+=h}return i&&s.push(i),s.length>0?s:[""]}function ye(n,e,t){let s=C(n),i=Math.max(0,e-s),r=" ".repeat(i),o=n+r;return t(o)}function ee(n,e,t="...",s=!1){if(e<=0)return"";if(n.length===0)return s?" ".repeat(e):"";let i=C(t);if(i>=e){let g=C(n);if(g<=e)return s?n+" ".repeat(e-g):n;let m=lo(t,e);return m.width===0?s?" ".repeat(e):"":en("",0,m.text,m.width,e,s)}if(nn(n)){if(n.length<=e)return s?n+" ".repeat(e-n.length):n;let g=e-i;return en(n.slice(0,g),g,t,i,e,s)}let r=e-i,o="",l="",a=0,c=0,h=!0,u=!1,d=!1,p=n.includes("\x1B"),f=n.includes(" ");if(!p&&!f){for(let{segment:g}of ie.segment(n)){let m=xe(g);if(h&&c+m<=r?(o+=g,c+=m):h=!1,a+=m,a>e){u=!0;break}}d=!u}else{let g=0;for(;g<n.length;){let m=V(n,g);if(m){l+=m.code,g+=m.length;continue}if(n[g]===" "){if(h&&c+3<=r?(l&&(o+=l,l=""),o+=" ",c+=3):(h=!1,l=""),a+=3,a>e){u=!0;break}g++;continue}let x=g;for(;x<n.length&&n[x]!==" "&&!V(n,x);)x++;for(let{segment:T}of ie.segment(n.slice(g,x))){let I=xe(T);if(h&&c+I<=r?(l&&(o+=l,l=""),o+=T,c+=I):(h=!1,l=""),a+=I,a>e){u=!0;break}}if(u)break;g=x}d=g>=n.length}return!u&&d?s?n+" ".repeat(Math.max(0,e-a)):n:en(o,c,t,i,e,s)}function Ie(n,e,t,s=!1){return rn(n,e,t,s).text}function rn(n,e,t,s=!1){if(t<=0)return{text:"",width:0};let i=e+t,r="",o=0,l=0,a=0,c="";for(;a<n.length;){let h=V(n,a);if(h){l>=e&&l<i?r+=h.code:l<e&&(c+=h.code),a+=h.length;continue}let u=a;for(;u<n.length&&!V(n,u);)u++;for(let{segment:d}of ie.segment(n.slice(a,u))){let p=xe(d),f=l>=e&&l<i,g=!s||l+p<=i;if(f&&g&&(c&&(r+=c,c=""),r+=d,o+=p),l+=p,l>=i)break}if(a=u,l>=i)break}return{text:r,width:o}}var tn=new He;function ti(n,e,t,s,i=!1){let r="",o=0,l="",a=0,c=0,h=0,u="",d=!1,p=t+s;for(tn.clear();h<n.length;){let f=V(n,h);if(f){tn.process(f.code),c<e?u+=f.code:c>=t&&c<p&&d&&(l+=f.code),h+=f.length;continue}let g=h;for(;g<n.length&&!V(n,g);)g++;for(let{segment:m}of ie.segment(n.slice(h,g))){let x=xe(m);if(c<e?(u&&(r+=u,u=""),r+=m,o+=x):c>=t&&c<p&&(!i||c+x<=p)&&(d||(l+=tn.getActiveCodes(),d=!0),l+=m,a+=x),c+=x,s<=0?c>=e:c>=p)break}if(h=g,s<=0?c>=e:c>=p)break}return{before:r,beforeWidth:o,after:l,afterWidth:a}}var $e=class{constructor(e="",t=1,s=1,i){this.text=e,this.paddingX=t,this.paddingY=s,this.customBgFn=i}setText(e){this.text=e,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}setCustomBgFn(e){this.customBgFn=e,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}invalidate(){this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}render(e){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===e)return this.cachedLines;if(!this.text||this.text.trim()===""){let u=[];return this.cachedText=this.text,this.cachedWidth=e,this.cachedLines=u,u}let t=this.text.replace(/\t/g," "),s=Math.max(1,e-this.paddingX*2),i=Q(t,s),r=" ".repeat(this.paddingX),o=" ".repeat(this.paddingX),l=[];for(let u of i){let d=r+u+o;if(this.customBgFn)l.push(ye(d,e,this.customBgFn));else{let p=C(d),f=Math.max(0,e-p);l.push(d+" ".repeat(f))}}let a=" ".repeat(e),c=[];for(let u=0;u<this.paddingY;u++){let d=this.customBgFn?ye(a,e,this.customBgFn):a;c.push(d)}let h=[...c,...l,...c];return this.cachedText=this.text,this.cachedWidth=e,this.cachedLines=h,h.length>0?h:[""]}};var re=!1;function Ue(n){re=n}var j={escape:"escape",esc:"esc",enter:"enter",return:"return",tab:"tab",space:"space",backspace:"backspace",delete:"delete",insert:"insert",clear:"clear",home:"home",end:"end",pageUp:"pageUp",pageDown:"pageDown",up:"up",down:"down",left:"left",right:"right",f1:"f1",f2:"f2",f3:"f3",f4:"f4",f5:"f5",f6:"f6",f7:"f7",f8:"f8",f9:"f9",f10:"f10",f11:"f11",f12:"f12",backtick:"`",hyphen:"-",equals:"=",leftbracket:"[",rightbracket:"]",backslash:"\\",semicolon:";",quote:"'",comma:",",period:".",slash:"/",exclamation:"!",at:"@",hash:"#",dollar:"$",percent:"%",caret:"^",ampersand:"&",asterisk:"*",leftparen:"(",rightparen:")",underscore:"_",plus:"+",pipe:"|",tilde:"~",leftbrace:"{",rightbrace:"}",colon:":",lessthan:"<",greaterthan:">",question:"?",ctrl:n=>`ctrl+${n}`,shift:n=>`shift+${n}`,alt:n=>`alt+${n}`,super:n=>`super+${n}`,ctrlShift:n=>`ctrl+shift+${n}`,shiftCtrl:n=>`shift+ctrl+${n}`,ctrlAlt:n=>`ctrl+alt+${n}`,altCtrl:n=>`alt+ctrl+${n}`,shiftAlt:n=>`shift+alt+${n}`,altShift:n=>`alt+shift+${n}`,ctrlSuper:n=>`ctrl+super+${n}`,superCtrl:n=>`super+ctrl+${n}`,shiftSuper:n=>`shift+super+${n}`,superShift:n=>`super+shift+${n}`,altSuper:n=>`alt+super+${n}`,superAlt:n=>`super+alt+${n}`,ctrlShiftAlt:n=>`ctrl+shift+alt+${n}`,ctrlShiftSuper:n=>`ctrl+shift+super+${n}`},ri=new Set(["`","-","=","[","]","\\",";","'",",",".","/","!","@","#","$","%","^","&","*","(",")","_","+","|","~","{","}",":","<",">","?"]),y={shift:1,alt:2,ctrl:4,super:8},vt=192,M={escape:27,tab:9,enter:13,space:32,backspace:127,kpEnter:57414},q={up:-1,down:-2,right:-3,left:-4},K={delete:-10,insert:-11,pageUp:-12,pageDown:-13,home:-14,end:-15},xo=new Map([[57399,48],[57400,49],[57401,50],[57402,51],[57403,52],[57404,53],[57405,54],[57406,55],[57407,56],[57408,57],[57409,46],[57410,47],[57411,42],[57412,45],[57413,43],[57415,61],[57416,44],[57417,q.left],[57418,q.right],[57419,q.up],[57420,q.down],[57421,K.pageUp],[57422,K.pageDown],[57423,K.home],[57424,K.end],[57425,K.insert],[57426,K.delete]]);function on(n){return xo.get(n)??n}function kt(n,e){return(e&~vt&y.shift)!==0&&n>=65&&n<=90?n+32:n}var J={up:["\x1B[A","\x1BOA"],down:["\x1B[B","\x1BOB"],right:["\x1B[C","\x1BOC"],left:["\x1B[D","\x1BOD"],home:["\x1B[H","\x1BOH","\x1B[1~","\x1B[7~"],end:["\x1B[F","\x1BOF","\x1B[4~","\x1B[8~"],insert:["\x1B[2~"],delete:["\x1B[3~"],pageUp:["\x1B[5~","\x1B[[5~"],pageDown:["\x1B[6~","\x1B[[6~"],clear:["\x1B[E","\x1BOE"],f1:["\x1BOP","\x1B[11~","\x1B[[A"],f2:["\x1BOQ","\x1B[12~","\x1B[[B"],f3:["\x1BOR","\x1B[13~","\x1B[[C"],f4:["\x1BOS","\x1B[14~","\x1B[[D"],f5:["\x1B[15~","\x1B[[E"],f6:["\x1B[17~"],f7:["\x1B[18~"],f8:["\x1B[19~"],f9:["\x1B[20~"],f10:["\x1B[21~"],f11:["\x1B[23~"],f12:["\x1B[24~"]},yo={up:["\x1B[a"],down:["\x1B[b"],right:["\x1B[c"],left:["\x1B[d"],clear:["\x1B[e"],insert:["\x1B[2$"],delete:["\x1B[3$"],pageUp:["\x1B[5$"],pageDown:["\x1B[6$"],home:["\x1B[7$"],end:["\x1B[8$"]},vo={up:["\x1BOa"],down:["\x1BOb"],right:["\x1BOc"],left:["\x1BOd"],clear:["\x1BOe"],insert:["\x1B[2^"],delete:["\x1B[3^"],pageUp:["\x1B[5^"],pageDown:["\x1B[6^"],home:["\x1B[7^"],end:["\x1B[8^"]};var z=(n,e)=>e.includes(n),G=(n,e,t)=>t===y.shift?z(n,yo[e]):t===y.ctrl?z(n,vo[e]):!1,bt="press";function an(n){return n.includes("\x1B[200~")?!1:!!(n.includes(":3u")||n.includes(":3~")||n.includes(":3A")||n.includes(":3B")||n.includes(":3C")||n.includes(":3D")||n.includes(":3H")||n.includes(":3F"))}function xt(n){if(!n)return"press";let e=parseInt(n,10);return e===2?"repeat":e===3?"release":"press"}function ko(n){let e=n.match(/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/);if(e){let r=parseInt(e[1],10),o=e[2]&&e[2].length>0?parseInt(e[2],10):void 0,l=e[3]?parseInt(e[3],10):void 0,a=e[4]?parseInt(e[4],10):1,c=xt(e[5]);return bt=c,{codepoint:r,shiftedKey:o,baseLayoutKey:l,modifier:a-1,eventType:c}}let t=n.match(/^\x1b\[1;(\d+)(?::(\d+))?([ABCD])$/);if(t){let r=parseInt(t[1],10),o=xt(t[2]),l={A:-1,B:-2,C:-3,D:-4};return bt=o,{codepoint:l[t[3]],modifier:r-1,eventType:o}}let s=n.match(/^\x1b\[(\d+)(?:;(\d+))?(?::(\d+))?~$/);if(s){let r=parseInt(s[1],10),o=s[2]?parseInt(s[2],10):1,l=xt(s[3]),c={2:K.insert,3:K.delete,5:K.pageUp,6:K.pageDown,7:K.home,8:K.end}[r];if(c!==void 0)return bt=l,{codepoint:c,modifier:o-1,eventType:l}}let i=n.match(/^\x1b\[1;(\d+)(?::(\d+))?([HF])$/);if(i){let r=parseInt(i[1],10),o=xt(i[2]),l=i[3]==="H"?K.home:K.end;return bt=o,{codepoint:l,modifier:r-1,eventType:o}}return null}function w(n,e,t){let s=ko(n);if(!s)return!1;let i=s.modifier&~vt,r=t&~vt;if(i!==r)return!1;let o=kt(on(s.codepoint),s.modifier),l=kt(on(e),t);if(o===l)return!0;if(s.baseLayoutKey!==void 0&&s.baseLayoutKey===e){let a=o,c=a>=97&&a<=122,h=ri.has(String.fromCharCode(a));if(!c&&!h)return!0}return!1}function oi(n){let e=n.match(/^\x1b\[27;(\d+);(\d+)~$/);if(!e)return null;let t=parseInt(e[1],10);return{codepoint:parseInt(e[2],10),modifier:t-1}}function Z(n,e,t){let s=oi(n);return s?s.codepoint===e&&s.modifier===t:!1}function Co(){return!!process.env.WT_SESSION&&!process.env.SSH_CONNECTION&&!process.env.SSH_CLIENT&&!process.env.SSH_TTY}function si(n,e){return n==="\x7F"?e===0:n!=="\b"?!1:Co()?e===y.ctrl:e===0}function So(n){let e=n.toLowerCase(),t=e.charCodeAt(0);return t>=97&&t<=122||e==="["||e==="\\"||e==="]"||e==="_"?String.fromCharCode(t&31):e==="-"?"":null}function ii(n){return n>="0"&&n<="9"}function yt(n,e,t){if(t===0)return!1;let s=oi(n);return!s||s.modifier!==t?!1:kt(s.codepoint,s.modifier)===kt(e,t)}function wo(n){let e=n.toLowerCase().split("+"),t=e[e.length-1];return t?{key:t,ctrl:e.includes("ctrl"),shift:e.includes("shift"),alt:e.includes("alt"),super:e.includes("super")}:null}function N(n,e){let t=wo(e);if(!t)return!1;let{key:s,ctrl:i,shift:r,alt:o,super:l}=t,a=0;switch(r&&(a|=y.shift),o&&(a|=y.alt),i&&(a|=y.ctrl),l&&(a|=y.super),s){case"escape":case"esc":return a!==0?!1:n==="\x1B"||w(n,M.escape,0)||Z(n,M.escape,0);case"space":return!re&&(a===y.ctrl&&n==="\0"||a===y.alt&&n==="\x1B ")?!0:a===0?n===" "||w(n,M.space,0)||Z(n,M.space,0):w(n,M.space,a)||Z(n,M.space,a);case"tab":return a===y.shift?n==="\x1B[Z"||w(n,M.tab,y.shift)||Z(n,M.tab,y.shift):a===0?n===" "||w(n,M.tab,0):w(n,M.tab,a)||Z(n,M.tab,a);case"enter":case"return":return a===y.shift?w(n,M.enter,y.shift)||w(n,M.kpEnter,y.shift)||Z(n,M.enter,y.shift)?!0:re?n==="\x1B\r"||n===`
|
|
255
|
+
`:!1:a===y.alt?w(n,M.enter,y.alt)||w(n,M.kpEnter,y.alt)||Z(n,M.enter,y.alt)?!0:re?!1:n==="\x1B\r":a===0?n==="\r"||!re&&n===`
|
|
256
|
+
`||n==="\x1BOM"||w(n,M.enter,0)||w(n,M.kpEnter,0):w(n,M.enter,a)||w(n,M.kpEnter,a)||Z(n,M.enter,a);case"backspace":return a===y.alt?n==="\x1B\x7F"||n==="\x1B\b"?!0:w(n,M.backspace,y.alt)||Z(n,M.backspace,y.alt):a===y.ctrl?si(n,y.ctrl)?!0:w(n,M.backspace,y.ctrl)||Z(n,M.backspace,y.ctrl):a===0?si(n,0)||w(n,M.backspace,0)||Z(n,M.backspace,0):w(n,M.backspace,a)||Z(n,M.backspace,a);case"insert":return a===0?z(n,J.insert)||w(n,K.insert,0):G(n,"insert",a)?!0:w(n,K.insert,a);case"delete":return a===0?z(n,J.delete)||w(n,K.delete,0):G(n,"delete",a)?!0:w(n,K.delete,a);case"clear":return a===0?z(n,J.clear):G(n,"clear",a);case"home":return a===0?z(n,J.home)||w(n,K.home,0):G(n,"home",a)?!0:w(n,K.home,a);case"end":return a===0?z(n,J.end)||w(n,K.end,0):G(n,"end",a)?!0:w(n,K.end,a);case"pageup":return a===0?z(n,J.pageUp)||w(n,K.pageUp,0):G(n,"pageUp",a)?!0:w(n,K.pageUp,a);case"pagedown":return a===0?z(n,J.pageDown)||w(n,K.pageDown,0):G(n,"pageDown",a)?!0:w(n,K.pageDown,a);case"up":return a===y.alt?n==="\x1Bp"||w(n,q.up,y.alt):a===0?z(n,J.up)||w(n,q.up,0):G(n,"up",a)?!0:w(n,q.up,a);case"down":return a===y.alt?n==="\x1Bn"||w(n,q.down,y.alt):a===0?z(n,J.down)||w(n,q.down,0):G(n,"down",a)?!0:w(n,q.down,a);case"left":return a===y.alt?n==="\x1B[1;3D"||!re&&n==="\x1BB"||n==="\x1Bb"||w(n,q.left,y.alt):a===y.ctrl?n==="\x1B[1;5D"||G(n,"left",y.ctrl)||w(n,q.left,y.ctrl):a===0?z(n,J.left)||w(n,q.left,0):G(n,"left",a)?!0:w(n,q.left,a);case"right":return a===y.alt?n==="\x1B[1;3C"||!re&&n==="\x1BF"||n==="\x1Bf"||w(n,q.right,y.alt):a===y.ctrl?n==="\x1B[1;5C"||G(n,"right",y.ctrl)||w(n,q.right,y.ctrl):a===0?z(n,J.right)||w(n,q.right,0):G(n,"right",a)?!0:w(n,q.right,a);case"f1":case"f2":case"f3":case"f4":case"f5":case"f6":case"f7":case"f8":case"f9":case"f10":case"f11":case"f12":return a!==0?!1:z(n,J[s])}if(s.length===1&&(s>="a"&&s<="z"||ii(s)||ri.has(s))){let c=s.charCodeAt(0),h=So(s),u=s>="a"&&s<="z",d=ii(s);return a===y.ctrl+y.alt&&!re&&h&&n===`\x1B${h}`||a===y.alt&&!re&&(u||d)&&n===`\x1B${s}`?!0:a===y.ctrl?h&&n===h?!0:w(n,c,y.ctrl)||yt(n,c,y.ctrl):a===y.shift+y.ctrl?w(n,c,y.shift+y.ctrl)||yt(n,c,y.shift+y.ctrl):a===y.shift?u&&n===s.toUpperCase()?!0:w(n,c,y.shift)||yt(n,c,y.shift):a!==0?w(n,c,a)||yt(n,c,a):n===s||w(n,c,0)}return!1}var To=/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/,Io=y.shift|vt;function ln(n){let e=n.match(To);if(!e)return;let t=Number.parseInt(e[1]??"",10);if(!Number.isFinite(t))return;let s=e[2]&&e[2].length>0?Number.parseInt(e[2],10):void 0,i=e[4]?Number.parseInt(e[4],10):1,r=Number.isFinite(i)?i-1:0;if((r&~Io)!==0||r&(y.alt|y.ctrl))return;let o=t;if(r&y.shift&&typeof s=="number"&&(o=s),o=on(o),!(!Number.isFinite(o)||o<32))try{return String.fromCodePoint(o)}catch{return}}var ai={"tui.editor.cursorUp":{defaultKeys:"up",description:"Move cursor up"},"tui.editor.cursorDown":{defaultKeys:"down",description:"Move cursor down"},"tui.editor.cursorLeft":{defaultKeys:["left","ctrl+b"],description:"Move cursor left"},"tui.editor.cursorRight":{defaultKeys:["right","ctrl+f"],description:"Move cursor right"},"tui.editor.cursorWordLeft":{defaultKeys:["alt+left","ctrl+left","alt+b"],description:"Move cursor word left"},"tui.editor.cursorWordRight":{defaultKeys:["alt+right","ctrl+right","alt+f"],description:"Move cursor word right"},"tui.editor.cursorLineStart":{defaultKeys:["home","ctrl+a"],description:"Move to line start"},"tui.editor.cursorLineEnd":{defaultKeys:["end","ctrl+e"],description:"Move to line end"},"tui.editor.jumpForward":{defaultKeys:"ctrl+]",description:"Jump forward to character"},"tui.editor.jumpBackward":{defaultKeys:"ctrl+alt+]",description:"Jump backward to character"},"tui.editor.pageUp":{defaultKeys:"pageUp",description:"Page up"},"tui.editor.pageDown":{defaultKeys:"pageDown",description:"Page down"},"tui.editor.deleteCharBackward":{defaultKeys:"backspace",description:"Delete character backward"},"tui.editor.deleteCharForward":{defaultKeys:["delete","ctrl+d"],description:"Delete character forward"},"tui.editor.deleteWordBackward":{defaultKeys:["ctrl+w","alt+backspace"],description:"Delete word backward"},"tui.editor.deleteWordForward":{defaultKeys:["alt+d","alt+delete"],description:"Delete word forward"},"tui.editor.deleteToLineStart":{defaultKeys:"ctrl+u",description:"Delete to line start"},"tui.editor.deleteToLineEnd":{defaultKeys:"ctrl+k",description:"Delete to line end"},"tui.editor.yank":{defaultKeys:"ctrl+y",description:"Yank"},"tui.editor.yankPop":{defaultKeys:"alt+y",description:"Yank pop"},"tui.editor.undo":{defaultKeys:"ctrl+-",description:"Undo"},"tui.input.newLine":{defaultKeys:"shift+enter",description:"Insert newline"},"tui.input.submit":{defaultKeys:"enter",description:"Submit input"},"tui.input.tab":{defaultKeys:"tab",description:"Tab / autocomplete"},"tui.input.copy":{defaultKeys:"ctrl+c",description:"Copy selection"},"tui.select.up":{defaultKeys:"up",description:"Move selection up"},"tui.select.down":{defaultKeys:"down",description:"Move selection down"},"tui.select.pageUp":{defaultKeys:"pageUp",description:"Selection page up"},"tui.select.pageDown":{defaultKeys:"pageDown",description:"Selection page down"},"tui.select.confirm":{defaultKeys:"enter",description:"Confirm selection"},"tui.select.cancel":{defaultKeys:["escape","ctrl+c"],description:"Cancel selection"}};function cn(n){if(n===void 0)return[];let e=Array.isArray(n)?n:[n],t=new Set,s=[];for(let i of e)t.has(i)||(t.add(i),s.push(i));return s}var Ct=class{constructor(e,t={}){this.keysById=new Map;this.conflicts=[];this.definitions=e,this.userBindings=t,this.rebuild()}rebuild(){this.keysById.clear(),this.conflicts=[];let e=new Map;for(let[t,s]of Object.entries(this.userBindings))if(t in this.definitions)for(let i of cn(s)){let r=e.get(i)??new Set;r.add(t),e.set(i,r)}for(let[t,s]of e)s.size>1&&this.conflicts.push({key:t,keybindings:[...s]});for(let[t,s]of Object.entries(this.definitions)){let i=this.userBindings[t],r=cn(i===void 0?s.defaultKeys:i);this.keysById.set(t,r)}}matches(e,t){let s=this.keysById.get(t)??[];for(let i of s)if(N(e,i))return!0;return!1}getKeys(e){return[...this.keysById.get(e)??[]]}getDefinition(e){return this.definitions[e]}getConflicts(){return this.conflicts.map(e=>({...e,keybindings:[...e.keybindings]}))}setUserBindings(e){this.userBindings=e,this.rebuild()}getUserBindings(){return{...this.userBindings}}getResolvedBindings(){let e={};for(let t of Object.keys(this.definitions)){let s=this.keysById.get(t)??[];e[t]=s.length===1?s[0]:[...s]}return e}},un=null;function ve(){return un||(un=new Ct(ai)),un}var ze=class{constructor(){this.ring=[]}push(e,t){if(e)if(t.accumulate&&this.ring.length>0){let s=this.ring.pop();this.ring.push(t.prepend?e+s:s+e)}else this.ring.push(e)}peek(){return this.ring.length>0?this.ring[this.ring.length-1]:void 0}rotate(){if(this.ring.length>1){let e=this.ring.pop();this.ring.unshift(e)}}get length(){return this.ring.length}};import*as de from"node:fs";import*as pn from"node:os";import*as Le from"node:path";import{performance as hn}from"node:perf_hooks";var li="\x1B_G";function dn(n){let e=n.indexOf(li);if(e===-1)return[];let t=e+li.length,s=n.indexOf(";",t);if(s===-1)return[];let i=n.slice(t,s);for(let r of i.split(",")){let[o,l]=r.split("=",2);if(o!=="i"||l===void 0)continue;let a=Number(l);if(Number.isInteger(a)&&a>0&&a<=4294967295)return[a]}return[]}function fn(n){return n!==null&&"focused"in n}var Re="\x1B_pi:c\x07";function ci(n,e){if(n===void 0)return;if(typeof n=="number")return n;let t=n.match(/^(\d+(?:\.\d+)?)%$/);if(t)return Math.floor(e*parseFloat(t[1])/100)}function Lo(){return!!process.env.TERMUX_VERSION}var Pe=class{constructor(){this.children=[]}addChild(e){this.children.push(e)}removeChild(e){let t=this.children.indexOf(e);t!==-1&&this.children.splice(t,1)}clear(){this.children=[]}invalidate(){for(let e of this.children)e.invalidate?.()}render(e){let t=[];for(let s of this.children){let i=s.render(e);for(let r of i)t.push(r)}return t}},Ve=class n extends Pe{constructor(t,s){super();this.previousLines=[];this.previousKittyImageIds=new Set;this.previousWidth=0;this.previousHeight=0;this.focusedComponent=null;this.inputListeners=new Set;this.renderRequested=!1;this.lastRenderAt=0;this.cursorRow=0;this.hardwareCursorRow=0;this.showHardwareCursor=process.env.PI_HARDWARE_CURSOR==="1";this.clearOnShrink=process.env.PI_CLEAR_ON_SHRINK==="1";this.maxLinesRendered=0;this.previousViewportTop=0;this.fullRedrawCount=0;this.stopped=!1;this.focusOrderCounter=0;this.overlayStack=[];this.terminal=t,s!==void 0&&(this.showHardwareCursor=s)}static{this.MIN_RENDER_INTERVAL_MS=16}get fullRedraws(){return this.fullRedrawCount}getShowHardwareCursor(){return this.showHardwareCursor}setShowHardwareCursor(t){this.showHardwareCursor!==t&&(this.showHardwareCursor=t,t||this.terminal.hideCursor(),this.requestRender())}getClearOnShrink(){return this.clearOnShrink}setClearOnShrink(t){this.clearOnShrink=t}setFocus(t){fn(this.focusedComponent)&&(this.focusedComponent.focused=!1),this.focusedComponent=t,fn(t)&&(t.focused=!0)}showOverlay(t,s){let i={component:t,options:s,preFocus:this.focusedComponent,hidden:!1,focusOrder:++this.focusOrderCounter};return this.overlayStack.push(i),!s?.nonCapturing&&this.isOverlayVisible(i)&&this.setFocus(t),this.terminal.hideCursor(),this.requestRender(),{hide:()=>{let r=this.overlayStack.indexOf(i);if(r!==-1){if(this.overlayStack.splice(r,1),this.focusedComponent===t){let o=this.getTopmostVisibleOverlay();this.setFocus(o?.component??i.preFocus)}this.overlayStack.length===0&&this.terminal.hideCursor(),this.requestRender()}},setHidden:r=>{if(i.hidden!==r){if(i.hidden=r,r){if(this.focusedComponent===t){let o=this.getTopmostVisibleOverlay();this.setFocus(o?.component??i.preFocus)}}else!s?.nonCapturing&&this.isOverlayVisible(i)&&(i.focusOrder=++this.focusOrderCounter,this.setFocus(t));this.requestRender()}},isHidden:()=>i.hidden,focus:()=>{!this.overlayStack.includes(i)||!this.isOverlayVisible(i)||(this.focusedComponent!==t&&this.setFocus(t),i.focusOrder=++this.focusOrderCounter,this.requestRender())},unfocus:()=>{if(this.focusedComponent!==t)return;let r=this.getTopmostVisibleOverlay();this.setFocus(r&&r!==i?r.component:i.preFocus),this.requestRender()},isFocused:()=>this.focusedComponent===t}}hideOverlay(){let t=this.overlayStack.pop();if(t){if(this.focusedComponent===t.component){let s=this.getTopmostVisibleOverlay();this.setFocus(s?.component??t.preFocus)}this.overlayStack.length===0&&this.terminal.hideCursor(),this.requestRender()}}hasOverlay(){return this.overlayStack.some(t=>this.isOverlayVisible(t))}isOverlayVisible(t){return t.hidden?!1:t.options?.visible?t.options.visible(this.terminal.columns,this.terminal.rows):!0}getTopmostVisibleOverlay(){for(let t=this.overlayStack.length-1;t>=0;t--)if(!this.overlayStack[t].options?.nonCapturing&&this.isOverlayVisible(this.overlayStack[t]))return this.overlayStack[t]}invalidate(){super.invalidate();for(let t of this.overlayStack)t.component.invalidate?.()}start(){this.stopped=!1,this.terminal.start(t=>this.handleInput(t),()=>this.requestRender()),this.terminal.hideCursor(),this.queryCellSize(),this.requestRender()}addInputListener(t){return this.inputListeners.add(t),()=>{this.inputListeners.delete(t)}}removeInputListener(t){this.inputListeners.delete(t)}queryCellSize(){ue().images&&this.terminal.write("\x1B[16t")}stop(){if(this.stopped=!0,this.renderTimer&&(clearTimeout(this.renderTimer),this.renderTimer=void 0),this.previousLines.length>0){let s=this.previousLines.length-this.hardwareCursorRow;s>0?this.terminal.write(`\x1B[${s}B`):s<0&&this.terminal.write(`\x1B[${-s}A`),this.terminal.write(`\r
|
|
257
|
+
`)}this.terminal.showCursor(),this.terminal.stop()}requestRender(t=!1){if(t){this.previousLines=[],this.previousWidth=-1,this.previousHeight=-1,this.cursorRow=0,this.hardwareCursorRow=0,this.maxLinesRendered=0,this.previousViewportTop=0,this.renderTimer&&(clearTimeout(this.renderTimer),this.renderTimer=void 0),this.renderRequested=!0,process.nextTick(()=>{this.stopped||!this.renderRequested||(this.renderRequested=!1,this.lastRenderAt=hn.now(),this.doRender())});return}this.renderRequested||(this.renderRequested=!0,process.nextTick(()=>this.scheduleRender()))}scheduleRender(){if(this.stopped||this.renderTimer||!this.renderRequested)return;let t=hn.now()-this.lastRenderAt,s=Math.max(0,n.MIN_RENDER_INTERVAL_MS-t);this.renderTimer=setTimeout(()=>{this.renderTimer=void 0,!(this.stopped||!this.renderRequested)&&(this.renderRequested=!1,this.lastRenderAt=hn.now(),this.doRender(),this.renderRequested&&this.scheduleRender())},s)}handleInput(t){if(this.inputListeners.size>0){let i=t;for(let r of this.inputListeners){let o=r(i);if(o?.consume)return;o?.data!==void 0&&(i=o.data)}if(i.length===0)return;t=i}if(this.consumeCellSizeResponse(t))return;if(N(t,"shift+ctrl+d")&&this.onDebug){this.onDebug();return}let s=this.overlayStack.find(i=>i.component===this.focusedComponent);if(s&&!this.isOverlayVisible(s)){let i=this.getTopmostVisibleOverlay();i?this.setFocus(i.component):this.setFocus(s.preFocus)}if(this.focusedComponent?.handleInput){if(an(t)&&!this.focusedComponent.wantsKeyRelease)return;this.focusedComponent.handleInput(t),this.requestRender()}}consumeCellSizeResponse(t){let s=t.match(/^\x1b\[6;(\d+);(\d+)t$/);if(!s)return!1;let i=parseInt(s[1],10),r=parseInt(s[2],10);return i<=0||r<=0||(Vt({widthPx:r,heightPx:i}),this.invalidate(),this.requestRender()),!0}resolveOverlayLayout(t,s,i,r){let o=t??{},l=typeof o.margin=="number"?{top:o.margin,right:o.margin,bottom:o.margin,left:o.margin}:o.margin??{},a=Math.max(0,l.top??0),c=Math.max(0,l.right??0),h=Math.max(0,l.bottom??0),u=Math.max(0,l.left??0),d=Math.max(1,i-u-c),p=Math.max(1,r-a-h),f=ci(o.width,i)??Math.min(80,d);o.minWidth!==void 0&&(f=Math.max(f,o.minWidth)),f=Math.max(1,Math.min(f,d));let g=ci(o.maxHeight,r);g!==void 0&&(g=Math.max(1,Math.min(g,p)));let m=g!==void 0?Math.min(s,g):s,x,T;if(o.row!==void 0)if(typeof o.row=="string"){let I=o.row.match(/^(\d+(?:\.\d+)?)%$/);if(I){let D=Math.max(0,p-m),R=parseFloat(I[1])/100;x=a+Math.floor(D*R)}else x=this.resolveAnchorRow("center",m,p,a)}else x=o.row;else{let I=o.anchor??"center";x=this.resolveAnchorRow(I,m,p,a)}if(o.col!==void 0)if(typeof o.col=="string"){let I=o.col.match(/^(\d+(?:\.\d+)?)%$/);if(I){let D=Math.max(0,d-f),R=parseFloat(I[1])/100;T=u+Math.floor(D*R)}else T=this.resolveAnchorCol("center",f,d,u)}else T=o.col;else{let I=o.anchor??"center";T=this.resolveAnchorCol(I,f,d,u)}return o.offsetY!==void 0&&(x+=o.offsetY),o.offsetX!==void 0&&(T+=o.offsetX),x=Math.max(a,Math.min(x,r-h-m)),T=Math.max(u,Math.min(T,i-c-f)),{width:f,row:x,col:T,maxHeight:g}}resolveAnchorRow(t,s,i,r){switch(t){case"top-left":case"top-center":case"top-right":return r;case"bottom-left":case"bottom-center":case"bottom-right":return r+i-s;case"left-center":case"center":case"right-center":return r+Math.floor((i-s)/2)}}resolveAnchorCol(t,s,i,r){switch(t){case"top-left":case"left-center":case"bottom-left":return r;case"top-right":case"right-center":case"bottom-right":return r+i-s;case"top-center":case"center":case"bottom-center":return r+Math.floor((i-s)/2)}}compositeOverlays(t,s,i){if(this.overlayStack.length===0)return t;let r=[...t],o=[],l=r.length,a=this.overlayStack.filter(u=>this.isOverlayVisible(u));a.sort((u,d)=>u.focusOrder-d.focusOrder);for(let u of a){let{component:d,options:p}=u,{width:f,maxHeight:g}=this.resolveOverlayLayout(p,0,s,i),m=d.render(f);g!==void 0&&m.length>g&&(m=m.slice(0,g));let{row:x,col:T}=this.resolveOverlayLayout(p,m.length,s,i);o.push({overlayLines:m,row:x,col:T,w:f}),l=Math.max(l,x+m.length)}let c=Math.max(r.length,i,l);for(;r.length<c;)r.push("");let h=Math.max(0,c-i);for(let{overlayLines:u,row:d,col:p,w:f}of o)for(let g=0;g<u.length;g++){let m=h+d+g;if(m>=0&&m<r.length){let x=C(u[g])>f?Ie(u[g],0,f,!0):u[g];r[m]=this.compositeLineAt(r[m],x,p,f,s)}}return r}static{this.SEGMENT_RESET="\x1B[0m\x1B]8;;\x07"}applyLineResets(t){let s=n.SEGMENT_RESET;for(let i=0;i<t.length;i++){let r=t[i];be(r)||(t[i]=Zs(r)+s)}return t}collectKittyImageIds(t){let s=new Set;for(let i of t)for(let r of dn(i))s.add(r);return s}deleteKittyImages(t){let s="";for(let i of t)s+=Yt(i);return s}expandLastChangedForKittyImages(t,s){let i=s;for(let r=t;r<this.previousLines.length;r++)dn(this.previousLines[r]).length>0&&(i=Math.max(i,r));return i}deleteChangedKittyImages(t,s){if(t<0||s<t)return"";let i=new Set,r=Math.min(s,this.previousLines.length-1);for(let o=t;o<=r;o++)for(let l of dn(this.previousLines[o]??""))i.add(l);return this.deleteKittyImages(i)}compositeLineAt(t,s,i,r,o){if(be(t))return t;let l=i+r,a=ti(t,i,l,o-l,!0),c=rn(s,0,r,!0),h=Math.max(0,i-a.beforeWidth),u=Math.max(0,r-c.width),d=Math.max(i,a.beforeWidth),p=Math.max(r,c.width),f=Math.max(0,o-d-p),g=Math.max(0,f-a.afterWidth),m=n.SEGMENT_RESET,x=a.before+" ".repeat(h)+m+c.text+" ".repeat(u)+m+a.after+" ".repeat(g);return C(x)<=o?x:Ie(x,0,o,!0)}extractCursorPosition(t,s){let i=Math.max(0,t.length-s);for(let r=t.length-1;r>=i;r--){let o=t[r],l=o.indexOf(Re);if(l!==-1){let a=o.slice(0,l),c=C(a);return t[r]=o.slice(0,l)+o.slice(l+Re.length),{row:r,col:c}}}return null}doRender(){if(this.stopped)return;let t=this.terminal.columns,s=this.terminal.rows,i=this.previousWidth!==0&&this.previousWidth!==t,r=this.previousHeight!==0&&this.previousHeight!==s,o=this.previousHeight>0?this.previousViewportTop+this.previousHeight:s,l=r?Math.max(0,o-s):this.previousViewportTop,a=l,c=this.hardwareCursorRow,h=b=>{let S=c-l;return b-a-S},u=this.render(t);this.overlayStack.length>0&&(u=this.compositeOverlays(u,t,s));let d=this.extractCursorPosition(u,s);u=this.applyLineResets(u);let p=b=>{this.fullRedrawCount+=1;let S="\x1B[?2026h";b&&(S+=this.deleteKittyImages(this.previousKittyImageIds),S+="\x1B[2J\x1B[H\x1B[3J");for(let P=0;P<u.length;P++)P>0&&(S+=`\r
|
|
258
|
+
`),S+=u[P];S+="\x1B[?2026l",this.terminal.write(S),this.cursorRow=Math.max(0,u.length-1),this.hardwareCursorRow=this.cursorRow,b?this.maxLinesRendered=u.length:this.maxLinesRendered=Math.max(this.maxLinesRendered,u.length);let W=Math.max(s,u.length);this.previousViewportTop=Math.max(0,W-s),this.positionHardwareCursor(d,u.length),this.previousLines=u,this.previousKittyImageIds=this.collectKittyImageIds(u),this.previousWidth=t,this.previousHeight=s},f=process.env.PI_DEBUG_REDRAW==="1",g=b=>{if(!f)return;let S=Le.join(pn.homedir(),".pi","agent","pi-debug.log"),W=`[${new Date().toISOString()}] fullRender: ${b} (prev=${this.previousLines.length}, new=${u.length}, height=${s})
|
|
259
|
+
`;de.appendFileSync(S,W)};if(this.previousLines.length===0&&!i&&!r){g("first render"),p(!1);return}if(i){g(`terminal width changed (${this.previousWidth} -> ${t})`),p(!0);return}if(r&&!Lo()){g(`terminal height changed (${this.previousHeight} -> ${s})`),p(!0);return}if(this.clearOnShrink&&u.length<this.maxLinesRendered&&this.overlayStack.length===0){g(`clearOnShrink (maxLinesRendered=${this.maxLinesRendered})`),p(!0);return}let m=-1,x=-1,T=Math.max(u.length,this.previousLines.length);for(let b=0;b<T;b++){let S=b<this.previousLines.length?this.previousLines[b]:"",W=b<u.length?u[b]:"";S!==W&&(m===-1&&(m=b),x=b)}let I=u.length>this.previousLines.length;I&&(m===-1&&(m=this.previousLines.length),x=u.length-1),m!==-1&&(x=this.expandLastChangedForKittyImages(m,x));let D=I&&m===this.previousLines.length&&m>0;if(m===-1){this.positionHardwareCursor(d,u.length),this.previousViewportTop=l,this.previousHeight=s;return}if(m>=u.length){if(this.previousLines.length>u.length){let b="\x1B[?2026h";b+=this.deleteChangedKittyImages(m,x);let S=Math.max(0,u.length-1);if(S<l){g(`deleted lines moved viewport up (${S} < ${l})`),p(!0);return}let W=h(S);W>0?b+=`\x1B[${W}B`:W<0&&(b+=`\x1B[${-W}A`),b+="\r";let P=this.previousLines.length-u.length;if(P>s){g(`extraLines > height (${P} > ${s})`),p(!0);return}P>0&&(b+="\x1B[1B");for(let se=0;se<P;se++)b+="\r\x1B[2K",se<P-1&&(b+="\x1B[1B");P>0&&(b+=`\x1B[${P}A`),b+="\x1B[?2026l",this.terminal.write(b),this.cursorRow=S,this.hardwareCursorRow=S}this.positionHardwareCursor(d,u.length),this.previousLines=u,this.previousKittyImageIds=this.collectKittyImageIds(u),this.previousWidth=t,this.previousHeight=s,this.previousViewportTop=l;return}if(m<l){g(`firstChanged < viewportTop (${m} < ${l})`),p(!0);return}let R="\x1B[?2026h";R+=this.deleteChangedKittyImages(m,x);let v=l+s-1,$=D?m-1:m;if($>v){let b=Math.max(0,Math.min(s-1,c-l)),S=s-1-b;S>0&&(R+=`\x1B[${S}B`);let W=$-v;R+=`\r
|
|
260
|
+
`.repeat(W),l+=W,a+=W,c=$}let B=h($);B>0?R+=`\x1B[${B}B`:B<0&&(R+=`\x1B[${-B}A`),R+=D?`\r
|
|
261
|
+
`:"\r";let F=Math.min(x,u.length-1);for(let b=m;b<=F;b++){b>m&&(R+=`\r
|
|
262
|
+
`),R+="\x1B[2K";let S=u[b];if(!be(S)&&C(S)>t){let P=Le.join(pn.homedir(),".pi","agent","tui-overflow.log"),se=`${new Date().toISOString()} width=${t} line=${b} vw=${C(S)} lineContent=${JSON.stringify(S)}
|
|
263
|
+
`;try{de.mkdirSync(Le.dirname(P),{recursive:!0}),de.appendFileSync(P,se)}catch{}S=ee(S,t)}R+=S}let A=F;if(this.previousLines.length>u.length){if(F<u.length-1){let S=u.length-1-F;R+=`\x1B[${S}B`,A=u.length-1}let b=this.previousLines.length-u.length;for(let S=u.length;S<this.previousLines.length;S++)R+=`\r
|
|
264
|
+
\x1B[2K`;R+=`\x1B[${b}A`}if(R+="\x1B[?2026l",process.env.PI_TUI_DEBUG==="1"){let b="/tmp/tui";de.mkdirSync(b,{recursive:!0});let S=Le.join(b,`render-${Date.now()}-${Math.random().toString(36).slice(2)}.log`),W=[`firstChanged: ${m}`,`viewportTop: ${a}`,`cursorRow: ${this.cursorRow}`,`height: ${s}`,`lineDiff: ${B}`,`hardwareCursorRow: ${c}`,`renderEnd: ${F}`,`finalCursorRow: ${A}`,`cursorPos: ${JSON.stringify(d)}`,`newLines.length: ${u.length}`,`previousLines.length: ${this.previousLines.length}`,"","=== newLines ===",JSON.stringify(u,null,2),"","=== previousLines ===",JSON.stringify(this.previousLines,null,2),"","=== buffer ===",JSON.stringify(R)].join(`
|
|
265
|
+
`);de.writeFileSync(S,W)}this.terminal.write(R),this.cursorRow=Math.max(0,u.length-1),this.hardwareCursorRow=A,this.maxLinesRendered=Math.max(this.maxLinesRendered,u.length),this.previousViewportTop=Math.max(l,A-s+1),this.positionHardwareCursor(d,u.length),this.previousLines=u,this.previousKittyImageIds=this.collectKittyImageIds(u),this.previousWidth=t,this.previousHeight=s}positionHardwareCursor(t,s){if(!t||s<=0){this.terminal.hideCursor();return}let i=Math.max(0,Math.min(t.row,s-1)),r=Math.max(0,t.col),o=i-this.hardwareCursorRow,l="";o>0?l+=`\x1B[${o}B`:o<0&&(l+=`\x1B[${-o}A`),l+=`\x1B[${r+1}G`,l&&this.terminal.write(l),this.hardwareCursorRow=i,this.showHardwareCursor?this.terminal.showCursor():this.terminal.hideCursor()}};var Ge=class{constructor(){this.stack=[]}push(e){this.stack.push(structuredClone(e))}pop(){return this.stack.pop()}clear(){this.stack.length=0}get length(){return this.stack.length}};var ui=mt();function gn(n,e,t){if(e<=0)return 0;let s=n.slice(0,e),i=t?.segment,r=t?.isAtomicSegment,o=i?[...i(s)]:[...ui.segment(s)],l=e;for(;o.length>0&&!r?.(o[o.length-1]?.segment||"")&&he(o[o.length-1]?.segment||"");)l-=o.pop()?.segment.length||0;if(o.length===0)return l;let a=o[o.length-1];if(r?.(a.segment))l-=a.segment.length;else if(a.isWordLike){let c=a.segment,h=[...c.matchAll(new RegExp(sn,"g"))];if(h.length<=0)l-=c.length;else{let u=h[h.length-1];l-=c.length-(u.index+u[0].length)}}else for(;o.length>0&&!r?.(o[o.length-1]?.segment||"")&&!o[o.length-1]?.isWordLike&&!he(o[o.length-1]?.segment||"");)l-=o.pop()?.segment.length||0;return l}function mn(n,e,t){if(e>=n.length)return n.length;let s=n.slice(e),i=t?.segment,r=t?.isAtomicSegment,l=(i?i(s):ui.segment(s))[Symbol.iterator](),a=l.next(),c=e;for(;!a.done&&!r?.(a.value.segment)&&he(a.value.segment);)c+=a.value.segment.length,a=l.next();if(a.done)return c;if(r?.(a.value.segment))c+=a.value.segment.length;else if(a.value.isWordLike)c+=sn.exec(a.value.segment)?.index??a.value.segment.length;else for(;!a.done&&!r?.(a.value.segment)&&!a.value.isWordLike&&!he(a.value.segment);)c+=a.value.segment.length,a=l.next();return c}var tu=gt(),nu=mt();var Ye=gt(),Ae=class{constructor(e={}){this.value="";this.cursor=0;this.focused=!1;this.pasteBuffer="";this.isInPaste=!1;this.killRing=new ze;this.lastAction=null;this.undoStack=new Ge;this.deps=e}getValue(){return this.value}setValue(e){this.value=e,this.cursor=e.length}handleInput(e){let t=this.value;try{if(e.includes("\x1B[200~")&&(this.isInPaste=!0,this.pasteBuffer="",e=e.replace("\x1B[200~","")),this.isInPaste){this.pasteBuffer+=e;let o=this.pasteBuffer.indexOf("\x1B[201~");if(o!==-1){let l=this.pasteBuffer.substring(0,o);this.handlePaste(l),this.isInPaste=!1;let a=this.pasteBuffer.substring(o+6);this.pasteBuffer="",a&&this.handleInput(a)}return}let s=ve();if(s.matches(e,"tui.select.cancel")){this.onEscape&&this.onEscape();return}if(s.matches(e,"tui.editor.undo")){this.undo();return}if(s.matches(e,"tui.input.submit")||e===`
|
|
266
|
+
`){this.onSubmit&&this.onSubmit(this.value);return}if(s.matches(e,"tui.editor.deleteCharBackward")){this.handleBackspace();return}if(s.matches(e,"tui.editor.deleteCharForward")){this.handleForwardDelete();return}if(s.matches(e,"tui.editor.deleteWordBackward")){this.deleteWordBackwards();return}if(s.matches(e,"tui.editor.deleteWordForward")){this.deleteWordForward();return}if(s.matches(e,"tui.editor.deleteToLineStart")){this.deleteToLineStart();return}if(s.matches(e,"tui.editor.deleteToLineEnd")){this.deleteToLineEnd();return}if(s.matches(e,"tui.editor.yank")){this.yank();return}if(s.matches(e,"tui.editor.yankPop")){this.yankPop();return}if(s.matches(e,"tui.editor.cursorLeft")){if(this.lastAction=null,this.cursor>0){let o=this.value.slice(0,this.cursor),l=[...Ye.segment(o)],a=l[l.length-1];this.cursor-=a?a.segment.length:1}return}if(s.matches(e,"tui.editor.cursorRight")){if(this.lastAction=null,this.cursor<this.value.length){let o=this.value.slice(this.cursor),a=[...Ye.segment(o)][0];this.cursor+=a?a.segment.length:1}return}if(s.matches(e,"tui.editor.cursorLineStart")){this.lastAction=null,this.cursor=0;return}if(s.matches(e,"tui.editor.cursorLineEnd")){this.lastAction=null,this.cursor=this.value.length;return}if(s.matches(e,"tui.editor.cursorWordLeft")){this.moveWordBackwards();return}if(s.matches(e,"tui.editor.cursorWordRight")){this.moveWordForwards();return}let i=ln(e);if(i!==void 0){this.insertCharacter(i);return}[...e].some(o=>{let l=o.charCodeAt(0);return l<32||l===127||l>=128&&l<=159})||this.insertCharacter(e)}finally{this.value!==t&&this.onChange?.(this.value)}}insertCharacter(e){(he(e)||this.lastAction!=="type-word")&&this.pushUndo(),this.lastAction="type-word",this.value=this.value.slice(0,this.cursor)+e+this.value.slice(this.cursor),this.cursor+=e.length}insertText(e){this.lastAction="type-word",this.value=this.value.slice(0,this.cursor)+e+this.value.slice(this.cursor),this.cursor+=e.length}handleBackspace(){if(this.lastAction=null,this.cursor>0){this.pushUndo();let e=this.value.slice(0,this.cursor),t=[...Ye.segment(e)],s=t[t.length-1],i=s?s.segment.length:1;this.value=this.value.slice(0,this.cursor-i)+this.value.slice(this.cursor),this.cursor-=i}}handleForwardDelete(){if(this.lastAction=null,this.cursor<this.value.length){this.pushUndo();let e=this.value.slice(this.cursor),s=[...Ye.segment(e)][0],i=s?s.segment.length:1;this.value=this.value.slice(0,this.cursor)+this.value.slice(this.cursor+i)}}deleteToLineStart(){if(this.cursor===0)return;this.pushUndo();let e=this.value.slice(0,this.cursor);this.killRing.push(e,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.value=this.value.slice(this.cursor),this.cursor=0}deleteToLineEnd(){if(this.cursor>=this.value.length)return;this.pushUndo();let e=this.value.slice(this.cursor);this.killRing.push(e,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.value=this.value.slice(0,this.cursor)}deleteWordBackwards(){if(this.cursor===0)return;let e=this.lastAction==="kill";this.pushUndo();let t=this.cursor;this.moveWordBackwards();let s=this.cursor;this.cursor=t;let i=this.value.slice(s,this.cursor);this.killRing.push(i,{prepend:!0,accumulate:e}),this.lastAction="kill",this.value=this.value.slice(0,s)+this.value.slice(this.cursor),this.cursor=s}deleteWordForward(){if(this.cursor>=this.value.length)return;let e=this.lastAction==="kill";this.pushUndo();let t=this.cursor;this.moveWordForwards();let s=this.cursor;this.cursor=t;let i=this.value.slice(this.cursor,s);this.killRing.push(i,{prepend:!1,accumulate:e}),this.lastAction="kill",this.value=this.value.slice(0,this.cursor)+this.value.slice(s)}yank(){let e=this.killRing.peek();e&&(this.pushUndo(),this.value=this.value.slice(0,this.cursor)+e+this.value.slice(this.cursor),this.cursor+=e.length,this.lastAction="yank")}yankPop(){if(this.lastAction!=="yank"||this.killRing.length<=1)return;this.pushUndo();let e=this.killRing.peek()||"";this.value=this.value.slice(0,this.cursor-e.length)+this.value.slice(this.cursor),this.cursor-=e.length,this.killRing.rotate();let t=this.killRing.peek()||"";this.value=this.value.slice(0,this.cursor)+t+this.value.slice(this.cursor),this.cursor+=t.length,this.lastAction="yank"}pushUndo(){this.undoStack.push({value:this.value,cursor:this.cursor})}undo(){let e=this.undoStack.pop();e&&(this.value=e.value,this.cursor=e.cursor,this.lastAction=null)}moveWordBackwards(){this.cursor!==0&&(this.lastAction=null,this.cursor=gn(this.value,this.cursor))}moveWordForwards(){this.cursor>=this.value.length||(this.lastAction=null,this.cursor=mn(this.value,this.cursor))}handlePaste(e){this.handlePasteAsync(e).catch(()=>{})}async handlePasteAsync(e){let{detectImage:t,readImage:s,registerImage:i}=this.deps,r=!1;try{r=await t?.()??!1}catch{r=!1}if(r&&s&&i){let l;try{l=await s()}catch{l={ok:!1,error:"OSASCRIPT_FAILED"}}if(l.ok){this.lastAction=null,this.pushUndo();let a=i(l.base64,l.bytes);this.insertText(`[Image #${a}]`),this.onAttachmentsChange?.();return}if(l.error==="TOO_LARGE"){this.lastAction=null,this.onError?.("\u56FE\u7247\u8D85\u8FC7 5MB\uFF0C\u5DF2\u5FFD\u7565");return}}this.lastAction=null,this.pushUndo();let o=e.replace(/\r\n/g,"").replace(/\r/g,"").replace(/\n/g,"").replace(/\t/g," ");this.value=this.value.slice(0,this.cursor)+o+this.value.slice(this.cursor),this.cursor+=o.length}invalidate(){}render(e){let s=e-2;if(s<=0)return["> "];let i="",r=this.cursor,o=C(this.value);if(o<s)i=this.value;else{let T=this.cursor===this.value.length?s-1:s,I=C(this.value.slice(0,this.cursor));if(T>0){let D=Math.floor(T/2),R=0;I<D?R=0:I>o-D?R=Math.max(0,o-T):R=Math.max(0,I-D),i=Ie(this.value,R,T,!0),r=Ie(this.value,R,Math.max(0,I-R),!0).length}else i="",r=0}let a=[...Ye.segment(i.slice(r))][0],c=i.slice(0,r),h=a?.segment??" ",u=i.slice(r+h.length),d=this.focused?Re:"",p=`\x1B[7m${h}\x1B[27m`,f=c+d+p+u,g=C(f),m=" ".repeat(Math.max(0,s-g));return["> "+f+m]}};function vn(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Ce=vn();function mi(n){Ce=n}var Je={exec:()=>null};function E(n,e=""){let t=typeof n=="string"?n:n.source,s={replace:(i,r)=>{let o=typeof r=="string"?r:r.source;return o=o.replace(U.caret,"$1"),t=t.replace(i,o),s},getRegex:()=>new RegExp(t,e)};return s}var U={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ xX]\] +/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:n=>new RegExp(`^( {0,3}${n})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:n=>new RegExp(`^ {0,${Math.min(3,n-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:n=>new RegExp(`^ {0,${Math.min(3,n-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:n=>new RegExp(`^ {0,${Math.min(3,n-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:n=>new RegExp(`^ {0,${Math.min(3,n-1)}}#`),htmlBeginRegex:n=>new RegExp(`^ {0,${Math.min(3,n-1)}}<(?:[a-z].*>|!--)`,"i")},Po=/^(?:[ \t]*(?:\n|$))+/,Ao=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Mo=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Ze=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Eo=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,kn=/(?:[*+-]|\d{1,9}[.)])/,bi=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,xi=E(bi).replace(/bull/g,kn).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Oo=E(bi).replace(/bull/g,kn).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Cn=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,_o=/^[^\n]+/,Sn=/(?!\s*\])(?:\\.|[^\[\]\\])+/,Bo=E(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Sn).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Ko=E(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,kn).getRegex(),$t="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",wn=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Do=E("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",wn).replace("tag",$t).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),yi=E(Cn).replace("hr",Ze).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",$t).getRegex(),Wo=E(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",yi).getRegex(),Tn={blockquote:Wo,code:Ao,def:Bo,fences:Mo,heading:Eo,hr:Ze,html:Do,lheading:xi,list:Ko,newline:Po,paragraph:yi,table:Je,text:_o},hi=E("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Ze).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",$t).getRegex(),No={...Tn,lheading:Oo,table:hi,paragraph:E(Cn).replace("hr",Ze).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",hi).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",$t).getRegex()},Fo={...Tn,html:E(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",wn).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Je,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:E(Cn).replace("hr",Ze).replace("heading",` *#{1,6} *[^
|
|
267
|
+
]`).replace("lheading",xi).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},jo=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,qo=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,vi=/^( {2,}|\\)\n(?!\s*$)/,Ho=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Lt=/[\p{P}\p{S}]/u,In=/[\s\p{P}\p{S}]/u,ki=/[^\s\p{P}\p{S}]/u,Uo=E(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,In).getRegex(),Ci=/(?!~)[\p{P}\p{S}]/u,zo=/(?!~)[\s\p{P}\p{S}]/u,Vo=/(?:[^\s\p{P}\p{S}]|~)/u,Go=/\[[^[\]]*?\]\((?:\\.|[^\\\(\)]|\((?:\\.|[^\\\(\)])*\))*\)|`[^`]*?`|<[^<>]*?>/g,Si=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,Yo=E(Si,"u").replace(/punct/g,Lt).getRegex(),Xo=E(Si,"u").replace(/punct/g,Ci).getRegex(),wi="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Qo=E(wi,"gu").replace(/notPunctSpace/g,ki).replace(/punctSpace/g,In).replace(/punct/g,Lt).getRegex(),Jo=E(wi,"gu").replace(/notPunctSpace/g,Vo).replace(/punctSpace/g,zo).replace(/punct/g,Ci).getRegex(),Zo=E("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,ki).replace(/punctSpace/g,In).replace(/punct/g,Lt).getRegex(),ea=E(/\\(punct)/,"gu").replace(/punct/g,Lt).getRegex(),ta=E(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),na=E(wn).replace("(?:-->|$)","-->").getRegex(),sa=E("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",na).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Tt=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,ia=E(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",Tt).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Ti=E(/^!?\[(label)\]\[(ref)\]/).replace("label",Tt).replace("ref",Sn).getRegex(),Ii=E(/^!?\[(ref)\](?:\[\])?/).replace("ref",Sn).getRegex(),ra=E("reflink|nolink(?!\\()","g").replace("reflink",Ti).replace("nolink",Ii).getRegex(),$n={_backpedal:Je,anyPunctuation:ea,autolink:ta,blockSkip:Go,br:vi,code:qo,del:Je,emStrongLDelim:Yo,emStrongRDelimAst:Qo,emStrongRDelimUnd:Zo,escape:jo,link:ia,nolink:Ii,punctuation:Uo,reflink:Ti,reflinkSearch:ra,tag:sa,text:Ho,url:Je},oa={...$n,link:E(/^!?\[(label)\]\((.*?)\)/).replace("label",Tt).getRegex(),reflink:E(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Tt).getRegex()},bn={...$n,emStrongRDelimAst:Jo,emStrongLDelim:Xo,url:E(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},aa={...bn,br:E(vi).replace("{2,}","*").getRegex(),text:E(bn.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},St={normal:Tn,gfm:No,pedantic:Fo},Xe={normal:$n,gfm:bn,breaks:aa,pedantic:oa},la={"&":"&","<":"<",">":">",'"':""","'":"'"},di=n=>la[n];function te(n,e){if(e){if(U.escapeTest.test(n))return n.replace(U.escapeReplace,di)}else if(U.escapeTestNoEncode.test(n))return n.replace(U.escapeReplaceNoEncode,di);return n}function pi(n){try{n=encodeURI(n).replace(U.percentDecode,"%")}catch{return null}return n}function fi(n,e){let t=n.replace(U.findPipe,(r,o,l)=>{let a=!1,c=o;for(;--c>=0&&l[c]==="\\";)a=!a;return a?"|":" |"}),s=t.split(U.splitPipe),i=0;if(s[0].trim()||s.shift(),s.length>0&&!s.at(-1)?.trim()&&s.pop(),e)if(s.length>e)s.splice(e);else for(;s.length<e;)s.push("");for(;i<s.length;i++)s[i]=s[i].trim().replace(U.slashPipe,"|");return s}function Qe(n,e,t){let s=n.length;if(s===0)return"";let i=0;for(;i<s;){let r=n.charAt(s-i-1);if(r===e&&!t)i++;else if(r!==e&&t)i++;else break}return n.slice(0,s-i)}function ca(n,e){if(n.indexOf(e[1])===-1)return-1;let t=0;for(let s=0;s<n.length;s++)if(n[s]==="\\")s++;else if(n[s]===e[0])t++;else if(n[s]===e[1]&&(t--,t<0))return s;return t>0?-2:-1}function gi(n,e,t,s,i){let r=e.href,o=e.title||null,l=n[1].replace(i.other.outputLinkReplace,"$1");s.state.inLink=!0;let a={type:n[0].charAt(0)==="!"?"image":"link",raw:t,href:r,title:o,text:l,tokens:s.inlineTokens(l)};return s.state.inLink=!1,a}function ua(n,e,t){let s=n.match(t.other.indentCodeCompensation);if(s===null)return e;let i=s[1];return e.split(`
|
|
268
|
+
`).map(r=>{let o=r.match(t.other.beginningSpace);if(o===null)return r;let[l]=o;return l.length>=i.length?r.slice(i.length):r}).join(`
|
|
269
|
+
`)}var Me=class{options;rules;lexer;constructor(n){this.options=n||Ce}space(n){let e=this.rules.block.newline.exec(n);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(n){let e=this.rules.block.code.exec(n);if(e){let t=e[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:e[0],codeBlockStyle:"indented",text:this.options.pedantic?t:Qe(t,`
|
|
270
|
+
`)}}}fences(n){let e=this.rules.block.fences.exec(n);if(e){let t=e[0],s=ua(t,e[3]||"",this.rules);return{type:"code",raw:t,lang:e[2]?e[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):e[2],text:s}}}heading(n){let e=this.rules.block.heading.exec(n);if(e){let t=e[2].trim();if(this.rules.other.endingHash.test(t)){let s=Qe(t,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(t=s.trim())}return{type:"heading",raw:e[0],depth:e[1].length,text:t,tokens:this.lexer.inline(t)}}}hr(n){let e=this.rules.block.hr.exec(n);if(e)return{type:"hr",raw:Qe(e[0],`
|
|
271
|
+
`)}}blockquote(n){let e=this.rules.block.blockquote.exec(n);if(e){let t=Qe(e[0],`
|
|
272
|
+
`).split(`
|
|
273
|
+
`),s="",i="",r=[];for(;t.length>0;){let o=!1,l=[],a;for(a=0;a<t.length;a++)if(this.rules.other.blockquoteStart.test(t[a]))l.push(t[a]),o=!0;else if(!o)l.push(t[a]);else break;t=t.slice(a);let c=l.join(`
|
|
274
|
+
`),h=c.replace(this.rules.other.blockquoteSetextReplace,`
|
|
275
|
+
$1`).replace(this.rules.other.blockquoteSetextReplace2,"");s=s?`${s}
|
|
276
|
+
${c}`:c,i=i?`${i}
|
|
277
|
+
${h}`:h;let u=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(h,r,!0),this.lexer.state.top=u,t.length===0)break;let d=r.at(-1);if(d?.type==="code")break;if(d?.type==="blockquote"){let p=d,f=p.raw+`
|
|
278
|
+
`+t.join(`
|
|
279
|
+
`),g=this.blockquote(f);r[r.length-1]=g,s=s.substring(0,s.length-p.raw.length)+g.raw,i=i.substring(0,i.length-p.text.length)+g.text;break}else if(d?.type==="list"){let p=d,f=p.raw+`
|
|
280
|
+
`+t.join(`
|
|
281
|
+
`),g=this.list(f);r[r.length-1]=g,s=s.substring(0,s.length-d.raw.length)+g.raw,i=i.substring(0,i.length-p.raw.length)+g.raw,t=f.substring(r.at(-1).raw.length).split(`
|
|
282
|
+
`);continue}}return{type:"blockquote",raw:s,tokens:r,text:i}}}list(n){let e=this.rules.block.list.exec(n);if(e){let t=e[1].trim(),s=t.length>1,i={type:"list",raw:"",ordered:s,start:s?+t.slice(0,-1):"",loose:!1,items:[]};t=s?`\\d{1,9}\\${t.slice(-1)}`:`\\${t}`,this.options.pedantic&&(t=s?t:"[*+-]");let r=this.rules.other.listItemRegex(t),o=!1;for(;n;){let a=!1,c="",h="";if(!(e=r.exec(n))||this.rules.block.hr.test(n))break;c=e[0],n=n.substring(c.length);let u=e[2].split(`
|
|
283
|
+
`,1)[0].replace(this.rules.other.listReplaceTabs,x=>" ".repeat(3*x.length)),d=n.split(`
|
|
284
|
+
`,1)[0],p=!u.trim(),f=0;if(this.options.pedantic?(f=2,h=u.trimStart()):p?f=e[1].length+1:(f=e[2].search(this.rules.other.nonSpaceChar),f=f>4?1:f,h=u.slice(f),f+=e[1].length),p&&this.rules.other.blankLine.test(d)&&(c+=d+`
|
|
285
|
+
`,n=n.substring(d.length+1),a=!0),!a){let x=this.rules.other.nextBulletRegex(f),T=this.rules.other.hrRegex(f),I=this.rules.other.fencesBeginRegex(f),D=this.rules.other.headingBeginRegex(f),R=this.rules.other.htmlBeginRegex(f);for(;n;){let v=n.split(`
|
|
286
|
+
`,1)[0],$;if(d=v,this.options.pedantic?(d=d.replace(this.rules.other.listReplaceNesting," "),$=d):$=d.replace(this.rules.other.tabCharGlobal," "),I.test(d)||D.test(d)||R.test(d)||x.test(d)||T.test(d))break;if($.search(this.rules.other.nonSpaceChar)>=f||!d.trim())h+=`
|
|
287
|
+
`+$.slice(f);else{if(p||u.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||I.test(u)||D.test(u)||T.test(u))break;h+=`
|
|
288
|
+
`+d}!p&&!d.trim()&&(p=!0),c+=v+`
|
|
289
|
+
`,n=n.substring(v.length+1),u=$.slice(f)}}i.loose||(o?i.loose=!0:this.rules.other.doubleBlankLine.test(c)&&(o=!0));let g=null,m;this.options.gfm&&(g=this.rules.other.listIsTask.exec(h),g&&(m=g[0]!=="[ ] ",h=h.replace(this.rules.other.listReplaceTask,""))),i.items.push({type:"list_item",raw:c,task:!!g,checked:m,loose:!1,text:h,tokens:[]}),i.raw+=c}let l=i.items.at(-1);if(l)l.raw=l.raw.trimEnd(),l.text=l.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let a=0;a<i.items.length;a++)if(this.lexer.state.top=!1,i.items[a].tokens=this.lexer.blockTokens(i.items[a].text,[]),!i.loose){let c=i.items[a].tokens.filter(u=>u.type==="space"),h=c.length>0&&c.some(u=>this.rules.other.anyLine.test(u.raw));i.loose=h}if(i.loose)for(let a=0;a<i.items.length;a++)i.items[a].loose=!0;return i}}html(n){let e=this.rules.block.html.exec(n);if(e)return{type:"html",block:!0,raw:e[0],pre:e[1]==="pre"||e[1]==="script"||e[1]==="style",text:e[0]}}def(n){let e=this.rules.block.def.exec(n);if(e){let t=e[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),s=e[2]?e[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",i=e[3]?e[3].substring(1,e[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):e[3];return{type:"def",tag:t,raw:e[0],href:s,title:i}}}table(n){let e=this.rules.block.table.exec(n);if(!e||!this.rules.other.tableDelimiter.test(e[2]))return;let t=fi(e[1]),s=e[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=e[3]?.trim()?e[3].replace(this.rules.other.tableRowBlankLine,"").split(`
|
|
290
|
+
`):[],r={type:"table",raw:e[0],header:[],align:[],rows:[]};if(t.length===s.length){for(let o of s)this.rules.other.tableAlignRight.test(o)?r.align.push("right"):this.rules.other.tableAlignCenter.test(o)?r.align.push("center"):this.rules.other.tableAlignLeft.test(o)?r.align.push("left"):r.align.push(null);for(let o=0;o<t.length;o++)r.header.push({text:t[o],tokens:this.lexer.inline(t[o]),header:!0,align:r.align[o]});for(let o of i)r.rows.push(fi(o,r.header.length).map((l,a)=>({text:l,tokens:this.lexer.inline(l),header:!1,align:r.align[a]})));return r}}lheading(n){let e=this.rules.block.lheading.exec(n);if(e)return{type:"heading",raw:e[0],depth:e[2].charAt(0)==="="?1:2,text:e[1],tokens:this.lexer.inline(e[1])}}paragraph(n){let e=this.rules.block.paragraph.exec(n);if(e){let t=e[1].charAt(e[1].length-1)===`
|
|
291
|
+
`?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:t,tokens:this.lexer.inline(t)}}}text(n){let e=this.rules.block.text.exec(n);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(n){let e=this.rules.inline.escape.exec(n);if(e)return{type:"escape",raw:e[0],text:e[1]}}tag(n){let e=this.rules.inline.tag.exec(n);if(e)return!this.lexer.state.inLink&&this.rules.other.startATag.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:e[0]}}link(n){let e=this.rules.inline.link.exec(n);if(e){let t=e[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(t)){if(!this.rules.other.endAngleBracket.test(t))return;let r=Qe(t.slice(0,-1),"\\");if((t.length-r.length)%2===0)return}else{let r=ca(e[2],"()");if(r===-2)return;if(r>-1){let l=(e[0].indexOf("!")===0?5:4)+e[1].length+r;e[2]=e[2].substring(0,r),e[0]=e[0].substring(0,l).trim(),e[3]=""}}let s=e[2],i="";if(this.options.pedantic){let r=this.rules.other.pedanticHrefTitle.exec(s);r&&(s=r[1],i=r[3])}else i=e[3]?e[3].slice(1,-1):"";return s=s.trim(),this.rules.other.startAngleBracket.test(s)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(t)?s=s.slice(1):s=s.slice(1,-1)),gi(e,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:i&&i.replace(this.rules.inline.anyPunctuation,"$1")},e[0],this.lexer,this.rules)}}reflink(n,e){let t;if((t=this.rules.inline.reflink.exec(n))||(t=this.rules.inline.nolink.exec(n))){let s=(t[2]||t[1]).replace(this.rules.other.multipleSpaceGlobal," "),i=e[s.toLowerCase()];if(!i){let r=t[0].charAt(0);return{type:"text",raw:r,text:r}}return gi(t,i,t[0],this.lexer,this.rules)}}emStrong(n,e,t=""){let s=this.rules.inline.emStrongLDelim.exec(n);if(!s||s[3]&&t.match(this.rules.other.unicodeAlphaNumeric))return;if(!(s[1]||s[2]||"")||!t||this.rules.inline.punctuation.exec(t)){let r=[...s[0]].length-1,o,l,a=r,c=0,h=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(h.lastIndex=0,e=e.slice(-1*n.length+r);(s=h.exec(e))!=null;){if(o=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!o)continue;if(l=[...o].length,s[3]||s[4]){a+=l;continue}else if((s[5]||s[6])&&r%3&&!((r+l)%3)){c+=l;continue}if(a-=l,a>0)continue;l=Math.min(l,l+a+c);let u=[...s[0]][0].length,d=n.slice(0,r+s.index+u+l);if(Math.min(r,l)%2){let f=d.slice(1,-1);return{type:"em",raw:d,text:f,tokens:this.lexer.inlineTokens(f)}}let p=d.slice(2,-2);return{type:"strong",raw:d,text:p,tokens:this.lexer.inlineTokens(p)}}}}codespan(n){let e=this.rules.inline.code.exec(n);if(e){let t=e[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(t),i=this.rules.other.startingSpaceChar.test(t)&&this.rules.other.endingSpaceChar.test(t);return s&&i&&(t=t.substring(1,t.length-1)),{type:"codespan",raw:e[0],text:t}}}br(n){let e=this.rules.inline.br.exec(n);if(e)return{type:"br",raw:e[0]}}del(n){let e=this.rules.inline.del.exec(n);if(e)return{type:"del",raw:e[0],text:e[2],tokens:this.lexer.inlineTokens(e[2])}}autolink(n){let e=this.rules.inline.autolink.exec(n);if(e){let t,s;return e[2]==="@"?(t=e[1],s="mailto:"+t):(t=e[1],s=t),{type:"link",raw:e[0],text:t,href:s,tokens:[{type:"text",raw:t,text:t}]}}}url(n){let e;if(e=this.rules.inline.url.exec(n)){let t,s;if(e[2]==="@")t=e[0],s="mailto:"+t;else{let i;do i=e[0],e[0]=this.rules.inline._backpedal.exec(e[0])?.[0]??"";while(i!==e[0]);t=e[0],e[1]==="www."?s="http://"+e[0]:s=e[0]}return{type:"link",raw:e[0],text:t,href:s,tokens:[{type:"text",raw:t,text:t}]}}}inlineText(n){let e=this.rules.inline.text.exec(n);if(e){let t=this.lexer.state.inRawBlock;return{type:"text",raw:e[0],text:e[0],escaped:t}}}},oe=class xn{tokens;options;state;tokenizer;inlineQueue;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||Ce,this.options.tokenizer=this.options.tokenizer||new Me,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={other:U,block:St.normal,inline:Xe.normal};this.options.pedantic?(t.block=St.pedantic,t.inline=Xe.pedantic):this.options.gfm&&(t.block=St.gfm,this.options.breaks?t.inline=Xe.breaks:t.inline=Xe.gfm),this.tokenizer.rules=t}static get rules(){return{block:St,inline:Xe}}static lex(e,t){return new xn(t).lex(e)}static lexInline(e,t){return new xn(t).inlineTokens(e)}lex(e){e=e.replace(U.carriageReturn,`
|
|
292
|
+
`),this.blockTokens(e,this.tokens);for(let t=0;t<this.inlineQueue.length;t++){let s=this.inlineQueue[t];this.inlineTokens(s.src,s.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],s=!1){for(this.options.pedantic&&(e=e.replace(U.tabCharGlobal," ").replace(U.spaceLine,""));e;){let i;if(this.options.extensions?.block?.some(o=>(i=o.call({lexer:this},e,t))?(e=e.substring(i.raw.length),t.push(i),!0):!1))continue;if(i=this.tokenizer.space(e)){e=e.substring(i.raw.length);let o=t.at(-1);i.raw.length===1&&o!==void 0?o.raw+=`
|
|
293
|
+
`:t.push(i);continue}if(i=this.tokenizer.code(e)){e=e.substring(i.raw.length);let o=t.at(-1);o?.type==="paragraph"||o?.type==="text"?(o.raw+=`
|
|
294
|
+
`+i.raw,o.text+=`
|
|
295
|
+
`+i.text,this.inlineQueue.at(-1).src=o.text):t.push(i);continue}if(i=this.tokenizer.fences(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.heading(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.hr(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.blockquote(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.list(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.html(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.def(e)){e=e.substring(i.raw.length);let o=t.at(-1);o?.type==="paragraph"||o?.type==="text"?(o.raw+=`
|
|
296
|
+
`+i.raw,o.text+=`
|
|
297
|
+
`+i.raw,this.inlineQueue.at(-1).src=o.text):this.tokens.links[i.tag]||(this.tokens.links[i.tag]={href:i.href,title:i.title});continue}if(i=this.tokenizer.table(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.lheading(e)){e=e.substring(i.raw.length),t.push(i);continue}let r=e;if(this.options.extensions?.startBlock){let o=1/0,l=e.slice(1),a;this.options.extensions.startBlock.forEach(c=>{a=c.call({lexer:this},l),typeof a=="number"&&a>=0&&(o=Math.min(o,a))}),o<1/0&&o>=0&&(r=e.substring(0,o+1))}if(this.state.top&&(i=this.tokenizer.paragraph(r))){let o=t.at(-1);s&&o?.type==="paragraph"?(o.raw+=`
|
|
298
|
+
`+i.raw,o.text+=`
|
|
299
|
+
`+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=o.text):t.push(i),s=r.length!==e.length,e=e.substring(i.raw.length);continue}if(i=this.tokenizer.text(e)){e=e.substring(i.raw.length);let o=t.at(-1);o?.type==="text"?(o.raw+=`
|
|
300
|
+
`+i.raw,o.text+=`
|
|
301
|
+
`+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=o.text):t.push(i);continue}if(e){let o="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(o);break}else throw new Error(o)}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){let s=e,i=null;if(this.tokens.links){let l=Object.keys(this.tokens.links);if(l.length>0)for(;(i=this.tokenizer.rules.inline.reflinkSearch.exec(s))!=null;)l.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(i=this.tokenizer.rules.inline.anyPunctuation.exec(s))!=null;)s=s.slice(0,i.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);for(;(i=this.tokenizer.rules.inline.blockSkip.exec(s))!=null;)s=s.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);let r=!1,o="";for(;e;){r||(o=""),r=!1;let l;if(this.options.extensions?.inline?.some(c=>(l=c.call({lexer:this},e,t))?(e=e.substring(l.raw.length),t.push(l),!0):!1))continue;if(l=this.tokenizer.escape(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.tag(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.link(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(l.raw.length);let c=t.at(-1);l.type==="text"&&c?.type==="text"?(c.raw+=l.raw,c.text+=l.text):t.push(l);continue}if(l=this.tokenizer.emStrong(e,s,o)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.codespan(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.br(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.del(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.autolink(e)){e=e.substring(l.raw.length),t.push(l);continue}if(!this.state.inLink&&(l=this.tokenizer.url(e))){e=e.substring(l.raw.length),t.push(l);continue}let a=e;if(this.options.extensions?.startInline){let c=1/0,h=e.slice(1),u;this.options.extensions.startInline.forEach(d=>{u=d.call({lexer:this},h),typeof u=="number"&&u>=0&&(c=Math.min(c,u))}),c<1/0&&c>=0&&(a=e.substring(0,c+1))}if(l=this.tokenizer.inlineText(a)){e=e.substring(l.raw.length),l.raw.slice(-1)!=="_"&&(o=l.raw.slice(-1)),r=!0;let c=t.at(-1);c?.type==="text"?(c.raw+=l.raw,c.text+=l.text):t.push(l);continue}if(e){let c="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(c);break}else throw new Error(c)}}return t}},It=class{options;parser;constructor(n){this.options=n||Ce}space(n){return""}code({text:n,lang:e,escaped:t}){let s=(e||"").match(U.notSpaceStart)?.[0],i=n.replace(U.endingNewline,"")+`
|
|
302
|
+
`;return s?'<pre><code class="language-'+te(s)+'">'+(t?i:te(i,!0))+`</code></pre>
|
|
303
|
+
`:"<pre><code>"+(t?i:te(i,!0))+`</code></pre>
|
|
304
|
+
`}blockquote({tokens:n}){return`<blockquote>
|
|
305
|
+
${this.parser.parse(n)}</blockquote>
|
|
306
|
+
`}html({text:n}){return n}heading({tokens:n,depth:e}){return`<h${e}>${this.parser.parseInline(n)}</h${e}>
|
|
307
|
+
`}hr(n){return`<hr>
|
|
308
|
+
`}list(n){let e=n.ordered,t=n.start,s="";for(let o=0;o<n.items.length;o++){let l=n.items[o];s+=this.listitem(l)}let i=e?"ol":"ul",r=e&&t!==1?' start="'+t+'"':"";return"<"+i+r+`>
|
|
309
|
+
`+s+"</"+i+`>
|
|
310
|
+
`}listitem(n){let e="";if(n.task){let t=this.checkbox({checked:!!n.checked});n.loose?n.tokens[0]?.type==="paragraph"?(n.tokens[0].text=t+" "+n.tokens[0].text,n.tokens[0].tokens&&n.tokens[0].tokens.length>0&&n.tokens[0].tokens[0].type==="text"&&(n.tokens[0].tokens[0].text=t+" "+te(n.tokens[0].tokens[0].text),n.tokens[0].tokens[0].escaped=!0)):n.tokens.unshift({type:"text",raw:t+" ",text:t+" ",escaped:!0}):e+=t+" "}return e+=this.parser.parse(n.tokens,!!n.loose),`<li>${e}</li>
|
|
311
|
+
`}checkbox({checked:n}){return"<input "+(n?'checked="" ':"")+'disabled="" type="checkbox">'}paragraph({tokens:n}){return`<p>${this.parser.parseInline(n)}</p>
|
|
312
|
+
`}table(n){let e="",t="";for(let i=0;i<n.header.length;i++)t+=this.tablecell(n.header[i]);e+=this.tablerow({text:t});let s="";for(let i=0;i<n.rows.length;i++){let r=n.rows[i];t="";for(let o=0;o<r.length;o++)t+=this.tablecell(r[o]);s+=this.tablerow({text:t})}return s&&(s=`<tbody>${s}</tbody>`),`<table>
|
|
313
|
+
<thead>
|
|
314
|
+
`+e+`</thead>
|
|
315
|
+
`+s+`</table>
|
|
316
|
+
`}tablerow({text:n}){return`<tr>
|
|
317
|
+
${n}</tr>
|
|
318
|
+
`}tablecell(n){let e=this.parser.parseInline(n.tokens),t=n.header?"th":"td";return(n.align?`<${t} align="${n.align}">`:`<${t}>`)+e+`</${t}>
|
|
319
|
+
`}strong({tokens:n}){return`<strong>${this.parser.parseInline(n)}</strong>`}em({tokens:n}){return`<em>${this.parser.parseInline(n)}</em>`}codespan({text:n}){return`<code>${te(n,!0)}</code>`}br(n){return"<br>"}del({tokens:n}){return`<del>${this.parser.parseInline(n)}</del>`}link({href:n,title:e,tokens:t}){let s=this.parser.parseInline(t),i=pi(n);if(i===null)return s;n=i;let r='<a href="'+n+'"';return e&&(r+=' title="'+te(e)+'"'),r+=">"+s+"</a>",r}image({href:n,title:e,text:t,tokens:s}){s&&(t=this.parser.parseInline(s,this.parser.textRenderer));let i=pi(n);if(i===null)return te(t);n=i;let r=`<img src="${n}" alt="${t}"`;return e&&(r+=` title="${te(e)}"`),r+=">",r}text(n){return"tokens"in n&&n.tokens?this.parser.parseInline(n.tokens):"escaped"in n&&n.escaped?n.text:te(n.text)}},Ln=class{strong({text:n}){return n}em({text:n}){return n}codespan({text:n}){return n}del({text:n}){return n}html({text:n}){return n}text({text:n}){return n}link({text:n}){return""+n}image({text:n}){return""+n}br(){return""}},ae=class yn{options;renderer;textRenderer;constructor(e){this.options=e||Ce,this.options.renderer=this.options.renderer||new It,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Ln}static parse(e,t){return new yn(t).parse(e)}static parseInline(e,t){return new yn(t).parseInline(e)}parse(e,t=!0){let s="";for(let i=0;i<e.length;i++){let r=e[i];if(this.options.extensions?.renderers?.[r.type]){let l=r,a=this.options.extensions.renderers[l.type].call({parser:this},l);if(a!==!1||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(l.type)){s+=a||"";continue}}let o=r;switch(o.type){case"space":{s+=this.renderer.space(o);continue}case"hr":{s+=this.renderer.hr(o);continue}case"heading":{s+=this.renderer.heading(o);continue}case"code":{s+=this.renderer.code(o);continue}case"table":{s+=this.renderer.table(o);continue}case"blockquote":{s+=this.renderer.blockquote(o);continue}case"list":{s+=this.renderer.list(o);continue}case"html":{s+=this.renderer.html(o);continue}case"paragraph":{s+=this.renderer.paragraph(o);continue}case"text":{let l=o,a=this.renderer.text(l);for(;i+1<e.length&&e[i+1].type==="text";)l=e[++i],a+=`
|
|
320
|
+
`+this.renderer.text(l);t?s+=this.renderer.paragraph({type:"paragraph",raw:a,text:a,tokens:[{type:"text",raw:a,text:a,escaped:!0}]}):s+=a;continue}default:{let l='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(l),"";throw new Error(l)}}}return s}parseInline(e,t=this.renderer){let s="";for(let i=0;i<e.length;i++){let r=e[i];if(this.options.extensions?.renderers?.[r.type]){let l=this.options.extensions.renderers[r.type].call({parser:this},r);if(l!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(r.type)){s+=l||"";continue}}let o=r;switch(o.type){case"escape":{s+=t.text(o);break}case"html":{s+=t.html(o);break}case"link":{s+=t.link(o);break}case"image":{s+=t.image(o);break}case"strong":{s+=t.strong(o);break}case"em":{s+=t.em(o);break}case"codespan":{s+=t.codespan(o);break}case"br":{s+=t.br(o);break}case"del":{s+=t.del(o);break}case"text":{s+=t.text(o);break}default:{let l='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(l),"";throw new Error(l)}}}return s}},wt=class{options;block;constructor(n){this.options=n||Ce}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(n){return n}postprocess(n){return n}processAllTokens(n){return n}provideLexer(){return this.block?oe.lex:oe.lexInline}provideParser(){return this.block?ae.parse:ae.parseInline}},Rn=class{defaults=vn();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=ae;Renderer=It;TextRenderer=Ln;Lexer=oe;Tokenizer=Me;Hooks=wt;constructor(...n){this.use(...n)}walkTokens(n,e){let t=[];for(let s of n)switch(t=t.concat(e.call(this,s)),s.type){case"table":{let i=s;for(let r of i.header)t=t.concat(this.walkTokens(r.tokens,e));for(let r of i.rows)for(let o of r)t=t.concat(this.walkTokens(o.tokens,e));break}case"list":{let i=s;t=t.concat(this.walkTokens(i.items,e));break}default:{let i=s;this.defaults.extensions?.childTokens?.[i.type]?this.defaults.extensions.childTokens[i.type].forEach(r=>{let o=i[r].flat(1/0);t=t.concat(this.walkTokens(o,e))}):i.tokens&&(t=t.concat(this.walkTokens(i.tokens,e)))}}return t}use(...n){let e=this.defaults.extensions||{renderers:{},childTokens:{}};return n.forEach(t=>{let s={...t};if(s.async=this.defaults.async||s.async||!1,t.extensions&&(t.extensions.forEach(i=>{if(!i.name)throw new Error("extension name required");if("renderer"in i){let r=e.renderers[i.name];r?e.renderers[i.name]=function(...o){let l=i.renderer.apply(this,o);return l===!1&&(l=r.apply(this,o)),l}:e.renderers[i.name]=i.renderer}if("tokenizer"in i){if(!i.level||i.level!=="block"&&i.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let r=e[i.level];r?r.unshift(i.tokenizer):e[i.level]=[i.tokenizer],i.start&&(i.level==="block"?e.startBlock?e.startBlock.push(i.start):e.startBlock=[i.start]:i.level==="inline"&&(e.startInline?e.startInline.push(i.start):e.startInline=[i.start]))}"childTokens"in i&&i.childTokens&&(e.childTokens[i.name]=i.childTokens)}),s.extensions=e),t.renderer){let i=this.defaults.renderer||new It(this.defaults);for(let r in t.renderer){if(!(r in i))throw new Error(`renderer '${r}' does not exist`);if(["options","parser"].includes(r))continue;let o=r,l=t.renderer[o],a=i[o];i[o]=(...c)=>{let h=l.apply(i,c);return h===!1&&(h=a.apply(i,c)),h||""}}s.renderer=i}if(t.tokenizer){let i=this.defaults.tokenizer||new Me(this.defaults);for(let r in t.tokenizer){if(!(r in i))throw new Error(`tokenizer '${r}' does not exist`);if(["options","rules","lexer"].includes(r))continue;let o=r,l=t.tokenizer[o],a=i[o];i[o]=(...c)=>{let h=l.apply(i,c);return h===!1&&(h=a.apply(i,c)),h}}s.tokenizer=i}if(t.hooks){let i=this.defaults.hooks||new wt;for(let r in t.hooks){if(!(r in i))throw new Error(`hook '${r}' does not exist`);if(["options","block"].includes(r))continue;let o=r,l=t.hooks[o],a=i[o];wt.passThroughHooks.has(r)?i[o]=c=>{if(this.defaults.async)return Promise.resolve(l.call(i,c)).then(u=>a.call(i,u));let h=l.call(i,c);return a.call(i,h)}:i[o]=(...c)=>{let h=l.apply(i,c);return h===!1&&(h=a.apply(i,c)),h}}s.hooks=i}if(t.walkTokens){let i=this.defaults.walkTokens,r=t.walkTokens;s.walkTokens=function(o){let l=[];return l.push(r.call(this,o)),i&&(l=l.concat(i.call(this,o))),l}}this.defaults={...this.defaults,...s}}),this}setOptions(n){return this.defaults={...this.defaults,...n},this}lexer(n,e){return oe.lex(n,e??this.defaults)}parser(n,e){return ae.parse(n,e??this.defaults)}parseMarkdown(n){return(t,s)=>{let i={...s},r={...this.defaults,...i},o=this.onError(!!r.silent,!!r.async);if(this.defaults.async===!0&&i.async===!1)return o(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return o(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));r.hooks&&(r.hooks.options=r,r.hooks.block=n);let l=r.hooks?r.hooks.provideLexer():n?oe.lex:oe.lexInline,a=r.hooks?r.hooks.provideParser():n?ae.parse:ae.parseInline;if(r.async)return Promise.resolve(r.hooks?r.hooks.preprocess(t):t).then(c=>l(c,r)).then(c=>r.hooks?r.hooks.processAllTokens(c):c).then(c=>r.walkTokens?Promise.all(this.walkTokens(c,r.walkTokens)).then(()=>c):c).then(c=>a(c,r)).then(c=>r.hooks?r.hooks.postprocess(c):c).catch(o);try{r.hooks&&(t=r.hooks.preprocess(t));let c=l(t,r);r.hooks&&(c=r.hooks.processAllTokens(c)),r.walkTokens&&this.walkTokens(c,r.walkTokens);let h=a(c,r);return r.hooks&&(h=r.hooks.postprocess(h)),h}catch(c){return o(c)}}}onError(n,e){return t=>{if(t.message+=`
|
|
321
|
+
Please report this to https://github.com/markedjs/marked.`,n){let s="<p>An error occurred:</p><pre>"+te(t.message+"",!0)+"</pre>";return e?Promise.resolve(s):s}if(e)return Promise.reject(t);throw t}}},ke=new Rn;function _(n,e){return ke.parse(n,e)}_.options=_.setOptions=function(n){return ke.setOptions(n),_.defaults=ke.defaults,mi(_.defaults),_};_.getDefaults=vn;_.defaults=Ce;_.use=function(...n){return ke.use(...n),_.defaults=ke.defaults,mi(_.defaults),_};_.walkTokens=function(n,e){return ke.walkTokens(n,e)};_.parseInline=ke.parseInline;_.Parser=ae;_.parser=ae.parse;_.Renderer=It;_.TextRenderer=Ln;_.Lexer=oe;_.lexer=oe.lex;_.Tokenizer=Me;_.Hooks=wt;_.parse=_;var du=_.options,pu=_.setOptions,fu=_.use,gu=_.walkTokens,mu=_.parseInline;var bu=ae.parse,xu=oe.lex;var ha=/^(~~)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,Pn=class extends Me{del(e){let t=ha.exec(e);if(!t)return;let s=t[2];return{type:"del",raw:t[0],text:s,tokens:this.lexer.inlineTokens(s)}}},$i=new Rn;$i.setOptions({tokenizer:new Pn});var et=class{constructor(e,t,s,i,r,o){this.text=e,this.paddingX=t,this.paddingY=s,this.theme=i,this.defaultTextStyle=r,this.options=o?{...o}:{}}setText(e){this.text=e,this.invalidate()}invalidate(){this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}render(e){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===e)return this.cachedLines;let t=Math.max(1,e-this.paddingX*2);if(!this.text||this.text.trim()===""){let f=[];return this.cachedText=this.text,this.cachedWidth=e,this.cachedLines=f,f}let s=this.text.replace(/\t/g," "),i=$i.lexer(s),r=[];for(let f=0;f<i.length;f++){let g=i[f],m=i[f+1],x=this.renderToken(g,t,m?.type);for(let T of x)r.push(T)}let o=[];for(let f of r)if(be(f))o.push(f);else for(let g of Q(f,t))o.push(g);let l=" ".repeat(this.paddingX),a=" ".repeat(this.paddingX),c=this.defaultTextStyle?.bgColor,h=[];for(let f of o){if(be(f)){h.push(f);continue}let g=l+f+a;if(c)h.push(ye(g,e,c));else{let m=C(g),x=Math.max(0,e-m);h.push(g+" ".repeat(x))}}let u=" ".repeat(e),d=[];for(let f=0;f<this.paddingY;f++){let g=c?ye(u,e,c):u;d.push(g)}let p=d.concat(h,d);return this.cachedText=this.text,this.cachedWidth=e,this.cachedLines=p,p.length>0?p:[""]}applyDefaultStyle(e){if(!this.defaultTextStyle)return e;let t=e;return this.defaultTextStyle.color&&(t=this.defaultTextStyle.color(t)),this.defaultTextStyle.bold&&(t=this.theme.bold(t)),this.defaultTextStyle.italic&&(t=this.theme.italic(t)),this.defaultTextStyle.strikethrough&&(t=this.theme.strikethrough(t)),this.defaultTextStyle.underline&&(t=this.theme.underline(t)),t}getDefaultStylePrefix(){if(!this.defaultTextStyle)return"";if(this.defaultStylePrefix!==void 0)return this.defaultStylePrefix;let e="\0",t=e;this.defaultTextStyle.color&&(t=this.defaultTextStyle.color(t)),this.defaultTextStyle.bold&&(t=this.theme.bold(t)),this.defaultTextStyle.italic&&(t=this.theme.italic(t)),this.defaultTextStyle.strikethrough&&(t=this.theme.strikethrough(t)),this.defaultTextStyle.underline&&(t=this.theme.underline(t));let s=t.indexOf(e);return this.defaultStylePrefix=s>=0?t.slice(0,s):"",this.defaultStylePrefix}getStylePrefix(e){let s=e("\0"),i=s.indexOf("\0");return i>=0?s.slice(0,i):""}getDefaultInlineStyleContext(){return{applyText:e=>this.applyDefaultStyle(e),stylePrefix:this.getDefaultStylePrefix()}}renderToken(e,t,s,i){let r=[];switch(e.type){case"heading":{let o=e.depth,l=`${"#".repeat(o)} `,a;o===1?a=d=>this.theme.heading(this.theme.bold(this.theme.underline(d))):a=d=>this.theme.heading(this.theme.bold(d));let c={applyText:a,stylePrefix:this.getStylePrefix(a)},h=this.renderInlineTokens(e.tokens||[],c),u=o>=3?a(l)+h:h;r.push(u),s&&s!=="space"&&r.push("");break}case"paragraph":{let o=this.renderInlineTokens(e.tokens||[],i);r.push(o),s&&s!=="list"&&s!=="space"&&r.push("");break}case"text":r.push(this.renderInlineTokens([e],i));break;case"code":{let o=this.theme.codeBlockIndent??" ";if(r.push(this.theme.codeBlockBorder(`\`\`\`${e.lang||""}`)),this.theme.highlightCode){let l=this.theme.highlightCode(e.text,e.lang);for(let a of l)r.push(`${o}${a}`)}else{let l=e.text.split(`
|
|
322
|
+
`);for(let a of l)r.push(`${o}${this.theme.codeBlock(a)}`)}r.push(this.theme.codeBlockBorder("```")),s&&s!=="space"&&r.push("");break}case"list":{let o=this.renderList(e,0,t,i);r.push(...o);break}case"table":{let o=this.renderTable(e,t,s,i);r.push(...o);break}case"blockquote":{let o=p=>this.theme.quote(this.theme.italic(p)),l=this.getStylePrefix(o),a=p=>{if(!l)return o(p);let f=p.replace(/\x1b\[0m/g,`\x1B[0m${l}`);return o(f)},c=Math.max(1,t-2),h={applyText:p=>p,stylePrefix:l},u=e.tokens||[],d=[];for(let p=0;p<u.length;p++){let f=u[p],g=u[p+1];d.push(...this.renderToken(f,c,g?.type,h))}for(;d.length>0&&d[d.length-1]==="";)d.pop();for(let p of d){let f=a(p),g=Q(f,c);for(let m of g)r.push(this.theme.quoteBorder("\u2502 ")+m)}s&&s!=="space"&&r.push("");break}case"hr":r.push(this.theme.hr("\u2500".repeat(Math.min(t,80)))),s&&s!=="space"&&r.push("");break;case"html":"raw"in e&&typeof e.raw=="string"&&r.push(this.applyDefaultStyle(e.raw.trim()));break;case"space":r.push("");break;default:"text"in e&&typeof e.text=="string"&&r.push(e.text)}return r}renderInlineTokens(e,t){let s="",i=t??this.getDefaultInlineStyleContext(),{applyText:r,stylePrefix:o}=i,l=a=>a.split(`
|
|
323
|
+
`).map(h=>r(h)).join(`
|
|
324
|
+
`);for(let a of e)switch(a.type){case"text":a.tokens&&a.tokens.length>0?s+=this.renderInlineTokens(a.tokens,i):s+=l(a.text);break;case"paragraph":s+=this.renderInlineTokens(a.tokens||[],i);break;case"strong":{let c=this.renderInlineTokens(a.tokens||[],i);s+=this.theme.bold(c)+o;break}case"em":{let c=this.renderInlineTokens(a.tokens||[],i);s+=this.theme.italic(c)+o;break}case"codespan":s+=this.theme.code(a.text)+o;break;case"link":{let c=this.renderInlineTokens(a.tokens||[],i),h=this.theme.link(this.theme.underline(c));if(ue().hyperlinks)s+=Qt(h,a.href)+o;else{let u=a.href.startsWith("mailto:")?a.href.slice(7):a.href;a.text===a.href||a.text===u?s+=h+o:s+=h+this.theme.linkUrl(` (${a.href})`)+o}break}case"br":s+=`
|
|
325
|
+
`;break;case"del":{let c=this.renderInlineTokens(a.tokens||[],i);s+=this.theme.strikethrough(c)+o;break}case"html":"raw"in a&&typeof a.raw=="string"&&(s+=l(a.raw));break;default:"text"in a&&typeof a.text=="string"&&(s+=l(a.text))}for(;o&&s.endsWith(o);)s=s.slice(0,-o.length);return s}getOrderedListMarker(e){let t=/^(?: {0,3})(\d{1,9}[.)])[ \t]+/.exec(e.raw);return t?`${t[1]} `:void 0}renderList(e,t,s,i){let r=[],o=" ".repeat(t),l=typeof e.start=="number"?e.start:1;for(let a=0;a<e.items.length;a++){let c=e.items[a],h=e.ordered?this.options.preserveOrderedListMarkers?this.getOrderedListMarker(c)??`${l+a}. `:`${l+a}. `:"- ",u=c.task?`[${c.checked?"x":" "}] `:"",d=h+u,p=o+this.theme.listBullet(d),f=o+" ".repeat(C(d)),g=Math.max(1,s-C(p)),m=!1;for(let x of c.tokens){if(x.type==="list"){r.push(...this.renderList(x,t+1,s,i)),m=!0;continue}let T=this.renderToken(x,g,void 0,i);for(let I of T)for(let D of Q(I,g)){let R=m?f:p;r.push(R+D),m=!0}}m||r.push(p)}return r}getLongestWordWidth(e,t){let s=e.split(/\s+/).filter(r=>r.length>0),i=0;for(let r of s)i=Math.max(i,C(r));return t===void 0?i:Math.min(i,t)}wrapCellText(e,t){return Q(e,Math.max(1,t))}renderTable(e,t,s,i){let r=[],o=e.header.length;if(o===0)return r;let l=3*o+1,a=t-l;if(a<o){let v=e.raw?Q(e.raw,t):[];return s&&s!=="space"&&v.push(""),v}let c=30,h=[],u=[];for(let v=0;v<o;v++){let $=this.renderInlineTokens(e.header[v].tokens||[],i);h[v]=C($),u[v]=Math.max(1,this.getLongestWordWidth($,c))}for(let v of e.rows)for(let $=0;$<v.length;$++){let B=this.renderInlineTokens(v[$].tokens||[],i);h[$]=Math.max(h[$]||0,C(B)),u[$]=Math.max(u[$]||1,this.getLongestWordWidth(B,c))}let d=u,p=d.reduce((v,$)=>v+$,0);if(p>a){d=new Array(o).fill(1);let v=a-o;if(v>0){let $=u.reduce((b,S)=>b+Math.max(0,S-1),0),B=u.map(b=>{let S=Math.max(0,b-1);return $>0?Math.floor(S/$*v):0});for(let b=0;b<o;b++)d[b]+=B[b]??0;let F=B.reduce((b,S)=>b+S,0),A=v-F;for(let b=0;A>0&&b<o;b++)d[b]++,A--}p=d.reduce(($,B)=>$+B,0)}let f=h.reduce((v,$)=>v+$,0)+l,g;if(f<=t)g=h.map((v,$)=>Math.max(v,d[$]));else{let v=h.reduce((A,b,S)=>A+Math.max(0,b-d[S]),0),$=Math.max(0,a-p);g=d.map((A,b)=>{let S=h[b],W=Math.max(0,S-A),P=0;return v>0&&(P=Math.floor(W/v*$)),A+P});let B=g.reduce((A,b)=>A+b,0),F=a-B;for(;F>0;){let A=!1;for(let b=0;b<o&&F>0;b++)g[b]<h[b]&&(g[b]++,F--,A=!0);if(!A)break}}let m=g.map(v=>"\u2500".repeat(v));r.push(`\u250C\u2500${m.join("\u2500\u252C\u2500")}\u2500\u2510`);let x=e.header.map((v,$)=>{let B=this.renderInlineTokens(v.tokens||[],i);return this.wrapCellText(B,g[$])}),T=Math.max(...x.map(v=>v.length));for(let v=0;v<T;v++){let $=x.map((B,F)=>{let A=B[v]||"",b=A+" ".repeat(Math.max(0,g[F]-C(A)));return this.theme.bold(b)});r.push(`\u2502 ${$.join(" \u2502 ")} \u2502`)}let D=`\u251C\u2500${g.map(v=>"\u2500".repeat(v)).join("\u2500\u253C\u2500")}\u2500\u2524`;r.push(D);for(let v=0;v<e.rows.length;v++){let B=e.rows[v].map((A,b)=>{let S=this.renderInlineTokens(A.tokens||[],i);return this.wrapCellText(S,g[b])}),F=Math.max(...B.map(A=>A.length));for(let A=0;A<F;A++){let b=B.map((S,W)=>{let P=S[A]||"";return P+" ".repeat(Math.max(0,g[W]-C(P)))});r.push(`\u2502 ${b.join(" \u2502 ")} \u2502`)}v<e.rows.length-1&&r.push(D)}let R=g.map(v=>"\u2500".repeat(v));return r.push(`\u2514\u2500${R.join("\u2500\u2534\u2500")}\u2500\u2518`),s&&s!=="space"&&r.push(""),r}};import{EventEmitter as da}from"events";var ne="\x1B",Li="\x1B[200~",Rt="\x1B[201~";function pa(n){if(!n.startsWith(ne))return"not-escape";if(n.length===1)return"incomplete";let e=n.slice(1);return e.startsWith("[")?e.startsWith("[M")?n.length>=6?"complete":"incomplete":fa(n):e.startsWith("]")?ga(n):e.startsWith("P")?ma(n):e.startsWith("_")?ba(n):e.startsWith("O")?e.length>=2?"complete":"incomplete":(e.length===1,"complete")}function fa(n){if(!n.startsWith(`${ne}[`))return"complete";if(n.length<3)return"incomplete";let e=n.slice(2),t=e[e.length-1],s=t.charCodeAt(0);if(s>=64&&s<=126){if(e.startsWith("<")){if(/^<\d+;\d+;\d+[Mm]$/.test(e))return"complete";if(t==="M"||t==="m"){let r=e.slice(1,-1).split(";");if(r.length===3&&r.every(o=>/^\d+$/.test(o)))return"complete"}return"incomplete"}return"complete"}return"incomplete"}function ga(n){return!n.startsWith(`${ne}]`)||n.endsWith(`${ne}\\`)||n.endsWith("\x07")?"complete":"incomplete"}function ma(n){return!n.startsWith(`${ne}P`)||n.endsWith(`${ne}\\`)?"complete":"incomplete"}function ba(n){return!n.startsWith(`${ne}_`)||n.endsWith(`${ne}\\`)?"complete":"incomplete"}function xa(n){let e=n.match(/^\x1b\[(\d+)(?::\d*)?(?::\d+)?u$/);if(!e)return;let t=parseInt(e[1],10);return t>=32?t:void 0}function Ri(n){let e=[],t=0;for(;t<n.length;){let s=n.slice(t);if(s.startsWith(ne)){let i=1;for(;i<=s.length;){let r=s.slice(0,i),o=pa(r);if(o==="complete"){if(r==="\x1B\x1B"){let l=s[i];if(l==="["||l==="]"||l==="O"||l==="P"||l==="_"){e.push(ne),t+=1;break}}e.push(r),t+=i;break}else if(o==="incomplete")i++;else{e.push(r),t+=i;break}}if(i>s.length)return{sequences:e,remainder:s}}else e.push(s[0]),t++}return{sequences:e,remainder:""}}var tt=class extends da{constructor(t={}){super();this.buffer="";this.timeout=null;this.pasteMode=!1;this.pasteBuffer="";this.timeoutMs=t.timeout??10}process(t){this.timeout&&(clearTimeout(this.timeout),this.timeout=null);let s;if(Buffer.isBuffer(t))if(t.length===1&&t[0]>127){let o=t[0]-128;s=`\x1B${String.fromCharCode(o)}`}else s=t.toString();else s=t;if(s.length===0&&this.buffer.length===0){this.emitDataSequence("");return}if(this.buffer+=s,this.pasteMode){this.pasteBuffer+=this.buffer,this.buffer="";let o=this.pasteBuffer.indexOf(Rt);if(o!==-1){let l=this.pasteBuffer.slice(0,o),a=this.pasteBuffer.slice(o+Rt.length);this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0,this.emit("paste",l),a.length>0&&this.process(a)}return}let i=this.buffer.indexOf(Li);if(i!==-1){if(i>0){let l=this.buffer.slice(0,i),a=Ri(l);for(let c of a.sequences)this.emitDataSequence(c)}this.pendingKittyPrintableCodepoint=void 0,this.buffer=this.buffer.slice(i+Li.length),this.pasteMode=!0,this.pasteBuffer=this.buffer,this.buffer="";let o=this.pasteBuffer.indexOf(Rt);if(o!==-1){let l=this.pasteBuffer.slice(0,o),a=this.pasteBuffer.slice(o+Rt.length);this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0,this.emit("paste",l),a.length>0&&this.process(a)}return}let r=Ri(this.buffer);this.buffer=r.remainder;for(let o of r.sequences)this.emitDataSequence(o);this.buffer.length>0&&(this.timeout=setTimeout(()=>{let o=this.flush();for(let l of o)this.emitDataSequence(l)},this.timeoutMs))}emitDataSequence(t){let s=t.length===1?t.codePointAt(0):void 0;if(s!==void 0&&s===this.pendingKittyPrintableCodepoint){this.pendingKittyPrintableCodepoint=void 0;return}this.pendingKittyPrintableCodepoint=xa(t),this.emit("data",t)}flush(){if(this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.buffer.length===0)return[];let t=[this.buffer];return this.buffer="",this.pendingKittyPrintableCodepoint=void 0,t}clear(){this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.buffer="",this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0}getBuffer(){return this.buffer}destroy(){this.clear()}};import*as At from"node:fs";import{createRequire as wa}from"node:module";import*as le from"node:path";import{fileURLToPath as Ta}from"node:url";import{createRequire as ya}from"node:module";import*as pe from"node:path";import{fileURLToPath as va}from"node:url";var ka=ya(import.meta.url),Pt;function Ca(n){return typeof n!="object"||n===null?!1:typeof n.isModifierPressed=="function"}function Sa(){if(Pt!==void 0)return Pt??void 0;if(Pt=null,process.platform!=="darwin")return;let n=process.arch;if(n!=="x64"&&n!=="arm64")return;let e=pe.dirname(va(import.meta.url)),t=pe.join("native","darwin","prebuilds",`darwin-${n}`,"darwin-modifiers.node"),s=[pe.join(e,"..",t),pe.join(e,t),pe.join(pe.dirname(process.execPath),t)];for(let i of s)try{let r=ka(i);if(Ca(r))return Pt=r,r}catch{}}function Pi(n){let e=Sa();if(!e)return!1;try{return e.isModifierPressed(n)===!0}catch{return!1}}var Ia=wa(import.meta.url),$a=1e3,Ai="\x1B]9;4;3\x07",Mi="\x1B]9;4;0;\x07",La="\x1B[13;2u",Ra=7,Pa=150,Aa=150,Ma=`\x1B[>${Ra}u\x1B[?u\x1B[c`;function Ei(n){let e=n.match(/^\x1b\[\?(\d+)u$/);if(e)return{type:"kitty-flags",flags:Number.parseInt(e[1],10)};if(/^\x1b\[\?[\d;]*c$/.test(n))return{type:"device-attributes"}}function Oi(n,e){return e&&n==="\x1B"||n==="\x1B["||/^\x1b\[\?[\d;]*$/.test(n)}function Ea(){return process.platform==="darwin"&&process.env.TERM_PROGRAM==="Apple_Terminal"}function Oa(n,e,t){return e&&n==="\r"&&t?La:n}var nt=class{constructor(){this.wasRaw=!1;this._kittyProtocolActive=!1;this._modifyOtherKeysActive=!1;this.keyboardProtocolPushed=!1;this.keyboardProtocolNegotiationPending=!1;this.keyboardProtocolLateResponsePending=!1;this.keyboardProtocolNegotiationBuffer="";this.writeLogPath=(()=>{let e=process.env.PI_TUI_WRITE_LOG||"";if(!e)return"";try{if(At.statSync(e).isDirectory()){let t=new Date,s=`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}_${String(t.getHours()).padStart(2,"0")}-${String(t.getMinutes()).padStart(2,"0")}-${String(t.getSeconds()).padStart(2,"0")}`;return le.join(e,`tui-${s}-${process.pid}.log`)}}catch{}return e})()}get kittyProtocolActive(){return this._kittyProtocolActive}start(e,t){this.inputHandler=e,this.resizeHandler=t,this.wasRaw=process.stdin.isRaw||!1,process.stdin.setRawMode&&process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),process.stdout.write("\x1B[?1049h\x1B[2J\x1B[H"),process.stdout.write("\x1B[?25l"),process.stdout.write("\x1B[?2004h"),process.stdout.on("resize",this.resizeHandler),process.platform!=="win32"&&process.kill(process.pid,"SIGWINCH"),this.enableWindowsVTInput(),this.queryAndEnableKittyProtocol()}setupStdinBuffer(){this.stdinBuffer=new tt({timeout:10}),this.stdinBuffer.on("data",e=>{if(this.keyboardProtocolNegotiationPending){let t=this.readKeyboardProtocolNegotiationSequence(e,!0);if(t==="pending"||this.handleKeyboardProtocolNegotiationSequence(t))return}if(this.keyboardProtocolLateResponsePending){let t=this.readKeyboardProtocolNegotiationSequence(e,!1);if(t==="pending"){this.scheduleKeyboardProtocolNegotiationBufferFlush();return}if(this.handleKeyboardProtocolNegotiationSequence(t))return}this.forwardInputSequence(e)}),this.stdinBuffer.on("paste",e=>{this.inputHandler&&this.inputHandler(`\x1B[200~${e}\x1B[201~`)}),this.stdinDataHandler=e=>{this.stdinBuffer.process(e)}}queryAndEnableKittyProtocol(){this.setupStdinBuffer(),process.stdin.on("data",this.stdinDataHandler),this.keyboardProtocolPushed=!0,this.keyboardProtocolNegotiationPending=!0,this.keyboardProtocolLateResponsePending=!1,this.clearKeyboardProtocolNegotiationBuffer(),process.stdout.write(Ma),this.keyboardProtocolFallbackTimer=setTimeout(()=>{this.keyboardProtocolFallbackTimer=void 0,this.keyboardProtocolNegotiationPending=!1,this.keyboardProtocolLateResponsePending=!0,this.keyboardProtocolNegotiationBuffer==="\x1B"?this.flushKeyboardProtocolNegotiationBufferAsInput():this.scheduleKeyboardProtocolNegotiationBufferFlush(),this.enableModifyOtherKeys()},Pa)}handleKeyboardProtocolNegotiationSequence(e){return e?e.type==="kitty-flags"?(e.flags!==0&&!this._kittyProtocolActive&&(this._kittyProtocolActive=!0,Ue(!0),this.keyboardProtocolNegotiationPending=!1,this.keyboardProtocolLateResponsePending=!0,this.clearKeyboardProtocolNegotiationBuffer(),this.clearKeyboardProtocolFallbackTimer()),!0):(this.keyboardProtocolNegotiationPending=!1,this.keyboardProtocolLateResponsePending=!0,this.clearKeyboardProtocolNegotiationBuffer(),this.clearKeyboardProtocolFallbackTimer(),this.enableModifyOtherKeys(),!0):!1}readKeyboardProtocolNegotiationSequence(e,t){if(this.keyboardProtocolNegotiationBuffer){let i=this.keyboardProtocolNegotiationBuffer+e,r=Ei(i);if(r)return this.clearKeyboardProtocolNegotiationBuffer(),r;if(Oi(i,t))return this.setKeyboardProtocolNegotiationBuffer(i),"pending";this.flushKeyboardProtocolNegotiationBufferAsInput()}let s=Ei(e);if(s)return s;if(Oi(e,t))return this.setKeyboardProtocolNegotiationBuffer(e),"pending"}setKeyboardProtocolNegotiationBuffer(e){this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer=e}clearKeyboardProtocolNegotiationBuffer(){this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer=""}flushKeyboardProtocolNegotiationBufferAsInput(){if(!this.keyboardProtocolNegotiationBuffer)return;let e=this.keyboardProtocolNegotiationBuffer;this.clearKeyboardProtocolNegotiationBuffer(),this.forwardInputSequence(e)}scheduleKeyboardProtocolNegotiationBufferFlush(){!this.keyboardProtocolNegotiationBuffer||this.keyboardProtocolBufferFlushTimer||(this.keyboardProtocolBufferFlushTimer=setTimeout(()=>{this.keyboardProtocolBufferFlushTimer=void 0,this.flushKeyboardProtocolNegotiationBufferAsInput()},Aa))}clearKeyboardProtocolNegotiationBufferFlushTimer(){this.keyboardProtocolBufferFlushTimer&&(clearTimeout(this.keyboardProtocolBufferFlushTimer),this.keyboardProtocolBufferFlushTimer=void 0)}forwardInputSequence(e){if(!this.inputHandler)return;let t=e==="\r"&&Ea(),s=Oa(e,t,t&&Pi("shift"));this.inputHandler(s)}enableModifyOtherKeys(){this._kittyProtocolActive||this._modifyOtherKeysActive||(process.stdout.write("\x1B[>4;2m"),this._modifyOtherKeysActive=!0)}clearKeyboardProtocolFallbackTimer(){this.keyboardProtocolFallbackTimer&&(clearTimeout(this.keyboardProtocolFallbackTimer),this.keyboardProtocolFallbackTimer=void 0)}enableWindowsVTInput(){if(process.platform==="win32")try{let e=process.arch;if(e!=="x64"&&e!=="arm64")return;let t=le.dirname(Ta(import.meta.url)),s=le.join("native","win32","prebuilds",`win32-${e}`,"win32-console-mode.node"),i=[le.join(t,"..",s),le.join(t,s),le.join(le.dirname(process.execPath),s)];for(let r of i)try{Ia(r).enableVirtualTerminalInput?.();return}catch{}}catch{}}async drainInput(e=1e3,t=50){let s=this.keyboardProtocolPushed||this._kittyProtocolActive||this.keyboardProtocolNegotiationPending;this.keyboardProtocolLateResponsePending=!1,this.clearKeyboardProtocolNegotiationBuffer(),this.clearKeyboardProtocolFallbackTimer(),s&&(process.stdout.write("\x1B[<u"),this.keyboardProtocolPushed=!1,this._kittyProtocolActive=!1,Ue(!1)),this.keyboardProtocolNegotiationPending=!1,this._modifyOtherKeysActive&&(process.stdout.write("\x1B[>4;0m"),this._modifyOtherKeysActive=!1);let i=this.inputHandler;this.inputHandler=void 0;let r=Date.now(),o=()=>{r=Date.now()};process.stdin.on("data",o);let l=Date.now()+e;try{for(;;){let a=Date.now(),c=l-a;if(c<=0||a-r>=t)break;await new Promise(h=>setTimeout(h,Math.min(t,c)))}}finally{process.stdin.removeListener("data",o),this.inputHandler=i}}stop(){this.clearProgressInterval()&&process.stdout.write(Mi),process.stdout.write("\x1B[?2004l");let e=this.keyboardProtocolPushed||this._kittyProtocolActive||this.keyboardProtocolNegotiationPending;this.keyboardProtocolLateResponsePending=!1,this.clearKeyboardProtocolNegotiationBuffer(),this.clearKeyboardProtocolFallbackTimer(),e&&(process.stdout.write("\x1B[<u"),this.keyboardProtocolPushed=!1,this._kittyProtocolActive=!1,Ue(!1)),this.keyboardProtocolNegotiationPending=!1,this._modifyOtherKeysActive&&(process.stdout.write("\x1B[>4;0m"),this._modifyOtherKeysActive=!1),this.stdinBuffer&&(this.stdinBuffer.destroy(),this.stdinBuffer=void 0),this.stdinDataHandler&&(process.stdin.removeListener("data",this.stdinDataHandler),this.stdinDataHandler=void 0),this.inputHandler=void 0,this.resizeHandler&&(process.stdout.removeListener("resize",this.resizeHandler),this.resizeHandler=void 0),process.stdin.pause(),process.stdin.setRawMode&&process.stdin.setRawMode(this.wasRaw),process.stdout.write("\x1B[?25h\x1B[?1049l")}write(e){if(process.stdout.write(e),this.writeLogPath)try{At.appendFileSync(this.writeLogPath,e,{encoding:"utf8"})}catch{}}get columns(){return process.stdout.columns||Number(process.env.COLUMNS)||80}get rows(){return process.stdout.rows||Number(process.env.LINES)||24}moveBy(e){e>0?process.stdout.write(`\x1B[${e}B`):e<0&&process.stdout.write(`\x1B[${-e}A`)}hideCursor(){process.stdout.write("\x1B[?25l")}showCursor(){process.stdout.write("\x1B[?25h")}clearLine(){process.stdout.write("\x1B[K")}clearFromCursor(){process.stdout.write("\x1B[J")}clearScreen(){process.stdout.write("\x1B[2J\x1B[H")}setTitle(e){process.stdout.write(`\x1B]0;${e}\x07`)}setProgress(e){e?(process.stdout.write(Ai),this.progressInterval||(this.progressInterval=setInterval(()=>{process.stdout.write(Ai)},$a))):(this.clearProgressInterval(),process.stdout.write(Mi))}clearProgressInterval(){return this.progressInterval?(clearInterval(this.progressInterval),this.progressInterval=void 0,!0):!1}};var _a=/\[Image #(\d+)\]/g,Mt=class{constructor(){this.map=new Map;this.nextId=1}add(e,t){let s=this.nextId++;return this.map.set(s,{id:s,base64:e,bytes:t}),s}get(e){return this.map.get(e)}idsInText(e){let t=new Set;for(let s of e.matchAll(_a)){let i=Number(s[1]);Number.isFinite(i)&&t.add(i)}return[...t]}snapshot(){return[...this.map.values()].sort((e,t)=>e.id-t.id)}clear(){this.map.clear()}};var Et=class{constructor(){this.cols=[]}setColumns(e){this.cols=e}invalidate(){for(let e of this.cols)e.component.invalidate?.()}render(e){if(this.cols.length===0)return[];let t=1,s=this.cols.length-1,i=this.resolveWidths(Math.max(0,e-s*t)),r=this.cols.map((a,c)=>a.component.render(i[c])),o=Math.max(...r.map(a=>a.length),1),l=[];for(let a=0;a<o;a++){let c="";for(let h=0;h<this.cols.length;h++){let u=r[h],d=u[a]!==void 0?u[a]:" ".repeat(i[h]);c+=d,h<this.cols.length-1&&(c+="\x1B[38;2;120;120;130m\u2502\x1B[0m")}l.push(c)}return l}resolveWidths(e){let t=this.cols.reduce((a,c)=>a+(c.fixedWidth??0),0),s=Math.max(0,e-t),i=this.cols.reduce((a,c)=>a+(c.fixedWidth!==void 0?0:c.flex??1),0),r=this.cols.map(a=>a.fixedWidth!==void 0?a.fixedWidth:Math.floor(s*(a.flex??1)/i)),o=r.reduce((a,c)=>a+c,0),l=e-o;if(l!==0){for(let a=r.length-1;a>=0;a--)if(this.cols[a].fixedWidth===void 0){r[a]+=l;break}}return r}};var _i="\x1B[0m",Ba="\x1B[1m",Ka="\x1B[2m";function Da(n){let e=parseInt(n.slice(1,3),16),t=parseInt(n.slice(3,5),16),s=parseInt(n.slice(5,7),16);return`\x1B[38;2;${e};${t};${s}m`}var Wa=Da("#79c0ff"),Ot=class{constructor(){this.focused=!1;this.lines=[];this.scrollOffset=0;this.manualScroll=!1;this.width=0;this.height=0;this.title="cc-agents \u5E2E\u52A9"}setContent(e,t,s,i){this.width=t,this.height=s,i&&(this.title=i);let r=Math.max(10,t-4);this.lines=Q(e,r),this.scrollOffset=0,this.manualScroll=!1}isAtBottom(){return this.scrollOffset===0}scrollUp(){this.manualScroll=!0,this.scrollOffset+=5}scrollDown(){this.scrollOffset=Math.max(0,this.scrollOffset-5),this.scrollOffset===0&&(this.manualScroll=!1)}scrollToTop(){this.manualScroll=!0,this.scrollOffset=this.lines.length}scrollToBottom(){this.scrollOffset=0,this.manualScroll=!1}scrollPageUp(){this.manualScroll=!0,this.scrollOffset+=Math.max(1,this.height-4)}scrollPageDown(){this.scrollOffset=Math.max(0,this.scrollOffset-Math.max(1,this.height-4)),this.scrollOffset===0&&(this.manualScroll=!1)}handleInput(e){if(N(e,j.escape)||e==="q"||e==="Q"){this.onClose?.();return}if(N(e,j.up)||e==="k"){this.scrollUp();return}if(N(e,j.down)||e==="j"){this.scrollDown();return}if(N(e,j.pageUp)){this.scrollPageUp();return}if(N(e,j.pageDown)||e===" "){this.scrollPageDown();return}if(e==="g"){this.scrollToTop();return}if(e==="G"){this.scrollToBottom();return}}invalidate(){}render(e){let t=Math.max(10,this.width||e),s=Math.max(5,this.height),i=[],r=` ${this.title} \xB7 \u2191/\u2193 \u6216 j/k \u6EDA\u52A8 \xB7 space/pgdn/pgup \u7FFB\u9875 \xB7 g/G \u8DF3\u5230\u9876/\u5E95 \xB7 Esc/q \u5173\u95ED `,o=this.renderBorderTop(t,r);i.push(o);let l=s-2,a=t-4,c=this.lines.length,u=Math.max(c,l)-this.scrollOffset-l;for(let d=0;d<l;d++){let p=u+d,f=p>=0&&p<c?this.lines[p]:"",g=C(f),m=Math.max(0,a-g);i.push(`\u2502 ${f}${" ".repeat(m)} \u2502`)}return i.push(this.renderBorderBottom(t)),i}renderBorderTop(e,t){let r=C(t),a=Math.max(0,e-1-1-r),c="\u250C\u2500",h=`${"\u2500".repeat(a)}\u2510`;return`${Wa}${Ba}${c}${t}${h}${_i}`}renderBorderBottom(e){let t=this.lines.length,s=Math.min(t,this.height-2),i=this.manualScroll?Math.max(0,t-s-this.scrollOffset)+1:t-s+1,r=t>0?` ${i}-${Math.min(t,i+s-1)}/${t} \u884C `:"",o=C(r),l=Math.max(0,Math.floor((e-2-o)/2)),a=Math.max(0,e-2-l-o),c=`${"\u2500".repeat(l)}${r}${"\u2500".repeat(a)}`;return`${Ka}\u2514${c}\u2518${_i}`}};function Ee(n){let e=parseInt(n.slice(1,3),16),t=parseInt(n.slice(3,5),16),s=parseInt(n.slice(5,7),16);return`\x1B[38;2;${e};${t};${s}m`}function Na(n){let e=parseInt(n.slice(1,3),16),t=parseInt(n.slice(3,5),16),s=parseInt(n.slice(5,7),16);return`\x1B[48;2;${e};${t};${s}m`}var O="\x1B[0m",Oe="\x1B[1m",fe="\x1B[2m",Bi="\x1B[3m",Ki="\x1B[4m",Wi="#161b22",Fa=new RegExp(`\\n${_t(fe)}\u2500\u2500 Round (\\d+) \u2500\u2500${_t(O)}\\n${_t(fe)}([^\\n]*)${_t(O)}\\n\\n`,"g");function _t(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Di=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Ni={bash:"\u{1F5A5}\uFE0F",read_file:"\u{1F4D6}",list_dir:"\u{1F4C2}",grep:"\u{1F50D}",find:"\u{1F9ED}",write_file:"\u270F\uFE0F",edit_file:"\u{1F4DD}"},Fi={bash:"Bash",read_file:"Read",list_dir:"Ls",grep:"Grep",find:"Glob",write_file:"Write",edit_file:"Edit"},ji=100,ja=Ee("#f85149");function qi(n,e){switch(n){case"bash":return String(e.command??"");case"read_file":case"list_dir":return String(e.path??"");case"grep":case"find":return String(e.pattern??"");case"write_file":case"edit_file":return String(e.path??"");default:return JSON.stringify(e)}}function An(n,e){return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function Mn(n,e,t){let s=Ni[n]??"\u{1F527}",i=Fi[n]??n,r=An(qi(n,e),ji),o=`${s} ${Oe}${i}${O}(${r})`;if(t.startsWith("Error:")){let l=t.split(`
|
|
326
|
+
`,1)[0]??t;return{text:`${o}
|
|
327
|
+
${ja}${An(l,200)}${O}
|
|
328
|
+
|
|
329
|
+
`,state:"error"}}return{text:`${o}
|
|
330
|
+
|
|
331
|
+
`,state:"complete"}}function qa(n,e,t,s){let i=Date.now()-t,r=Math.floor(i/90)%Di.length,o=Di[r],l=i/700*Math.PI*2,a=.55+.35*Math.sin(l),c=Hi(s,Wi,a),h=Ee(c),u=Ni[n]??"\u{1F527}",d=Fi[n]??n,p=An(qi(n,e),ji);return`${h}${o}${O} ${u} ${Oe}${d}${O}(${p})`}var _e=class{constructor(e,t,s,i){this.content="";this.streaming=!1;this.focused=!1;this.scrollOffset=0;this.manualScroll=!1;this.liveToolBlock=null;this.toolBlockSeq=0;this.role=e,this.label=t,this.themeColor=s,this.terminal=i,this.markdown=new et("",0,0,this.buildTheme())}buildTheme(){let e=Ee(this.themeColor),t=fe;return{heading:s=>`${e}${Oe}${s}${O}`,link:s=>`${Ki}${e}${s}${O}`,linkUrl:s=>`${t}${s}${O}`,code:s=>`${t}${s}${O}`,codeBlock:s=>`${t}${s}${O}`,codeBlockBorder:s=>`${t}${s}${O}`,quote:s=>`${Bi}${t}${s}${O}`,quoteBorder:s=>`${t}${s}${O}`,hr:s=>`${t}${s}${O}`,listBullet:s=>`${e}${s}${O}`,bold:s=>`${Oe}${s}${O}`,italic:s=>`${Bi}${s}${O}`,strikethrough:s=>`\x1B[9m${s}${O}`,underline:s=>`${Ki}${s}${O}`}}setPet(e){this.pet=e}setAvailableHeight(e){this.availableHeight=e}addBlock(e,t){let s=`
|
|
332
|
+
${fe}\u2500\u2500 Round ${e} \u2500\u2500${O}
|
|
333
|
+
${fe}${t}${O}
|
|
334
|
+
|
|
335
|
+
`;this.content+=s,this.manualScroll||(this.scrollOffset=0)}appendStreamChunk(e){this.content+=e,this.manualScroll||(this.scrollOffset=0)}appendText(e){this.content+=e,this.manualScroll||(this.scrollOffset=0)}clearContent(){this.content="",this.scrollOffset=0,this.manualScroll=!1,this.liveToolBlock=null,this.toolBlockSeq=0}toolBlockSentinel(e){return`\0TB${e}\0`}nextToolBlockId(){return++this.toolBlockSeq}beginToolBlock(){let e=this.nextToolBlockId();this.content.length>0&&!this.content.endsWith(`
|
|
336
|
+
|
|
337
|
+
`)&&(this.content+=this.content.endsWith(`
|
|
338
|
+
`)?`
|
|
339
|
+
`:`
|
|
340
|
+
|
|
341
|
+
`);let t=this.content.length;return this.content+=this.toolBlockSentinel(e),this.liveToolBlock={startIdx:t,renderedLength:0,name:"",input:{},startedAt:Date.now(),state:"running"},e}setLiveToolBlockMeta(e,t){this.liveToolBlock&&(this.liveToolBlock.name=e,this.liveToolBlock.input=t)}completeToolBlock(e,t){if(!this.liveToolBlock)return;let s=this.toolBlockSentinel(this.toolBlockSeq);this.content.startsWith(s,this.liveToolBlock.startIdx)?this.content=this.content.slice(0,this.liveToolBlock.startIdx)+e+this.content.slice(this.liveToolBlock.startIdx+s.length):this.content+=e,this.liveToolBlock.state=t,this.liveToolBlock.completeText=e,this.liveToolBlock=null}hasLiveToolBlock(){return this.liveToolBlock!==null}getText(){return this.content.replace(/\x1b\[[0-9;]*m/g,"").trim()}replaceLastBlockContent(e){let t=/\n\x1b\[2m── Round \d+ ──\x1b\[0m\n\x1b\[2m[^\n]*\x1b\[0m\n\n/g,s=-1,i=t.exec(this.content);for(;i!==null;)s=i.index+i[0].length,i=t.exec(this.content);s!==-1?this.content=this.content.slice(0,s)+e:this.content+=e,this.scrollOffset=0,this.manualScroll=!1}setStreaming(e){this.streaming=e}setFocused(e){this.focused=e}scrollUp(){this.manualScroll=!0,this.scrollOffset+=5}scrollDown(){this.scrollOffset=Math.max(0,this.scrollOffset-5),this.scrollOffset===0&&(this.manualScroll=!1)}invalidate(){}render(e){let t=Math.max(4,this.availableHeight??this.terminal.rows-3),s=[];s.push(this.renderHeader(e));let i=t-2,r=Math.max(1,e-2),o=this.getContentLines(r),l=o.length,c=Math.max(l,i)-this.scrollOffset-i;for(let h=0;h<i;h++){let u=c+h,d=u>=0&&u<l?o[u]:"",p=C(d),f=Math.max(0,e-2-p);s.push(` ${d}${" ".repeat(f)} `)}return s.push(this.renderStatus(e)),s}renderHeader(e){let t=Ee(this.themeColor),s=this.pet?` ${this.pet.face()}`:"",i=` ${this.label}${s}`,r=C(i),o=Math.max(0,e-r),l=this.focused?.28:.12,a=Na(Hi(this.themeColor,Wi,l));return`${a}${t}${Oe}${i}${O}${a}${" ".repeat(o)}${O}`}renderStatus(e){if(this.streaming){let t=Ee(this.themeColor),s=` \u25CF \u7B49\u5F85 ${this.role} \u56DE\u590D\u4E2D\u2026`,i=C(s),r=Math.max(0,e-i);return`${t}${s}${" ".repeat(r)}${O}`}if(this.manualScroll){let t=" \u2191 \u6D4F\u89C8\u4E2D (\u2193 \u8FD4\u56DE\u5E95\u90E8)",s=C(t),i=Math.max(0,e-s);return`${fe}${t}${" ".repeat(i)}${O}`}return" ".repeat(e)}getContentLines(e){if(!this.content.trim())return[fe+{engineer:"\u8F93\u5165\u95EE\u9898\u5411 engineer \u63D0\u95EE",genius:"\u4F7F\u7528 /genius [\u95EE\u9898] \u53D1\u8D77\u8D28\u7591 / \u5DE7\u601D",judge:"\u4F7F\u7528 /judge \u8BA9\u5BFC\u5E08\u5728\u7EC4\u4F1A\u4E0A\u53CD\u95EE"}[this.role]+O];let t=[],s=new RegExp(`${Fa.source}|(\\x00TB(\\d+)\\x00)`,"g"),i=0,r;for(;(r=s.exec(this.content))!==null;){let c=this.content.slice(i,r.index).replace(/^\n+/,"");c&&t.push({kind:"md",text:c}),r[1]?t.push({kind:"divider",round:Number.parseInt(r[1],10),userMsg:r[2]}):r[3]&&t.push({kind:"toolblock",id:Number.parseInt(r[4],10)}),i=r.index+r[0].length}let o=this.content.slice(i).replace(/^\n+/,"");o&&t.push({kind:"md",text:o});let l=[],a=Ee(this.themeColor);for(let c of t)c.kind==="divider"?(l.push(`${a}${Oe}\u2500\u2500 Round ${c.round} \u2500\u2500${O}`),l.push(`${fe}${c.userMsg}${O}`),l.push("")):c.kind==="toolblock"?l.push(...this.renderToolBlock(c.id,e)):(this.markdown.setText(c.text),l.push(...this.markdown.render(e)));return l}renderToolBlock(e,t){return!this.liveToolBlock||e!==this.toolBlockSeq?[]:[qa(this.liveToolBlock.name,this.liveToolBlock.input,this.liveToolBlock.startedAt,this.themeColor)]}};function Hi(n,e,t){let s=p=>[parseInt(p.slice(1,3),16),parseInt(p.slice(3,5),16),parseInt(p.slice(5,7),16)],[i,r,o]=s(n),[l,a,c]=s(e),h=Math.round(i*t+l*(1-t)),u=Math.round(r*t+a*(1-t)),d=Math.round(o*t+c*(1-t));return`#${h.toString(16).padStart(2,"0")}${u.toString(16).padStart(2,"0")}${d.toString(16).padStart(2,"0")}`}import{readFileSync as Ha,writeFileSync as Ua}from"node:fs";import{join as za}from"node:path";function Ui(n,e){let t=za(n,".cc-agents","settings.json");try{let s=Ha(t,"utf-8"),i=JSON.parse(s);i.panels=e,Ua(t,`${JSON.stringify(i,null," ")}
|
|
342
|
+
`)}catch(s){console.warn(`[cc-agents] failed to persist panel visibility: ${s instanceof Error?s.message:s}`)}}var Vi={cat:["=^.^=","=^-^=","=^\u03C9^="],duck:["<(^)>","<(-)>","<(^)>"],bunny:["(^\u03C9^)","(-\u03C9-)","(>\u03C9<)"],ghost:["(o o)","(- -)","(o w)"],axolotl:["(\u2070 \u2070)","(- -)","(\u2070 v)"],capybara:["(^oo^)","(-oo-)","(^Oo^)"],penguin:["(^>^)","(-.-)","(^>^)"],frog:["(o Uo)","(- u-)","(o Uo)"]},zi=Object.keys(Vi),En=[0,0,0,1,0,0,0,2,0,0,1,0];function Va(n){let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}function Ga(n){let e=n>>>0;return()=>{e|=0,e=e+1831565813|0;let t=Math.imul(e^e>>>15,1|e);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296}}var Ya=700,Be=class{constructor(e="cc-agents-genius-pet"){this.seqIdx=0;this.intervalId=null;let t=Ga(Va(e)),s=Math.floor(t()*zi.length);this.species=zi[s]}start(e){this.intervalId=setInterval(()=>{this.seqIdx=(this.seqIdx+1)%En.length,e.requestRender()},Ya)}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null)}face(){let e=En[this.seqIdx%En.length];return Vi[this.species][e]}};import{existsSync as Gi,mkdirSync as Xa,readFileSync as Qa,writeFileSync as Yi}from"node:fs";import{join as Xi}from"node:path";function On(n){return Xi(n,".cc-agents","sessions","current.json")}function _n(n,e,t){try{let s=Xi(n,".cc-agents","sessions");Xa(s,{recursive:!0});let i={state:e,mode:t,savedAt:new Date().toISOString()};Yi(On(n),JSON.stringify(i,null,2))}catch{}}function Qi(n){let e=On(n);if(!Gi(e))return null;try{let t=JSON.parse(Qa(e,"utf-8"));return!t.state||!Array.isArray(t.state.rounds)?null:{state:t.state,mode:t.mode??"engineer",savedAt:t.savedAt??""}}catch{return null}}function Ji(n){try{let e=On(n);Gi(e)&&Yi(e,JSON.stringify({state:{rounds:[]},mode:"engineer",savedAt:new Date().toISOString()},null,2))}catch{}}var ge="\x1B[0m",me="\x1B[2m",Zi="\x1B[1m",Ja="\x1B[38;2;255;166;87m",Za="\x1B[38;2;255;80;80m";function el(n){let e=parseInt(n.slice(1,3),16),t=parseInt(n.slice(3,5),16),s=parseInt(n.slice(5,7),16);return`\x1B[38;2;${e};${t};${s}m`}var tl=[{key:"engineer",label:"engineer",color:"#79c0ff"},{key:"genius",label:"genius",color:"#d2a8ff"},{key:"judge",label:"judge",color:"#ffa657"}],Bt=class{constructor(){this.visible={engineer:!0,genius:!0,judge:!0};this.tokens={engineer:{input:0,output:0},genius:{input:0,output:0},judge:{input:0,output:0}};this.models={engineer:"",genius:"",judge:""};this.lastInput={engineer:0,genius:0,judge:0};this.ctxWindow={engineer:2e5,genius:2e5,judge:2e5};this.notice=null}setNotice(e,t,s){this.notice=e,setTimeout(()=>{this.notice=null,s()},t)}setModels(e){this.models={...e}}setLastInput(e,t){this.lastInput[e]=t}setContextWindows(e){this.ctxWindow={...e}}toggle(e){let t=Object.values(this.visible).filter(Boolean).length;this.visible[e]&&t<=1||(this.visible[e]=!this.visible[e],this.onToggle?.(e,this.visible[e]))}isVisible(e){return this.visible[e]}setVisible(e,t){this.visible[e]!==t&&(!t&&Object.values(this.visible).filter(Boolean).length<=1||(this.visible[e]=t,this.onToggle?.(e,t)))}showAll(){let e=!1;for(let t of["engineer","genius","judge"])this.visible[t]||(this.visible[t]=!0,e=!0);e&&this.onToggle?.("engineer",!0)}addTokens(e,t,s){this.tokens[e].input+=t,this.tokens[e].output+=s}getTotalTokens(){return Object.values(this.tokens).reduce((e,t)=>e+t.input+t.output,0)}invalidate(){}render(e){let t=[];for(let a of tl){let c=this.visible[a.key],h=c?"\u25CF":"\u25CB",u=c?el(a.color):me,d=` ${h} ${a.label}`,p=C(d);t.push(`${u}${Zi}${d}${ge}${" ".repeat(Math.max(0,e-p))}`);let f=this.models[a.key];if(f){let x=` ${f}`,T=C(x)>e?x.slice(0,e-1)+"\u2026":x,I=C(T);t.push(`${me}${T}${" ".repeat(Math.max(0,e-I))}${ge}`)}else t.push(" ".repeat(e));let g=this.lastInput[a.key],m=this.ctxWindow[a.key];if(g>0){let x=Math.round(g/m*100),T=g>=1e3?`${Math.round(g/1e3)}k`:`${g}`,I=`${Math.round(m/1e3)}k`,D=` ${T}/${I} ${x}%`,R=C(D),v=x>=90?`${Za}${Zi}`:x>=70?Ja:me;t.push(`${v}${D}${" ".repeat(Math.max(0,e-R))}${ge}`)}else t.push(" ".repeat(e))}t.push(`${me}${"\u2500".repeat(e)}${ge}`);let s=this.getTotalTokens(),i=s>=1e3?` \u03A3 ${(s/1e3).toFixed(1)}k`:` \u03A3 ${s}`,r=C(i);t.push(`${me}${i}${" ".repeat(Math.max(0,e-r))}${ge}`);let o=" tokens",l=C(o);if(t.push(`${me}${o}${" ".repeat(Math.max(0,e-l))}${ge}`),this.notice){t.push(`${me}${"\u2500".repeat(e)}${ge}`);for(let a=0;a<this.notice.length;a+=e){let c=this.notice.slice(a,a+e),h=C(c);t.push(`${me}${c}${" ".repeat(Math.max(0,e-h))}${ge}`)}}return t}};var er=[{name:"engineer",kind:"engineer",description:"\u5411 engineer \u63D0\u95EE\uFF08\u9ED8\u8BA4\u6A21\u5F0F\uFF09",takesArgs:!0,argHint:"[\u95EE\u9898]"},{name:"genius",kind:"genius",description:"\u5BF9\u5F53\u524D\u56DE\u7B54\u53D1\u8D77\u8D28\u7591 + \u5DE7\u601D",takesArgs:!0,argHint:"[\u95EE\u9898]"},{name:"judge",kind:"judge",description:"\u8BA9 judge\uFF08\u7EC4\u4F1A\u5BFC\u5E08\uFF09\u53CD\u95EE\u5F53\u524D\u5C40\u52BF",takesArgs:!1},{name:"summarize",kind:"summarize",description:"\u8BA9 judge \u751F\u6210\u603B\u7ED3\u6587\u6863\u5199\u5165 docs/",takesArgs:!1},{name:"skills",kind:"skills",description:"\u5217\u51FA\u6240\u6709\u53EF\u7528 skills\uFF08\u6765\u81EA .cc-agents/skills/\uFF09",takesArgs:!1},{name:"clear",kind:"clear",description:"\u6E05\u7A7A\u6240\u6709\u9762\u677F\u5185\u5BB9",takesArgs:!1},{name:"hide",kind:"hide",description:"\u9690\u85CF\u67D0\u4E2A agent \u9762\u677F",takesArgs:!0,argHint:"<engineer|genius|judge>"},{name:"show",kind:"show",description:"\u663E\u793A\u9762\u677F",takesArgs:!0,argHint:"<role|all>"},{name:"copy",kind:"copy",description:"\u590D\u5236\u9762\u677F\u5185\u5BB9\u5230\u526A\u8D34\u677F",takesArgs:!0,argHint:"<role|all>"},{name:"help",kind:"help",description:"\u663E\u793A\u6240\u6709\u547D\u4EE4",takesArgs:!1},{name:"resume",kind:"resume",description:"\u6062\u590D\u4E0A\u6B21\u4FDD\u5B58\u7684\u5BF9\u8BDD\u5386\u53F2",takesArgs:!1}];var ce="\x1B[0m",Bn="\x1B[1m",Kt="\x1B[2m",nl="\x1B[7m",tr="\x1B[38;2;255;200;80m",sl="\x1B[38;2;121;192;255m",Dt=6,Wt=class{constructor(){this.selectedIdx=0;this.items=[]}update(e){if(!e.startsWith("/")||e.includes(" ")||e.includes(`
|
|
343
|
+
`)){this.items=[],this.selectedIdx=0;return}let t=e.slice(1).toLowerCase();this.items=er.filter(s=>s.name.startsWith(t)).map(s=>({spec:s,matchLen:t.length})),this.selectedIdx>=this.items.length&&(this.selectedIdx=0)}isVisible(){return this.items.length>0}getSelected(){return this.items[this.selectedIdx]?.spec}getItemCount(){return this.items.length}up(){this.items.length!==0&&(this.selectedIdx=(this.selectedIdx-1+this.items.length)%this.items.length)}down(){this.items.length!==0&&(this.selectedIdx=(this.selectedIdx+1)%this.items.length)}apply(){let e=this.getSelected();if(!e)return;let t=`/${e.name}${e.takesArgs?" ":""}`;return{text:t,cursor:t.length}}invalidate(){}render(e){if(this.items.length===0)return[];let t=[],s=`\u25B8 ${this.items.length} match${this.items.length===1?"":"es"} \xB7 Tab to complete`,i=C(s);t.push(`${Kt}${ee(s,e,"")}${" ".repeat(Math.max(0,e-i))}${ce}`);let r=Math.max(0,Math.min(this.selectedIdx-Math.floor(Dt/2),this.items.length-Dt)),o=Math.min(r+Dt,this.items.length);for(let a=r;a<o;a++){let c=this.items[a];c&&t.push(this.renderItem(c,a===this.selectedIdx,e))}let l=o-r;for(let a=l;a<Dt;a++)t.push(" ".repeat(e));return t}renderItem(e,t,s){let{spec:i,matchLen:r}=e,o=i.name.slice(0,r),l=i.name.slice(r),a=t?`${sl}\u25B6${ce}`:" ",c=t?`${tr}${Bn}${o}${ce}${Bn}${l}${ce}`:`${tr}${Bn}${o}${ce}${l}`,h=`${Kt}/${ce}`,u=i.argHint?`${Kt}${i.argHint}${ce}`:"",d=`${a} ${h}${c}`,p=`${u} ${Kt}${i.description}${ce}`,f=t?`${nl}${d}${p}${ce}`:`${d} ${p}`,g=C(f);return g>s?ee(f,s,""):f+" ".repeat(Math.max(0,s-g))}};var k="\x1B[0m",Y="\x1B[1m",L="\x1B[2m";function st(n){let e=parseInt(n.slice(1,3),16),t=parseInt(n.slice(3,5),16),s=parseInt(n.slice(5,7),16);return`\x1B[38;2;${e};${t};${s}m`}function ol(n){let e=n.engineer.model,t=n.genius.model,s=n.judge.model;return[`${Y}cc-agents \u5E2E\u52A9${k}`,`${L} engineer: ${e} genius: ${t} judge: ${s}${k}`,"",`${Y}\u547D\u4EE4${k}`,`${L}\u76F4\u63A5\u8F93\u5165${k} \u53D1\u9001\u7ED9\u5F53\u524D\u6A21\u5F0F\u7684 agent`,`${L}/engineer [\u5185\u5BB9]${k} \u5207\u6362\u5230 engineer \u6A21\u5F0F\uFF0C\u53EF\u9644\u5E26\u6D88\u606F`,`${L}/genius [\u5185\u5BB9]${k} \u5207\u6362\u5230 Genius Challenger \u6A21\u5F0F\uFF0C\u53EF\u9644\u5E26\u6D88\u606F`,`${L}/judge${k} \u89E6\u53D1 judge \u4E00\u6B21\u6027\u5206\u6790\u5F53\u524D\u5C40\u52BF`,`${L}/summarize${k} \u8BA9 judge \u751F\u6210\u603B\u7ED3\u6587\u6863\u5E76\u5199\u5165 docs/`,`${L}/skills${k} \u5217\u51FA .cc-agents/skills/ \u4E0B\u6240\u6709\u53EF\u7528 skill`,`${L}/copy X${k} \u590D\u5236\u9762\u677F\u5230\u526A\u8D34\u677F\uFF08X = engineer / genius / judge / all\uFF09`,`${L}/resume${k} \u6062\u590D\u4E0A\u6B21\u4FDD\u5B58\u7684\u5BF9\u8BDD\u5386\u53F2\uFF08\u65AD\u70B9\u7EED\u4F1A\uFF09`,`${L}/clear${k} \u6E05\u7A7A\u6240\u6709\u9762\u677F\u548C\u5BF9\u8BDD\u5386\u53F2`,`${L}/hide X${k} \u9690\u85CF\u9762\u677F\uFF08X = engineer / genius / judge\uFF09\uFF0C\u91CD\u542F\u540E\u4FDD\u7559`,`${L}/show X${k} \u663E\u793A\u9762\u677F\uFF08X = engineer / genius / judge / all\uFF09`,`${L}/help${k} \u663E\u793A\u6B64\u5E2E\u52A9\uFF08\u72EC\u7ACB\u5168\u5C4F\u7A97\u53E3\uFF0C\u4E0D\u5199\u5165\u9762\u677F\uFF09`,"",`${Y}\u952E\u76D8${k}`,`${L}\u2191 / \u2193${k} \u968F\u65F6\u6EDA\u52A8\u5F53\u524D\u6A21\u5F0F\u9762\u677F\uFF08\u65E0\u9700\u5148\u5207\u7126\u70B9\uFF09`,`${L}Cmd+1 / 2 / 3${k} \u805A\u7126\u6307\u5B9A\u9762\u677F\u540E\u7528 \u2191/\u2193 \u6EDA\u52A8\u8BE5\u9762\u677F`,`${L}Tab (\u9762\u677F\u7126\u70B9\u4E2D)${k} \u5FAA\u73AF\u5207\u6362\u9762\u677F\u7126\u70B9`,`${L}Esc${k} \u9000\u51FA\u9762\u677F\u7126\u70B9\uFF0C\u56DE\u5230\u8F93\u5165\u6846`,`${L}Alt+1 / 2 / 3${k} \u5207\u6362\u9762\u677F\u663E\u793A / \u9690\u85CF\uFF08\u6301\u4E45\u5316\uFF09`,`${L}Tab (\u8F93\u5165\u6846\u4E2D)${k} \u9884\u586B judge \u5EFA\u8BAE\u7684\u8FFD\u95EE`,`${L}Ctrl+C / Ctrl+Q${k} \u9000\u51FA`,"",`${Y}\u6D41\u7A0B${k}`," 1. \u8F93\u5165\u95EE\u9898 \u2192 engineer \u56DE\u7B54"," 2. /genius [\u8D28\u7591\u70B9] \u2192 Genius Challenger \u6311\u6218 engineer \u7684\u8BBA\u70B9 + \u5DE7\u601D"," 3. /judge \u2192 judge \u7ED9\u51FA\u5C40\u52BF\u5206\u6790\u548C\u5EFA\u8BAE\u8FFD\u95EE"," 4. Tab \u9884\u586B\u8FFD\u95EE\uFF0C\u7EE7\u7EED\u4E0B\u4E00\u8F6E"," 5. /summarize \u2192 \u751F\u6210\u5B8C\u6574\u8BA8\u8BBA\u603B\u7ED3\u5B58\u5165 docs/"].join(`
|
|
344
|
+
`)}function al(n,e){if(n.length===0)return`${L}\u6CA1\u6709\u627E\u5230 skill\u3002${k}
|
|
345
|
+
|
|
346
|
+
${L}\u628A SKILL.md \u653E\u8FDB ${e}/.cc-agents/skills/<name>/ \u5373\u53EF\uFF08YAML frontmatter \u5305\u542B name + description\uFF09\u3002${k}`;let t=80,s=[`${Y}\u53EF\u7528 skills\uFF08${n.length} \u4E2A\uFF09${k}`,`${L}\u76EE\u5F55\uFF1A${e}/.cc-agents/skills/${k}`,`${L}LLM \u5728\u5339\u914D description \u65F6\u81EA\u52A8\u52A0\u8F7D\u5BF9\u5E94 SKILL.md\uFF1B\u8FD9\u91CC\u662F\u7ED9\u4EBA\u770B\u7684\u603B\u89C8\u3002${k}`,""];for(let i of n){let r=i.description.replace(/\s+/g," ").trim();r.length>t&&(r=`${r.slice(0,t-1)}\u2026`),s.push(` ${Y}${i.name}${k}`),s.push(` ${L}${r}${k}`)}return s.join(`
|
|
347
|
+
`)}var Nt=class{constructor(e,t,s){this.state=ys();this.mode="engineer";this.streaming=!1;this.inputQueue=[];this.focusedElement="input";this.tokenWarningShown=!1;this.pendingClear=!1;this.animationTimer=null;this.settings=e,this.projectRoot=t,this.tracker=s;let i=ms(t),r=bs(t);this.settings={engineer:{...e.engineer,systemPrompt:i+e.engineer.systemPrompt+(r?`
|
|
348
|
+
|
|
349
|
+
${r}`:"")},genius:{...e.genius,systemPrompt:i+e.genius.systemPrompt},judge:{...e.judge,systemPrompt:i+e.judge.systemPrompt}},this.terminal=new nt,this.tui=new Ve(this.terminal);let o=e.engineer.themeColor,l=e.genius.themeColor,a=e.judge.themeColor;this.engineerPanel=new _e("engineer","1 engineer",o,this.terminal),this.geniusPanel=new _e("genius","2 Genius Challenger",l,this.terminal),this.judgePanel=new _e("judge","3 judge",a,this.terminal);let c=new Be("cc-agents-engineer-pet"),h=new Be("cc-agents-genius-pet"),u=new Be("cc-agents-judge-pet");if(this.engineerPanel.setPet(c),this.geniusPanel.setPet(h),this.judgePanel.setPet(u),this.pets=[c,h,u],this.sidebar=new Bt,this.sidebar.setModels({engineer:e.engineer.model,genius:e.genius.model,judge:e.judge.model}),this.sidebar.setContextWindows({engineer:2e5,genius:2e5,judge:2e5}),e.panels)for(let p of["engineer","genius","judge"]){let f=e.panels[p];typeof f=="boolean"&&this.sidebar.setVisible(p,f)}this.mainColumns=new Et,this.rebuildColumns(),this.modeBadge=new $e("",0,0),this.pastedStore=new Mt,this.attachmentsPreview=new pt(this.pastedStore),this.slashAutocomplete=new Wt,this.helpOverlay=new Ot,this.input=new Ae({detectImage:ss,readImage:is,registerImage:(p,f)=>this.pastedStore.add(p,f)}),this.sidebar.onToggle=(p,f)=>{this.rebuildColumns(),this.persistPanels()};let d=new Pe;d.addChild(this.mainColumns),d.addChild(this.modeBadge),d.addChild(this.attachmentsPreview),d.addChild(this.input),d.addChild(this.slashAutocomplete),this.tui.addChild(d),this.tui.setFocus(this.input),this.updateModeBadge(),this.tui.addInputListener(p=>this.handleGlobalKey(p)),process.stdout.on("resize",()=>{this.updatePanelHeights()}),this.input.onSubmit=p=>{this.handleSubmit(p).catch(f=>{this.showError(String(f))})},this.input.onAttachmentsChange=()=>{this.updatePanelHeights(),this.tui.requestRender()},this.input.onError=p=>{this.showError(p)},this.input.onChange=p=>{this.slashAutocomplete.update(p),this.updatePanelHeights(),this.tui.requestRender()}}start(){for(let e of this.pets)e.start(this.tui);this.tui.start(),this.tracker&&(this.sidebar.setNotice(this.tracker.info().url,8e3,()=>this.tui.requestRender()),this.tui.requestRender())}stop(){return this.tracker?.stop()??Promise.resolve()}recordUsage(e){this.tracker?.record({role:e.role,model:e.model,command:e.command,messagesCount:e.messagesCount,hasTools:e.hasTools,inputTokens:e.inputTokens,outputTokens:e.outputTokens,lastInputTokens:e.lastInputTokens,durationMs:Math.round(performance.now()-e.startedAt)})}rebuildColumns(){let e=[];this.sidebar.isVisible("engineer")&&e.push({component:this.engineerPanel,flex:1}),this.sidebar.isVisible("genius")&&e.push({component:this.geniusPanel,flex:1}),this.sidebar.isVisible("judge")&&e.push({component:this.judgePanel,flex:1}),e.push({component:this.sidebar,fixedWidth:20}),this.mainColumns.setColumns(e)}handleGlobalKey(e){if((N(e,j.ctrl("c"))||N(e,j.ctrl("q")))&&(this.tui.stop(),process.exit(0)),!this.helpHandle){if(N(e,j.tab)){if(this.slashAutocomplete.isVisible()){let t=this.slashAutocomplete.apply();return t&&(this.input.setValue(t.text),this.slashAutocomplete.update(t.text),this.updatePanelHeights(),this.tui.requestRender()),{consume:!0}}if(this.focusedElement!=="input")return this.cyclePanelFocus(),{consume:!0};if(this.latestNext)return this.input.setValue(`/${this.latestNext.target} ${this.latestNext.question}`),this.tui.requestRender(),{consume:!0}}if(N(e,j.alt("1")))return this.sidebar.toggle("engineer"),this.rebuildColumns(),this.tui.requestRender(),{consume:!0};if(N(e,j.alt("2")))return this.sidebar.toggle("genius"),this.rebuildColumns(),this.tui.requestRender(),{consume:!0};if(N(e,j.alt("3")))return this.sidebar.toggle("judge"),this.rebuildColumns(),this.tui.requestRender(),{consume:!0};if(N(e,j.super("1")))return this.setFocusElement("engineer"),this.tui.requestRender(),{consume:!0};if(N(e,j.super("2")))return this.setFocusElement("genius"),this.tui.requestRender(),{consume:!0};if(N(e,j.super("3")))return this.setFocusElement("judge"),this.tui.requestRender(),{consume:!0};if(N(e,j.up)){if(this.slashAutocomplete.isVisible())return this.slashAutocomplete.up(),this.tui.requestRender(),{consume:!0};let t=this.focusedElement!=="input"?this.focusedElement:this.mode;return this.getPanel(t)?.scrollUp(),this.tui.requestRender(),{consume:!0}}if(N(e,j.down)){if(this.slashAutocomplete.isVisible())return this.slashAutocomplete.down(),this.tui.requestRender(),{consume:!0};let t=this.focusedElement!=="input"?this.focusedElement:this.mode;return this.getPanel(t)?.scrollDown(),this.tui.requestRender(),{consume:!0}}if(N(e,j.escape)){if(this.pendingClear)return this.pendingClear=!1,this.judgePanel.appendText(`${L}\u6E05\u7A7A\u5DF2\u53D6\u6D88\u3002${k}
|
|
350
|
+
`),this.tui.requestRender(),{consume:!0};if(this.focusedElement!=="input")return this.setFocusElement("input"),this.tui.requestRender(),{consume:!0}}this.focusedElement!=="input"&&e.length>0&&!e.startsWith("\x1B")&&e.charCodeAt(0)>=32&&this.setFocusElement("input")}}setFocusElement(e){this.focusedElement=e,this.engineerPanel.setFocused(e==="engineer"),this.geniusPanel.setFocused(e==="genius"),this.judgePanel.setFocused(e==="judge"),e==="input"&&this.tui.setFocus(this.input)}getPanel(e){if(e==="engineer")return this.engineerPanel;if(e==="genius")return this.geniusPanel;if(e==="judge")return this.judgePanel}cyclePanelFocus(){let t=["engineer","genius","judge"].filter(r=>this.sidebar.isVisible(r));if(t.length===0)return;let s=t.indexOf(this.focusedElement),i=t[(s+1)%t.length];this.setFocusElement(i),this.tui.requestRender()}updatePanelHeights(){let e=this.slashAutocomplete.isVisible()?7:0,t=this.attachmentsPreview.rowCount(),s=Math.max(4,this.terminal.rows-2-e-t);this.engineerPanel.setAvailableHeight(s),this.geniusPanel.setAvailableHeight(s),this.judgePanel.setAvailableHeight(s)}async handleSubmit(e,t){if(!t){if(!e.trim())return;if(this.streaming){let o=this.collectReferencedAttachments(e);this.warnOrphans(o.orphanIds),this.inputQueue.push({value:e,attachments:o.attachments}),this.input.setValue(""),this.judgePanel.appendText(`${L}
|
|
351
|
+
[\u6392\u961F\u4E2D] ${e.slice(0,60)}${e.length>60?"\u2026":""}
|
|
352
|
+
${k}`),this.tui.requestRender();return}}let s=os(e);this.input.setValue(""),this.tui.requestRender(),s.kind!=="clear"&&this.pendingClear&&(this.pendingClear=!1);let i=s.kind==="text"||(s.kind==="engineer"||s.kind==="genius")&&s.content.length>0,r=t??[];if(!t&&i){let o=this.collectReferencedAttachments(s.content);this.warnOrphans(o.orphanIds),r=o.attachments}switch(s.kind){case"engineer":this.mode="engineer",s.content&&await this.sendToEngineer(s.content,r);break;case"genius":this.mode="genius",s.content&&await this.sendToGenius(s.content,r);break;case"judge":await this.callJudge();break;case"summarize":await this.callSummarize();break;case"clear":this.pendingClear?this.clearAll():(this.pendingClear=!0,this.judgePanel.appendText(`
|
|
353
|
+
${L}\u786E\u8BA4\u6E05\u7A7A\u6240\u6709\u9762\u677F\u548C\u5BF9\u8BDD\u5386\u53F2\uFF1F\u518D\u6B21\u8F93\u5165 /clear \u786E\u8BA4\uFF0CEsc \u53D6\u6D88\u3002${k}
|
|
354
|
+
`),this.tui.requestRender());break;case"help":this.showHelp();break;case"skills":this.showSkills();break;case"resume":this.resumeSession();break;case"hide":{let o=s.content,l=this.sidebar.isVisible(o);this.sidebar.setVisible(o,!1),this.sidebar.isVisible(o)===l&&this.showError(`\u65E0\u6CD5\u9690\u85CF ${o}\uFF08\u81F3\u5C11\u4FDD\u7559\u4E00\u4E2A\u9762\u677F\uFF09`),this.rebuildColumns();break}case"show":s.content==="all"?this.sidebar.showAll():this.sidebar.setVisible(s.content,!0),this.rebuildColumns();break;case"copy":{let o=s.content,l=this.collectPanelText(o);if(l.length===0){this.showError("\u6CA1\u6709\u5185\u5BB9\u53EF\u590D\u5236");break}await ts(l)?this.flashStatus(`${o==="all"?"\u5168\u90E8\u9762\u677F":o} (${l.length} \u5B57\u7B26) \u5DF2\u590D\u5236\u5230\u526A\u8D34\u677F`):this.showError("\u526A\u8D34\u677F\u590D\u5236\u5931\u8D25\uFF08\u672A\u627E\u5230 pbcopy/xclip/wl-copy/clip\uFF09");break}case"text":this.mode==="engineer"?await this.sendToEngineer(s.content,r):await this.sendToGenius(s.content,r);break}this.pastedStore.snapshot().length>0&&(this.pastedStore.clear(),this.updatePanelHeights()),this.updateModeBadge(),this.tui.requestRender()}collectReferencedAttachments(e){let t=new Set(this.pastedStore.idsInText(e)),s=[],i=[];for(let r of this.pastedStore.snapshot())t.has(r.id)?s.push({type:"image",source:{type:"base64",media_type:"image/png",data:r.base64}}):i.push(r.id);return{attachments:s,orphanIds:i}}warnOrphans(e){if(e.length===0)return;let t=e.map(s=>`#${s}`).join(", ");this.judgePanel.appendText(`${L}
|
|
355
|
+
\u56FE\u7247 ${t} \u5360\u4F4D\u7B26\u5DF2\u5220\u9664\uFF0C\u5DF2\u4E22\u5F03
|
|
356
|
+
${k}`)}async sendToEngineer(e,t=[]){vs(this.state,e);let s=this.state.pending.id,i=t.length>0?`\u{1F5BC}\uFE0F \u7528\u6237 (\u9644 ${t.length} \u56FE): ${e}`:`\u7528\u6237: ${e}`;this.engineerPanel.addBlock(s,i),this.engineerPanel.setStreaming(!0),this.setStreaming(!0),this.tui.requestRender();try{let r=Qn(this.state,e,t),o=this.projectRoot,l=performance.now(),a=await qt(this.settings.engineer,Rs,r,h=>{this.engineerPanel.appendStreamChunk(h),this.tui.requestRender()},(h,u)=>{this.engineerPanel.beginToolBlock(),this.engineerPanel.setLiveToolBlockMeta(h,u),this.startAnimationTicker(),this.tui.requestRender()},(h,u,d)=>{let{text:p,state:f}=Mn(h,u,d);this.engineerPanel.completeToolBlock(p,f),this.tui.requestRender()},(h,u)=>Ut(h,u,o));ks(this.state,a.text),Cs(this.state,us(a.text)),this.sidebar.addTokens("engineer",a.usage.inputTokens,a.usage.outputTokens),this.sidebar.setLastInput("engineer",a.usage.lastInputTokens),this.recordUsage({role:"engineer",model:this.settings.engineer.model,command:"engineer",messagesCount:r.length,hasTools:!0,inputTokens:a.usage.inputTokens,outputTokens:a.usage.outputTokens,lastInputTokens:a.usage.lastInputTokens,startedAt:l});let c=this.ctxWindowFor("engineer");ls(a.usage.lastInputTokens,c)&&await this.runAutoCompact(),_n(this.projectRoot,this.state,this.mode)}catch(r){this.engineerPanel.appendText(`
|
|
357
|
+
[\u9519\u8BEF: ${r instanceof Error?r.message:String(r)}]
|
|
358
|
+
`)}finally{this.stopAnimationTicker(),this.engineerPanel.setStreaming(!1),this.setStreaming(!1),this.tui.requestRender()}}async sendToGenius(e,t=[]){if(!this.state.pending?.engineerResponse){this.geniusPanel.appendText(`${L}
|
|
359
|
+
\u9700\u8981\u5148\u83B7\u53D6 engineer \u7684\u56DE\u590D\uFF0C\u518D\u8BA9 Genius Challenger \u5DE7\u601D
|
|
360
|
+
${k}`),this.tui.requestRender();return}let s=this.state.pending.id??1,i=t.length>0?`\u{1F5BC}\uFE0F \u7528\u6237 (\u9644 ${t.length} \u56FE): ${e}`:`\u7528\u6237: ${e}`;this.geniusPanel.addBlock(s,i),this.geniusPanel.setStreaming(!0),this.setStreaming(!0),this.tui.requestRender();try{let r=Jn(this.state,e,t),o=this.projectRoot,l=performance.now(),a=await qt(this.settings.genius,Ps,r,c=>{this.geniusPanel.appendStreamChunk(c),this.tui.requestRender()},(c,h)=>{this.geniusPanel.beginToolBlock(),this.geniusPanel.setLiveToolBlockMeta(c,h),this.startAnimationTicker(),this.tui.requestRender()},(c,h,u)=>{let{text:d,state:p}=Mn(c,h,u);this.geniusPanel.completeToolBlock(d,p),this.tui.requestRender()},(c,h)=>Ut(c,h,o));Ss(this.state,e,a.text),this.sidebar.addTokens("genius",a.usage.inputTokens,a.usage.outputTokens),this.sidebar.setLastInput("genius",a.usage.lastInputTokens),this.recordUsage({role:"genius",model:this.settings.genius.model,command:"genius",messagesCount:r.length,hasTools:!0,inputTokens:a.usage.inputTokens,outputTokens:a.usage.outputTokens,lastInputTokens:a.usage.lastInputTokens,startedAt:l}),_n(this.projectRoot,this.state,this.mode)}catch(r){this.geniusPanel.appendText(`
|
|
361
|
+
[\u9519\u8BEF: ${r instanceof Error?r.message:String(r)}]
|
|
362
|
+
`)}finally{this.geniusPanel.setStreaming(!1),this.setStreaming(!1),this.tui.requestRender()}}async callJudge(){if(!this.state.pending&&this.state.rounds.length===0){this.judgePanel.appendText(`${L}
|
|
363
|
+
\u9700\u8981\u5148\u4E0E engineer \u5BF9\u8BDD\u540E\u624D\u80FD\u8C03\u7528 /judge
|
|
364
|
+
${k}`),this.tui.requestRender();return}this.judgePanel.addBlock(this.state.rounds.length+1,"Judge \u5206\u6790"),this.judgePanel.setStreaming(!0),this.setStreaming(!0),this.tui.requestRender();try{let e=es(this.state),t=performance.now(),s=await We(this.settings.judge,e,o=>{this.judgePanel.appendStreamChunk(o),this.tui.requestRender()}),i=hs(s.text);this.latestNext=i.next,this.sidebar.addTokens("judge",s.usage.inputTokens,s.usage.outputTokens),this.sidebar.setLastInput("judge",s.usage.lastInputTokens),this.recordUsage({role:"judge",model:this.settings.judge.model,command:"judge",messagesCount:e.length,hasTools:!1,inputTokens:s.usage.inputTokens,outputTokens:s.usage.outputTokens,lastInputTokens:s.usage.lastInputTokens,startedAt:t});let r=this.formatJudgeOutput(i);this.judgePanel.replaceLastBlockContent(r)}catch(e){this.judgePanel.appendText(`
|
|
365
|
+
[\u9519\u8BEF: ${e instanceof Error?e.message:String(e)}]
|
|
366
|
+
`)}finally{this.judgePanel.setStreaming(!1),this.setStreaming(!1),this.tui.requestRender()}}async callSummarize(){if(!this.state.pending?.engineerResponse&&this.state.rounds.length===0){this.judgePanel.appendText(`${L}
|
|
367
|
+
\u9700\u8981\u5148\u4E0E engineer \u5BF9\u8BDD\u540E\u624D\u80FD\u8C03\u7528 /summarize
|
|
368
|
+
${k}`),this.tui.requestRender();return}let e=this.state.rounds.length+1;this.judgePanel.addBlock(e,"/summarize \u751F\u6210\u603B\u7ED3"),this.judgePanel.setStreaming(!0),this.setStreaming(!0),this.tui.requestRender();try{let t=Xn(this.state),s=Yn(this.settings.judge),i=performance.now(),r=await We(s,t,d=>{this.judgePanel.appendStreamChunk(d),this.tui.requestRender()});this.sidebar.addTokens("judge",r.usage.inputTokens,r.usage.outputTokens),this.sidebar.setLastInput("judge",r.usage.lastInputTokens),this.recordUsage({role:"judge",model:s.model,command:"summarize",messagesCount:t.length,hasTools:!1,inputTokens:r.usage.inputTokens,outputTokens:r.usage.outputTokens,lastInputTokens:r.usage.lastInputTokens,startedAt:i});let l=(r.text.trim().split(`
|
|
369
|
+
`)[0]??"").match(/^#\s*\d{4}-\d{2}-\d{2}\s+(.+)/),a=l?l[1].toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""):"summary",h=`${new Date().toISOString().split("T")[0]}-${a}.md`,u=nr(this.projectRoot,"docs");il(u,{recursive:!0}),rl(nr(u,h),r.text),this.judgePanel.appendText(`
|
|
370
|
+
${L}\u2713 \u603B\u7ED3\u5DF2\u5199\u5165 docs/${h}${k}
|
|
371
|
+
`)}catch(t){this.judgePanel.appendText(`
|
|
372
|
+
[\u9519\u8BEF: ${t instanceof Error?t.message:String(t)}]
|
|
373
|
+
`)}finally{this.judgePanel.setStreaming(!1),this.setStreaming(!1),this.tui.requestRender()}}startAnimationTicker(){this.animationTimer===null&&(this.animationTimer=setInterval(()=>{this.engineerPanel.hasLiveToolBlock()?this.tui.requestRender():this.stopAnimationTicker()},50))}stopAnimationTicker(){this.animationTimer!==null&&(clearInterval(this.animationTimer),this.animationTimer=null)}setStreaming(e){if(this.streaming=e,!e&&(this.checkTokenThreshold(),this.inputQueue.length>0)){let t=this.inputQueue.shift();setTimeout(()=>{this.handleSubmit(t.value,t.attachments).catch(s=>this.showError(String(s)))},0)}}checkTokenThreshold(){let e=this.sidebar.lastInput.engineer,t=this.ctxWindowFor("engineer"),s=t>0?e/t:0;if(!this.tokenWarningShown&&s>=.5&&e>0){this.tokenWarningShown=!0;let i=Math.round(s*100);this.judgePanel.appendText(`
|
|
374
|
+
${L}\u26A0 Engineer \u4E0A\u4E0B\u6587\u5DF2\u7528 ${i}%\uFF08${Math.round(e/1e3)}k/${Math.round(t/1e3)}k\uFF09\u3002
|
|
375
|
+
\u8D85\u8FC7 75% \u65F6\u4F1A\u81EA\u52A8\u538B\u7F29\u5386\u53F2\uFF1B\u5EFA\u8BAE /summarize \u5F52\u6863\u91CD\u8981\u5185\u5BB9\u3002${k}
|
|
376
|
+
`),this.tui.requestRender()}}clearAll(){ws(this.state),this.engineerPanel.clearContent(),this.geniusPanel.clearContent(),this.judgePanel.clearContent(),this.latestNext=void 0,this.pendingClear=!1,this.tokenWarningShown=!1,Ji(this.projectRoot),this.tui.requestRender()}ctxWindowFor(e){return 2e5}resumeSession(){let e=Qi(this.projectRoot);if(!e){this.judgePanel.appendText(`${L}
|
|
377
|
+
\u6CA1\u6709\u627E\u5230\u4FDD\u5B58\u7684\u4F1A\u8BDD\uFF08.cc-agents/sessions/current.json \u4E0D\u5B58\u5728\uFF09
|
|
378
|
+
${k}`),this.tui.requestRender();return}let{state:t,mode:s,savedAt:i}=e,r=t.rounds.length+(t.pending?.engineerResponse?1:0);Object.assign(this.state,t),this.mode=s,this.updateModeBadge();let o=i?new Date(i).toLocaleString():"\u672A\u77E5\u65F6\u95F4",l=t.compactSummary?"\uFF08\u542B\u5386\u53F2\u538B\u7F29\u6458\u8981\uFF09":"";this.judgePanel.appendText(`
|
|
379
|
+
${L}\u2713 \u5DF2\u6062\u590D\u4F1A\u8BDD ${l}
|
|
380
|
+
\u4FDD\u5B58\u65F6\u95F4\uFF1A${o}
|
|
381
|
+
\u5386\u53F2\u8F6E\u6B21\uFF1A${r} \u8F6E
|
|
382
|
+
\u5F53\u524D\u6A21\u5F0F\uFF1A${s}
|
|
383
|
+
${k}`),this.tui.requestRender()}async runAutoCompact(){if(!(this.state.rounds.length<=2)){this.engineerPanel.appendText(`
|
|
384
|
+
${L}[\u81EA\u52A8\u538B\u7F29\u5386\u53F2\u5BF9\u8BDD\u4E2D\u2026]${k}
|
|
385
|
+
`),this.tui.requestRender();try{let{compacted:t}=await cs(this.state,this.settings.engineer,()=>{});t>0&&(this.engineerPanel.appendText(`${L}\u2713 \u5DF2\u5C06 ${t} \u8F6E\u5386\u53F2\u538B\u7F29\u4E3A\u6458\u8981\uFF08\u4FDD\u7559\u6700\u8FD1 ${this.state.rounds.length} \u8F6E\u539F\u6587\uFF09${k}
|
|
386
|
+
`),this.tui.requestRender())}catch(t){this.engineerPanel.appendText(`${L}[\u5386\u53F2\u538B\u7F29\u5931\u8D25\uFF0C\u8DF3\u8FC7: ${t instanceof Error?t.message:String(t)}]${k}
|
|
387
|
+
`),this.tui.requestRender()}}}collectPanelText(e){let t=[],s=["engineer","genius","judge"],i={engineer:"1 engineer",genius:"2 Genius Challenger",judge:"3 judge"},r=e==="all"?s:[e];for(let o of r){let l=this.getPanel(o);if(!l)continue;let a=l.getText();a&&t.push(`=== ${i[o]} ===
|
|
388
|
+
${a}`)}return t.join(`
|
|
389
|
+
|
|
390
|
+
`)}flashStatus(e){let t=`${this.mode==="engineer"?st(this.settings.engineer.themeColor):st(this.settings.genius.themeColor)}${Y} \u2192 ${this.mode}${k}`,s=st("#3fb950");this.modeBadge.setText(`${s}${Y} \u2713 ${e}${k}`),this.tui.requestRender(),setTimeout(()=>{this.updateModeBadge(),this.tui.requestRender()},3e3)}formatJudgeOutput(e){let t=[];return t.push(`${Y}\u5206\u6790${k}
|
|
391
|
+
${e.analysis}`),e.verdict&&t.push(`
|
|
392
|
+
${Y}\u88C1\u5B9A${k}
|
|
393
|
+
${e.verdict}`),e.next&&(t.push(`
|
|
394
|
+
${Y}\u5EFA\u8BAE\u8FFD\u95EE \u2192 ${e.next.target}${k}
|
|
395
|
+
${e.next.question}`),t.push(`
|
|
396
|
+
${L}\u6309 Tab \u4E00\u952E\u9884\u586B${k}`)),`${t.join(`
|
|
397
|
+
`)}
|
|
398
|
+
`}showHelp(){this.helpHandle||(this.helpOverlay.setContent(ol(this.settings),this.terminal.columns,this.terminal.rows),this.helpOverlay.onClose=()=>{this.helpHandle?.hide(),this.helpHandle=void 0,this.tui.requestRender()},this.helpHandle=this.tui.showOverlay(this.helpOverlay))}showSkills(){if(this.helpHandle)return;let e=xs(this.projectRoot),t=al(e,this.projectRoot);this.helpOverlay.setContent(t,this.terminal.columns,this.terminal.rows,"\u53EF\u7528 skills"),this.helpOverlay.onClose=()=>{this.helpHandle?.hide(),this.helpHandle=void 0,this.tui.requestRender()},this.helpHandle=this.tui.showOverlay(this.helpOverlay)}persistPanels(){Ui(this.projectRoot,{engineer:this.sidebar.isVisible("engineer"),genius:this.sidebar.isVisible("genius"),judge:this.sidebar.isVisible("judge")})}showError(e){this.judgePanel.appendText(`
|
|
399
|
+
[\u7CFB\u7EDF\u9519\u8BEF: ${e}]
|
|
400
|
+
`),this.tui.requestRender()}updateModeBadge(){let e=this.mode==="engineer"?st(this.settings.engineer.themeColor):st(this.settings.genius.themeColor),t=this.mode==="engineer"?"engineer":"genius";this.modeBadge.setText(`${e}${Y} \u2192 ${t}${k}${L} /engineer /genius /judge /summarize /clear \xB7 Tab \u9884\u586B \xB7 ${k}${Y}1/2/3${k}${L} \u5207\u6362\u680F${k}`)}};var Kn=process.cwd(),Ft;try{Ft=jn(Kn)}catch(n){console.error(String(n)),process.exit(1)}var sr;if(Ft.tokenTracker?.enabled)try{sr=await Gn({projectRoot:Kn,config:Ft.tokenTracker})}catch(n){console.error(`[token-tracker] failed to start: ${n instanceof Error?n.message:String(n)}`)}var ir=new Nt(Ft,Kn,sr),rr=async()=>{await ir.stop(),process.exit(0)};process.on("SIGINT",()=>{rr()});process.on("SIGTERM",()=>{rr()});ir.start();
|