@aria-cli/cli 1.0.14 → 1.0.15
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/dist/.aria-build-stamp.json +1 -1
- package/dist/attached-local-control-client-2jz8vmjb.js +1 -0
- package/dist/cli-context.js +1 -0
- package/dist/commands/index.js +1 -0
- package/dist/config.js +1 -0
- package/dist/daemon-service-esj85cr7.js +1 -0
- package/dist/ensure-daemon.js +1 -0
- package/dist/history/index.js +1 -0
- package/dist/index-00jaxgt2.js +2 -0
- package/dist/index-5v7br509.js +2 -0
- package/dist/index-718zvjhe.js +12 -0
- package/dist/index-76vaj0sr.js +321 -0
- package/dist/index-92syx5hd.js +149 -0
- package/dist/index-9j6r3gr8.js +2 -0
- package/dist/index-g5devafm.js +0 -0
- package/dist/index-j035n0mr.js +2 -0
- package/dist/index-nnqfqvqh.js +2 -0
- package/dist/index-sx36201d.js +5 -0
- package/dist/index-sxga6d5s.js +2 -0
- package/dist/index-wbm34jf5.js +24 -0
- package/dist/index-xjwfqz7t.js +2 -0
- package/dist/index-y2vy5jks.js +4 -0
- package/dist/index.js +1 -505
- package/dist/ink-repl.js +1 -0
- package/dist/kernel-0tytvcv0.js +1 -0
- package/dist/local-control-client.js +1 -0
- package/dist/repl-cleanup.js +1 -0
- package/dist/runtime-cutover-reset-0nywfrh6.js +1 -0
- package/dist/session-ybzq2j2n.js +1 -0
- package/dist/session.js +1 -0
- package/dist/ui/components/Banner.d.ts +1 -1
- package/package.json +10 -10
package/dist/index.js
CHANGED
|
@@ -1,505 +1 @@
|
|
|
1
|
-
|
|
2
|
-
CREATE TABLE IF NOT EXISTS sessions (
|
|
3
|
-
id TEXT PRIMARY KEY,
|
|
4
|
-
created_at TEXT NOT NULL,
|
|
5
|
-
updated_at TEXT NOT NULL,
|
|
6
|
-
completed_at TEXT,
|
|
7
|
-
title TEXT,
|
|
8
|
-
arion TEXT NOT NULL,
|
|
9
|
-
model TEXT NOT NULL,
|
|
10
|
-
message_count INTEGER DEFAULT 0
|
|
11
|
-
);
|
|
12
|
-
|
|
13
|
-
CREATE TABLE IF NOT EXISTS messages (
|
|
14
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
15
|
-
session_id TEXT NOT NULL,
|
|
16
|
-
role TEXT NOT NULL,
|
|
17
|
-
content TEXT NOT NULL,
|
|
18
|
-
arion TEXT,
|
|
19
|
-
created_at TEXT NOT NULL,
|
|
20
|
-
FOREIGN KEY (session_id) REFERENCES sessions(id) ON DELETE CASCADE
|
|
21
|
-
);
|
|
22
|
-
|
|
23
|
-
CREATE TABLE IF NOT EXISTS input_history (
|
|
24
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
25
|
-
content TEXT NOT NULL UNIQUE,
|
|
26
|
-
used_at TEXT NOT NULL
|
|
27
|
-
);
|
|
28
|
-
|
|
29
|
-
CREATE INDEX IF NOT EXISTS idx_messages_session ON messages(session_id);
|
|
30
|
-
CREATE INDEX IF NOT EXISTS idx_sessions_updated ON sessions(updated_at DESC);
|
|
31
|
-
CREATE INDEX IF NOT EXISTS idx_input_history_used ON input_history(used_at DESC);
|
|
32
|
-
`);try{this.db.exec("ALTER TABLE sessions ADD COLUMN completed_at TEXT")}catch(t){if(!(t?.message??"").includes("duplicate column name"))throw t}try{this.db.exec("ALTER TABLE messages ADD COLUMN tool_call_id TEXT")}catch(t){if(!(t?.message??"").includes("duplicate column name"))throw t}try{this.db.exec("ALTER TABLE messages ADD COLUMN tool_calls TEXT")}catch(t){if(!(t?.message??"").includes("duplicate column name"))throw t}try{this.db.exec("ALTER TABLE messages ADD COLUMN thinking TEXT")}catch(t){if(!(t?.message??"").includes("duplicate column name"))throw t}try{this.db.exec("ALTER TABLE messages ADD COLUMN data TEXT")}catch(t){if(!(t?.message??"").includes("duplicate column name"))throw t}this.db.exec(`
|
|
33
|
-
CREATE TABLE IF NOT EXISTS run_metrics (
|
|
34
|
-
id TEXT PRIMARY KEY,
|
|
35
|
-
session_id TEXT NOT NULL,
|
|
36
|
-
turn_count INTEGER,
|
|
37
|
-
input_tokens INTEGER,
|
|
38
|
-
output_tokens INTEGER,
|
|
39
|
-
total_tokens INTEGER,
|
|
40
|
-
estimated_cost REAL,
|
|
41
|
-
wall_time_ms INTEGER,
|
|
42
|
-
tool_count INTEGER,
|
|
43
|
-
guardrail_fires INTEGER,
|
|
44
|
-
handoff_count INTEGER,
|
|
45
|
-
created_at TEXT DEFAULT (datetime('now')),
|
|
46
|
-
FOREIGN KEY (session_id) REFERENCES sessions(id)
|
|
47
|
-
);
|
|
48
|
-
|
|
49
|
-
CREATE INDEX IF NOT EXISTS idx_run_metrics_session ON run_metrics(session_id);
|
|
50
|
-
`),this.db.exec(`
|
|
51
|
-
CREATE TABLE IF NOT EXISTS session_runtime_state (
|
|
52
|
-
session_id TEXT PRIMARY KEY,
|
|
53
|
-
state_status TEXT NOT NULL DEFAULT 'idle',
|
|
54
|
-
active_run_id TEXT,
|
|
55
|
-
paused_state_json TEXT,
|
|
56
|
-
policy_snapshot_json TEXT,
|
|
57
|
-
last_event_seq INTEGER NOT NULL DEFAULT 0,
|
|
58
|
-
revision INTEGER NOT NULL DEFAULT 0,
|
|
59
|
-
lease_owner TEXT,
|
|
60
|
-
lease_expires_at TEXT,
|
|
61
|
-
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
62
|
-
FOREIGN KEY (session_id) REFERENCES sessions(id) ON DELETE CASCADE
|
|
63
|
-
);
|
|
64
|
-
|
|
65
|
-
CREATE TABLE IF NOT EXISTS session_interactions (
|
|
66
|
-
interaction_id TEXT PRIMARY KEY,
|
|
67
|
-
session_id TEXT NOT NULL,
|
|
68
|
-
request_id TEXT NOT NULL,
|
|
69
|
-
source TEXT NOT NULL,
|
|
70
|
-
kind TEXT NOT NULL,
|
|
71
|
-
status TEXT NOT NULL,
|
|
72
|
-
prompt_json TEXT NOT NULL,
|
|
73
|
-
response_json TEXT,
|
|
74
|
-
created_at TEXT NOT NULL,
|
|
75
|
-
answered_at TEXT,
|
|
76
|
-
applied_at TEXT,
|
|
77
|
-
FOREIGN KEY (session_id) REFERENCES sessions(id) ON DELETE CASCADE
|
|
78
|
-
);
|
|
79
|
-
|
|
80
|
-
CREATE INDEX IF NOT EXISTS idx_session_runtime_state_status
|
|
81
|
-
ON session_runtime_state(state_status, updated_at DESC);
|
|
82
|
-
CREATE INDEX IF NOT EXISTS idx_session_interactions_session
|
|
83
|
-
ON session_interactions(session_id, created_at DESC);
|
|
84
|
-
CREATE INDEX IF NOT EXISTS idx_session_interactions_status
|
|
85
|
-
ON session_interactions(status, created_at DESC);
|
|
86
|
-
`),this.initializeSessionFts();try{this.db.pragma("wal_checkpoint(PASSIVE)")}catch{}}initializeSessionFts(){try{this.db.exec(`
|
|
87
|
-
CREATE VIRTUAL TABLE IF NOT EXISTS fts_session_messages USING fts5(
|
|
88
|
-
message_id UNINDEXED,
|
|
89
|
-
session_id UNINDEXED,
|
|
90
|
-
content
|
|
91
|
-
);
|
|
92
|
-
|
|
93
|
-
CREATE TRIGGER IF NOT EXISTS trg_messages_ai_fts
|
|
94
|
-
AFTER INSERT ON messages BEGIN
|
|
95
|
-
INSERT INTO fts_session_messages (message_id, session_id, content)
|
|
96
|
-
VALUES (new.id, new.session_id, new.content);
|
|
97
|
-
END;
|
|
98
|
-
|
|
99
|
-
CREATE TRIGGER IF NOT EXISTS trg_messages_au_fts
|
|
100
|
-
AFTER UPDATE OF content, session_id ON messages BEGIN
|
|
101
|
-
DELETE FROM fts_session_messages WHERE message_id = old.id;
|
|
102
|
-
INSERT INTO fts_session_messages (message_id, session_id, content)
|
|
103
|
-
VALUES (new.id, new.session_id, new.content);
|
|
104
|
-
END;
|
|
105
|
-
|
|
106
|
-
CREATE TRIGGER IF NOT EXISTS trg_messages_ad_fts
|
|
107
|
-
AFTER DELETE ON messages BEGIN
|
|
108
|
-
DELETE FROM fts_session_messages WHERE message_id = old.id;
|
|
109
|
-
END;
|
|
110
|
-
`);let t=this.db.prepare("SELECT COUNT(*) as c FROM messages").get().c;this.db.prepare("SELECT COUNT(*) as c FROM fts_session_messages").get().c<t&&this.db.exec(`
|
|
111
|
-
INSERT INTO fts_session_messages (message_id, session_id, content)
|
|
112
|
-
SELECT m.id, m.session_id, m.content
|
|
113
|
-
FROM messages m
|
|
114
|
-
LEFT JOIN fts_session_messages f ON f.message_id = m.id
|
|
115
|
-
WHERE f.message_id IS NULL;
|
|
116
|
-
`),this.sessionFtsEnabled=!0}catch(t){this.sessionFtsEnabled=!1,Vt.warn("[SessionHistory] Session FTS disabled:",t?.message??String(t))}}toFtsPrefixQuery(t){return t.trim().split(/\s+/).filter(Boolean).map(r=>`"${r.replace(/"/g,'""')}"*`).join(" AND ")}withImmediateTransaction(t){this.db.exec("BEGIN IMMEDIATE");try{let r=t();return this.db.exec("COMMIT"),r}catch(r){try{this.db.exec("ROLLBACK")}catch{}throw r}}ensureSessionRuntimeRow(t){let r=new Date().toISOString();this.db.prepare(`INSERT INTO session_runtime_state (
|
|
117
|
-
session_id,
|
|
118
|
-
state_status,
|
|
119
|
-
last_event_seq,
|
|
120
|
-
revision,
|
|
121
|
-
updated_at
|
|
122
|
-
) VALUES (?, 'idle', 0, 0, ?)
|
|
123
|
-
ON CONFLICT(session_id) DO NOTHING`).run(t,r)}readSessionRuntimeStateRow(t){return this.ensureSessionRuntimeRow(t),this.db.prepare("SELECT * FROM session_runtime_state WHERE session_id = ?").get(t)??null}parseJsonColumn(t,r,n){if(!r)return n;try{return JSON.parse(r)}catch{return Vt.warn(`[SessionHistory] Corrupted ${t} JSON, using fallback value`),n}}toSessionRuntimeState(t){return t?{sessionId:t.session_id,stateStatus:t.state_status,activeRunId:t.active_run_id,pausedState:this.parseJsonColumn("paused_state_json",t.paused_state_json,null),policySnapshot:this.parseJsonColumn("policy_snapshot_json",t.policy_snapshot_json,null),lastEventSeq:t.last_event_seq,revision:t.revision,leaseOwner:t.lease_owner,leaseExpiresAt:t.lease_expires_at,updatedAt:t.updated_at}:null}toSessionInteractionRecord(t){return t?{interactionId:t.interaction_id,sessionId:t.session_id,requestId:t.request_id,source:t.source,kind:t.kind,status:t.status,prompt:this.parseJsonColumn("prompt_json",t.prompt_json,{}),response:this.parseJsonColumn("response_json",t.response_json,null),createdAt:t.created_at,answeredAt:t.answered_at,appliedAt:t.applied_at}:null}assertSessionMutationGuard(t,r,n){let o=Date.now(),s=t.lease_expires_at?Date.parse(t.lease_expires_at):null;if(r&&t.lease_owner&&t.lease_owner!==r&&s!==null&&Number.isFinite(s)&&s>o)throw new Error(`Session ${t.session_id} is leased by ${t.lease_owner} until ${t.lease_expires_at}`);if(n!==void 0&&t.revision!==n)throw new Error(`Session ${t.session_id} revision mismatch: expected ${n}, got ${t.revision}`)}createSession(t,r,n){n??=Aw.randomUUID();let o=new Date().toISOString();return this.withImmediateTransaction(()=>{this.db.prepare(`
|
|
124
|
-
INSERT INTO sessions (id, created_at, updated_at, arion, model, message_count)
|
|
125
|
-
VALUES (?, ?, ?, ?, ?, 0)
|
|
126
|
-
`).run(n,o,o,t,r),this.db.prepare(`INSERT INTO session_runtime_state (
|
|
127
|
-
session_id,
|
|
128
|
-
state_status,
|
|
129
|
-
last_event_seq,
|
|
130
|
-
revision,
|
|
131
|
-
updated_at
|
|
132
|
-
) VALUES (?, 'idle', 0, 0, ?)`).run(n,o)}),n}forkSession(t,r){let n=this.db.prepare("SELECT * FROM sessions WHERE id = ?").get(t);if(!n)throw new Error(`Source session not found: ${t}`);let o=Aw.randomUUID(),s=new Date().toISOString(),i=r?.title??(n.title?`\u{1F374} ${n.title}`:"\u{1F374} Forked session"),a=r?.messageLimit!==void 0&&r.messageLimit>=0?this.db.prepare("SELECT * FROM messages WHERE session_id = ? ORDER BY id ASC LIMIT ?"):this.db.prepare("SELECT * FROM messages WHERE session_id = ? ORDER BY id ASC"),c=r?.messageLimit!==void 0&&r.messageLimit>=0?a.all(t,r.messageLimit):a.all(t);return this.withImmediateTransaction(()=>{if(this.db.prepare(`INSERT INTO sessions (id, created_at, updated_at, arion, model, message_count, title)
|
|
133
|
-
VALUES (?, ?, ?, ?, ?, ?, ?)`).run(o,s,s,n.arion,n.model,c.length,i),this.db.prepare(`INSERT INTO session_runtime_state (
|
|
134
|
-
session_id, state_status, last_event_seq, revision, updated_at
|
|
135
|
-
) VALUES (?, 'idle', 0, 0, ?)`).run(o,s),c.length>0){let l=this.db.prepare(`INSERT INTO messages (session_id, role, content, arion, tool_call_id, tool_calls, thinking, data, created_at)
|
|
136
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`);for(let d of c)l.run(o,d.role,d.content,d.arion,d.tool_call_id,d.tool_calls,d.thinking,d.data,d.created_at)}}),{newSessionId:o,sourceSessionId:t,messagesCopied:c.length,title:i}}addMessage(t,r,n,o){try{let s=new Date().toISOString(),i=o?.arion??null,a=o?.toolCallId??null,c=o?.toolCalls?JSON.stringify(o.toolCalls):null,l=o?.thinking?JSON.stringify(o.thinking):null;this.db.transaction(()=>{this.db.prepare(`INSERT INTO messages (session_id, role, content, arion, tool_call_id, tool_calls, thinking, created_at)
|
|
137
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(t,r,n,i,a,c,l,s),this.db.prepare(`UPDATE sessions
|
|
138
|
-
SET updated_at = ?,
|
|
139
|
-
message_count = message_count + 1,
|
|
140
|
-
title = COALESCE(title, CASE WHEN ? = 'user' THEN substr(?, 1, 60) END)
|
|
141
|
-
WHERE id = ?`).run(s,r,n,t)})()}catch(s){Vt.warn("[SessionHistory] Failed to persist message:",s?.message??s)}}addConversationMessage(t,r){try{let n=new Date().toISOString(),o=Ki(r);if(r.role==="tool"&&!o){let f=r.content.find(u=>u.type==="tool_result");f&&f.type==="tool_result"&&(o=f.content)}let s=r.arion?.name??null,i=Ji(r),a=Vi(r),c=Yi(r),l=JSON.stringify(r);this.db.transaction(()=>{this.db.prepare(`INSERT INTO messages (session_id, role, content, arion, tool_call_id, tool_calls, thinking, data, created_at)
|
|
142
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(t,r.role,o,s,i,a,c,l,n),this.db.prepare(`UPDATE sessions
|
|
143
|
-
SET updated_at = ?,
|
|
144
|
-
message_count = message_count + 1,
|
|
145
|
-
title = COALESCE(title, CASE WHEN ? = 'user' THEN substr(?, 1, 60) END)
|
|
146
|
-
WHERE id = ?`).run(n,r.role,o,t)})(),this.incrementalSessions.add(t)}catch(n){Vt.warn("[SessionHistory] Failed to persist conversation message:",n?.message??n)}}addConversationMessages(t,r){if(r.length!==0){if(r.length===1){this.addConversationMessage(t,r[0]);return}try{let n=new Date().toISOString(),o=this.db.prepare(`INSERT INTO messages (session_id, role, content, arion, tool_call_id, tool_calls, thinking, data, created_at)
|
|
147
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`),s=this.db.prepare(`UPDATE sessions
|
|
148
|
-
SET updated_at = ?,
|
|
149
|
-
message_count = message_count + ?,
|
|
150
|
-
title = COALESCE(title, CASE WHEN ? = 'user' THEN substr(?, 1, 60) END)
|
|
151
|
-
WHERE id = ?`);this.db.transaction(()=>{let a=null;for(let c of r){let l=Ki(c);if(c.role==="tool"&&!l){let S=c.content.find(R=>R.type==="tool_result");S&&S.type==="tool_result"&&(l=S.content)}c.role==="user"&&!a&&(a=l);let d=c.arion?.name??null,f=Ji(c),u=Vi(c),h=Yi(c),y=JSON.stringify(c);o.run(t,c.role,l,d,f,u,h,y,n)}s.run(n,r.length,a?"user":"assistant",a??"",t)})()}catch(n){Vt.warn("[SessionHistory] Failed to persist conversation messages batch:",n?.message??n)}}}replaceConversationMessages(t,r){if(!this.incrementalSessions.has(t))try{let n=performance.now(),o=this.db.prepare("SELECT COUNT(*) as cnt FROM messages WHERE session_id = ?").get(t)?.cnt??0,s=performance.now();cr(`SessionHistory:replaceConversationMessages(del=${o},ins=${r.length})`);let i=new Date().toISOString(),a=this.db.prepare(`INSERT INTO messages (session_id, role, content, arion, tool_call_id, tool_calls, thinking, data, created_at)
|
|
152
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`);this.db.transaction(()=>{this.db.prepare("DELETE FROM messages WHERE session_id = ?").run(t);let d=null;for(let f of r){let u=Ki(f);if(f.role==="tool"&&!u){let h=f.content.find(y=>y.type==="tool_result");h&&h.type==="tool_result"&&(u=h.content)}f.role==="user"&&!d&&(d=u),a.run(t,f.role,u,f.arion?.name??null,Ji(f),Vi(f),Yi(f),JSON.stringify(f),i)}this.db.prepare(`UPDATE sessions
|
|
153
|
-
SET updated_at = ?,
|
|
154
|
-
message_count = ?,
|
|
155
|
-
title = CASE
|
|
156
|
-
WHEN ? IS NOT NULL AND length(?) > 0 THEN substr(?, 1, 60)
|
|
157
|
-
ELSE title
|
|
158
|
-
END
|
|
159
|
-
WHERE id = ?`).run(i,r.length,d,d,d,t)})();let l=performance.now()-n;if(Kt(),process.env.DEBUG&&(l>200||o>500))try{process.stderr.write(`[SessionHistory][DIAG] replaceConversationMessages: total=${l.toFixed(0)}ms (count=${(s-n).toFixed(0)}ms txn=${(l-(s-n)).toFixed(0)}ms) existingRows=${o} newRows=${r.length} session=${t}
|
|
160
|
-
`)}catch{}}catch(n){Kt(),Vt.warn("[SessionHistory] Failed to replace conversation messages batch:",n?.message??n)}}loadSessionMessages(t){let r=this.db.prepare("SELECT * FROM sessions WHERE id = ?").get(t);if(!r)return null;let o=this.db.prepare("SELECT * FROM messages WHERE session_id = ? ORDER BY id ASC").all(t).map(s=>{if(s.data)try{let i=JSON.parse(s.data),a=Cd.safeParse(i);return a.success?a.data:(Vt.warn(`[loadSessionMessages] Schema validation failed for message row ${s.id} (session ${t}), falling back to v1 columns`),zi(s))}catch{return Vt.warn(`[loadSessionMessages] Corrupted data column in message row ${s.id} (session ${t}), falling back to v1 columns`),zi(s)}return zi(s)});return{id:r.id,arion:r.arion,model:r.model,messages:o}}loadSession(t){let r=this.loadSessionMessages(t);if(!r)return null;let n=this.toSessionRuntimeState(this.readSessionRuntimeStateRow(t)),o=this.db.prepare(`SELECT * FROM session_interactions
|
|
161
|
-
WHERE session_id = ?
|
|
162
|
-
AND status = 'pending'
|
|
163
|
-
ORDER BY created_at DESC
|
|
164
|
-
LIMIT 1`).get(t)??null;return{session:r,runtimeState:n,pendingInteraction:this.toSessionInteractionRecord(o)}}getSessionRuntimeState(t){return this.toSessionRuntimeState(this.readSessionRuntimeStateRow(t))}getInteraction(t){let r=this.db.prepare("SELECT * FROM session_interactions WHERE interaction_id = ?").get(t)??null;return this.toSessionInteractionRecord(r)}claimSessionForMutation(t,r,n){if(!r.trim())throw new Error("claimSessionForMutation requires a non-empty ownerId");if(!Number.isFinite(n)||n<=0)throw new Error("claimSessionForMutation requires a positive staleAfterMs");return this.withImmediateTransaction(()=>{let o=this.readSessionRuntimeStateRow(t);if(!o)throw new Error(`Session ${t} not found`);this.assertSessionMutationGuard(o,r);let s=new Date().toISOString(),i=new Date(Date.now()+n).toISOString();return this.db.prepare(`UPDATE session_runtime_state
|
|
165
|
-
SET lease_owner = ?,
|
|
166
|
-
lease_expires_at = ?,
|
|
167
|
-
updated_at = ?
|
|
168
|
-
WHERE session_id = ?`).run(r,i,s,t),this.toSessionRuntimeState(this.readSessionRuntimeStateRow(t))})}recordPausedRun(t,r,n,o,s,i){return this.withImmediateTransaction(()=>{let a=this.readSessionRuntimeStateRow(t);if(!a)throw new Error(`Session ${t} not found`);this.assertSessionMutationGuard(a,i?.ownerId,i?.expectedRevision);let c=new Date().toISOString(),l=a.revision+1;return this.db.prepare(`UPDATE session_runtime_state
|
|
169
|
-
SET state_status = 'paused',
|
|
170
|
-
active_run_id = ?,
|
|
171
|
-
paused_state_json = ?,
|
|
172
|
-
policy_snapshot_json = ?,
|
|
173
|
-
last_event_seq = ?,
|
|
174
|
-
revision = ?,
|
|
175
|
-
updated_at = ?
|
|
176
|
-
WHERE session_id = ?`).run(r,JSON.stringify(n),JSON.stringify(o),i?.lastEventSeq??a.last_event_seq,l,c,t),s&&this.db.prepare(`INSERT INTO session_interactions (
|
|
177
|
-
interaction_id,
|
|
178
|
-
session_id,
|
|
179
|
-
request_id,
|
|
180
|
-
source,
|
|
181
|
-
kind,
|
|
182
|
-
status,
|
|
183
|
-
prompt_json,
|
|
184
|
-
created_at
|
|
185
|
-
) VALUES (?, ?, ?, ?, ?, 'pending', ?, ?)`).run(s.interactionId,t,s.requestId,s.source,s.kind,JSON.stringify(s.prompt),c),this.toSessionRuntimeState(this.readSessionRuntimeStateRow(t))})}recordInteractionResponse(t,r,n,o){return this.withImmediateTransaction(()=>{let s=this.readSessionRuntimeStateRow(t);if(!s)throw new Error(`Session ${t} not found`);this.assertSessionMutationGuard(s,o?.ownerId,o?.expectedRevision);let i=this.db.prepare(`SELECT * FROM session_interactions
|
|
186
|
-
WHERE session_id = ?
|
|
187
|
-
AND interaction_id = ?`).get(t,r)??null;if(!i)throw new Error(`Interaction ${r} not found for session ${t}`);if(i.status!=="pending")throw new Error(`Interaction ${r} is not pending (current status: ${i.status})`);let a=new Date().toISOString();this.db.prepare(`UPDATE session_interactions
|
|
188
|
-
SET status = 'answered',
|
|
189
|
-
response_json = ?,
|
|
190
|
-
answered_at = ?
|
|
191
|
-
WHERE interaction_id = ?`).run(JSON.stringify(n),a,r),this.db.prepare(`UPDATE session_runtime_state
|
|
192
|
-
SET revision = revision + 1,
|
|
193
|
-
updated_at = ?
|
|
194
|
-
WHERE session_id = ?`).run(a,t);let c=this.db.prepare("SELECT * FROM session_interactions WHERE interaction_id = ?").get(r)??null;return this.toSessionInteractionRecord(c)})}cancelInteraction(t,r,n){return this.withImmediateTransaction(()=>{let o=this.readSessionRuntimeStateRow(t);if(!o)throw new Error(`Session ${t} not found`);this.assertSessionMutationGuard(o,n?.ownerId,n?.expectedRevision);let s=this.db.prepare(`SELECT * FROM session_interactions
|
|
195
|
-
WHERE session_id = ?
|
|
196
|
-
AND interaction_id = ?`).get(t,r)??null;if(!s)throw new Error(`Interaction ${r} not found for session ${t}`);if(s.status!=="pending")throw new Error(`Interaction ${r} is not pending (current status: ${s.status})`);let i=new Date().toISOString();this.db.prepare(`UPDATE session_interactions
|
|
197
|
-
SET status = 'canceled',
|
|
198
|
-
answered_at = ?
|
|
199
|
-
WHERE interaction_id = ?`).run(i,r),this.db.prepare(`UPDATE session_runtime_state
|
|
200
|
-
SET state_status = 'completed',
|
|
201
|
-
active_run_id = NULL,
|
|
202
|
-
paused_state_json = NULL,
|
|
203
|
-
policy_snapshot_json = NULL,
|
|
204
|
-
revision = revision + 1,
|
|
205
|
-
updated_at = ?
|
|
206
|
-
WHERE session_id = ?`).run(i,t),this.db.prepare(`UPDATE sessions
|
|
207
|
-
SET completed_at = COALESCE(completed_at, ?),
|
|
208
|
-
updated_at = ?
|
|
209
|
-
WHERE id = ?`).run(i,i,t);let a=this.db.prepare("SELECT * FROM session_interactions WHERE interaction_id = ?").get(r)??null;return this.toSessionInteractionRecord(a)})}completeRun(t,r,n){return this.withImmediateTransaction(()=>{let o=this.readSessionRuntimeStateRow(t);if(!o)throw new Error(`Session ${t} not found`);this.assertSessionMutationGuard(o,n?.ownerId,n?.expectedRevision);let s=new Date().toISOString();return this.db.prepare(`UPDATE session_runtime_state
|
|
210
|
-
SET state_status = 'completed',
|
|
211
|
-
active_run_id = NULL,
|
|
212
|
-
paused_state_json = NULL,
|
|
213
|
-
policy_snapshot_json = NULL,
|
|
214
|
-
revision = revision + 1,
|
|
215
|
-
updated_at = ?
|
|
216
|
-
WHERE session_id = ?`).run(s,t),this.db.prepare(`UPDATE session_interactions
|
|
217
|
-
SET status = CASE WHEN response_json IS NULL THEN 'expired' ELSE 'applied' END,
|
|
218
|
-
answered_at = COALESCE(answered_at, ?),
|
|
219
|
-
applied_at = CASE WHEN response_json IS NULL THEN applied_at ELSE ? END
|
|
220
|
-
WHERE session_id = ?
|
|
221
|
-
AND status IN ('pending', 'answered')`).run(s,s,t),this.db.prepare(`UPDATE sessions
|
|
222
|
-
SET completed_at = COALESCE(completed_at, ?),
|
|
223
|
-
updated_at = ?
|
|
224
|
-
WHERE id = ?`).run(s,s,t),this.toSessionRuntimeState(this.readSessionRuntimeStateRow(t))})}releaseSessionClaim(t,r){this.withImmediateTransaction(()=>{let n=this.readSessionRuntimeStateRow(t);if(!n)throw new Error(`Session ${t} not found`);if(n.lease_owner&&n.lease_owner!==r)throw new Error(`Cannot release session ${t} lease owned by ${n.lease_owner} with ${r}`);let o=new Date().toISOString();this.db.prepare(`UPDATE session_runtime_state
|
|
225
|
-
SET lease_owner = NULL,
|
|
226
|
-
lease_expires_at = NULL,
|
|
227
|
-
updated_at = ?
|
|
228
|
-
WHERE session_id = ?`).run(o,t)})}listSessions(t=20,r=0){return this.db.prepare(`
|
|
229
|
-
SELECT
|
|
230
|
-
s.*,
|
|
231
|
-
COALESCE(s.title, '') as preview
|
|
232
|
-
FROM sessions s
|
|
233
|
-
WHERE s.message_count > 0
|
|
234
|
-
ORDER BY s.updated_at DESC, s.rowid DESC
|
|
235
|
-
LIMIT ? OFFSET ?
|
|
236
|
-
`).all(t,r).map(o=>({id:o.id,createdAt:new Date(o.created_at),updatedAt:new Date(o.updated_at),completedAt:o.completed_at?new Date(o.completed_at):void 0,title:o.title,arion:o.arion,model:o.model,messageCount:o.message_count,preview:this.truncatePreview(o.preview??"",60)}))}searchSessions(t,r=20,n=0){let s=`%${t.replace(/[%_\\]/g,"\\$&")}%`;return this.db.prepare(`
|
|
237
|
-
SELECT DISTINCT
|
|
238
|
-
s.*,
|
|
239
|
-
(SELECT content FROM messages WHERE session_id = s.id AND role = 'user' ORDER BY id LIMIT 1) as preview
|
|
240
|
-
FROM sessions s
|
|
241
|
-
LEFT JOIN messages m ON m.session_id = s.id
|
|
242
|
-
WHERE s.message_count > 0
|
|
243
|
-
AND (s.title LIKE ? ESCAPE '\\' OR m.content LIKE ? ESCAPE '\\')
|
|
244
|
-
ORDER BY s.updated_at DESC, s.rowid DESC
|
|
245
|
-
LIMIT ? OFFSET ?
|
|
246
|
-
`).all(s,s,r,n).map(a=>({id:a.id,createdAt:new Date(a.created_at),updatedAt:new Date(a.updated_at),completedAt:a.completed_at?new Date(a.completed_at):void 0,title:a.title,arion:a.arion,model:a.model,messageCount:a.message_count,preview:this.truncatePreview(a.preview??"",60)}))}searchSessionsFts(t,r=100,n=0){let o=t.trim();if(!o)return[];if(!this.sessionFtsEnabled)return this.searchSessions(o,r,n);let s=this.toFtsPrefixQuery(o);if(!s)return[];try{return this.db.prepare(`
|
|
247
|
-
WITH matched AS (
|
|
248
|
-
SELECT session_id, MIN(bm25(fts_session_messages)) as rank
|
|
249
|
-
FROM fts_session_messages
|
|
250
|
-
WHERE fts_session_messages MATCH ?
|
|
251
|
-
GROUP BY session_id
|
|
252
|
-
)
|
|
253
|
-
SELECT
|
|
254
|
-
s.*,
|
|
255
|
-
COALESCE(s.title, '') as preview
|
|
256
|
-
FROM matched m
|
|
257
|
-
JOIN sessions s ON s.id = m.session_id
|
|
258
|
-
WHERE s.message_count > 0
|
|
259
|
-
ORDER BY m.rank ASC, s.updated_at DESC, s.rowid DESC
|
|
260
|
-
LIMIT ? OFFSET ?
|
|
261
|
-
`).all(s,r,n).map(a=>({id:a.id,createdAt:new Date(a.created_at),updatedAt:new Date(a.updated_at),completedAt:a.completed_at?new Date(a.completed_at):void 0,title:a.title,arion:a.arion,model:a.model,messageCount:a.message_count,preview:this.truncatePreview(a.preview??"",60)}))}catch{return this.searchSessions(o,r,n)}}searchSessionSummaries(t,r=100,n=0){let s=`%${t.replace(/[%_\\]/g,"\\$&")}%`;return this.db.prepare(`
|
|
262
|
-
SELECT
|
|
263
|
-
s.*,
|
|
264
|
-
COALESCE(s.title, '') as preview
|
|
265
|
-
FROM sessions s
|
|
266
|
-
WHERE s.message_count > 0
|
|
267
|
-
AND (
|
|
268
|
-
s.title LIKE ? ESCAPE '\\'
|
|
269
|
-
OR s.arion LIKE ? ESCAPE '\\'
|
|
270
|
-
OR s.model LIKE ? ESCAPE '\\'
|
|
271
|
-
OR s.id LIKE ? ESCAPE '\\'
|
|
272
|
-
)
|
|
273
|
-
ORDER BY s.updated_at DESC, s.rowid DESC
|
|
274
|
-
LIMIT ? OFFSET ?
|
|
275
|
-
`).all(s,s,s,s,r,n).map(a=>({id:a.id,createdAt:new Date(a.created_at),updatedAt:new Date(a.updated_at),completedAt:a.completed_at?new Date(a.completed_at):void 0,title:a.title,arion:a.arion,model:a.model,messageCount:a.message_count,preview:this.truncatePreview(a.preview??"",60)}))}getSession(t){let r=this.db.prepare(`
|
|
276
|
-
SELECT * FROM sessions WHERE id = ?
|
|
277
|
-
`).get(t);if(!r)return null;let n=this.db.prepare(`
|
|
278
|
-
SELECT * FROM messages WHERE session_id = ? ORDER BY id ASC
|
|
279
|
-
`).all(t);return{id:r.id,arion:r.arion,model:r.model,messages:n.map(o=>({id:o.id,role:o.role,content:o.content,arion:o.arion??void 0,toolCallId:o.tool_call_id??void 0,toolCalls:o.tool_calls?(()=>{try{return JSON.parse(o.tool_calls)}catch{Vt.warn(`[getSession] Corrupted tool_calls JSON in message row ${o.id} (session ${t})`);return}})():void 0,thinking:o.thinking?(()=>{try{return JSON.parse(o.thinking)}catch{Vt.warn(`[getSession] Corrupted thinking JSON in message row ${o.id} (session ${t})`);return}})():void 0,createdAt:new Date(o.created_at)}))}}deleteSession(t){this.db.prepare("DELETE FROM sessions WHERE id = ?").run(t)}setSessionTitle(t,r){try{this.db.prepare("UPDATE sessions SET title = ? WHERE id = ?").run(r,t)}catch(n){Vt.warn("[SessionHistory] Failed to set session title:",n?.message??n)}}markCompleted(t){try{let r=new Date().toISOString();this.withImmediateTransaction(()=>{this.db.prepare(`UPDATE sessions
|
|
280
|
-
SET completed_at = COALESCE(completed_at, ?),
|
|
281
|
-
updated_at = ?
|
|
282
|
-
WHERE id = ?`).run(r,r,t),this.ensureSessionRuntimeRow(t),this.db.prepare(`UPDATE session_runtime_state
|
|
283
|
-
SET state_status = 'completed',
|
|
284
|
-
active_run_id = NULL,
|
|
285
|
-
paused_state_json = NULL,
|
|
286
|
-
policy_snapshot_json = NULL,
|
|
287
|
-
lease_owner = NULL,
|
|
288
|
-
lease_expires_at = NULL,
|
|
289
|
-
revision = revision + 1,
|
|
290
|
-
updated_at = ?
|
|
291
|
-
WHERE session_id = ?`).run(r,t)})}catch(r){Vt.warn("[SessionHistory] Failed to mark session completed:",r?.message??r)}}markStaleSessionsCompleted(t){try{let r=new Date(Date.now()-t*864e5).toISOString(),n=new Date().toISOString();return this.db.prepare(`UPDATE sessions
|
|
292
|
-
SET completed_at = COALESCE(completed_at, ?),
|
|
293
|
-
updated_at = ?
|
|
294
|
-
WHERE completed_at IS NULL
|
|
295
|
-
AND message_count > 0
|
|
296
|
-
AND updated_at < ?`).run(n,n,r).changes}catch(r){return Vt.warn("[SessionHistory] Failed to mark stale sessions completed:",r?.message??r),0}}getIncompleteSessions(t=10){return this.db.prepare(`
|
|
297
|
-
SELECT
|
|
298
|
-
s.*,
|
|
299
|
-
(SELECT content FROM messages WHERE session_id = s.id AND role = 'user' ORDER BY id LIMIT 1) as preview
|
|
300
|
-
FROM sessions s
|
|
301
|
-
WHERE s.message_count > 0
|
|
302
|
-
AND s.completed_at IS NULL
|
|
303
|
-
ORDER BY s.updated_at DESC, s.rowid DESC
|
|
304
|
-
LIMIT ?
|
|
305
|
-
`).all(t).map(n=>({id:n.id,createdAt:new Date(n.created_at),updatedAt:new Date(n.updated_at),completedAt:n.completed_at?new Date(n.completed_at):void 0,title:n.title,arion:n.arion,model:n.model,messageCount:n.message_count,preview:this.truncatePreview(n.preview??"",60)}))}findSessionByPrefix(t){if(t.length===36)return this.db.prepare("SELECT id FROM sessions WHERE id = ? AND message_count > 0").get(t)?.id??null;if(t.length<8)return null;let r=this.db.prepare("SELECT id FROM sessions WHERE id LIKE ? AND message_count > 0 LIMIT 2").all(`${t}%`);return r.length===1?r[0].id:null}getSessionCount(){return this.db.prepare("SELECT COUNT(*) as count FROM sessions WHERE message_count > 0").get()?.count??0}truncatePreview(t,r){return t.length<=r?t:t.slice(0,r-3)+"..."}addInputHistory(t){try{let r=new Date().toISOString();this.db.prepare(`
|
|
306
|
-
INSERT INTO input_history (content, used_at)
|
|
307
|
-
VALUES (?, ?)
|
|
308
|
-
ON CONFLICT(content) DO UPDATE SET used_at = excluded.used_at
|
|
309
|
-
`).run(t,r),this.db.prepare(`
|
|
310
|
-
DELETE FROM input_history
|
|
311
|
-
WHERE id NOT IN (
|
|
312
|
-
SELECT id FROM input_history ORDER BY used_at DESC LIMIT 500
|
|
313
|
-
)
|
|
314
|
-
`).run()}catch(r){Vt.warn("[SessionHistory] Failed to save input history:",r?.message??r)}}getInputHistory(t=100){return this.db.prepare(`
|
|
315
|
-
SELECT content FROM input_history
|
|
316
|
-
ORDER BY used_at DESC
|
|
317
|
-
LIMIT ?
|
|
318
|
-
`).all(t).map(n=>n.content)}saveRunMetrics(t,r){try{this.db.prepare(`INSERT INTO run_metrics (id, session_id, turn_count, input_tokens, output_tokens, total_tokens, estimated_cost, wall_time_ms, tool_count, guardrail_fires, handoff_count)
|
|
319
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(r.id,t,r.turnCount??null,r.inputTokens??null,r.outputTokens??null,r.totalTokens??null,r.estimatedCost??null,r.wallTimeMs??null,r.toolCount??null,r.guardrailFires??null,r.handoffCount??null)}catch(n){Vt.warn("[SessionHistory] Failed to save run metrics:",n?.message??n)}}getRunMetrics(t){return this.db.prepare("SELECT * FROM run_metrics WHERE session_id = ? ORDER BY created_at ASC").all(t).map(n=>({id:n.id,sessionId:n.session_id,turnCount:n.turn_count??void 0,inputTokens:n.input_tokens??void 0,outputTokens:n.output_tokens??void 0,totalTokens:n.total_tokens??void 0,estimatedCost:n.estimated_cost??void 0,wallTimeMs:n.wall_time_ms??void 0,toolCount:n.tool_count??void 0,guardrailFires:n.guardrail_fires??void 0,handoffCount:n.handoff_count??void 0,createdAt:n.created_at}))}close(){try{this.db.pragma("wal_checkpoint(TRUNCATE)")}catch{}this.db.close()}}});var ea,Mf=G(()=>{"use strict";ea={name:"dark",displayName:"Dark",colors:{primary:"#5f97cd",secondary:"#888888",text:"#ffffff",textMuted:"#999999",textInverse:"#000000",success:"#4eba65",error:"#ff6b80",warning:"#ffc107",info:"#00d9ff",diffAdded:"#4eba65",diffAddedDimmed:"#2d5a35",diffRemoved:"#ff6b80",diffRemovedDimmed:"#8a3a45",arion:{cyan:"#00d9ff",magenta:"#bd00ff",yellow:"#ffc107",green:"#4eba65",blue:"#5f97cd",red:"#ff6b80",white:"#ffffff"}},symbols:{prompt:"\u276F",divider:"\u2500",success:"\u2713",error:"\u2717",warning:"\u26A0",info:"\u2139",pending:"\u25CB",bullet:"\u2022",arrow:"\u2192"},banner:{gradient:{start:"#00D9FF",middle:"#BD00FF",end:"#6366F1"},animationDuration:1600}}});var Ic,Df=G(()=>{"use strict";Ic={name:"light",displayName:"Light",colors:{primary:"#5f97cd",secondary:"#999999",text:"#000000",textMuted:"#666666",textInverse:"#ffffff",success:"#2c7a39",error:"#ab2b3f",warning:"#b8860b",info:"#0077aa",diffAdded:"#2c7a39",diffAddedDimmed:"#a8d5b1",diffRemoved:"#ab2b3f",diffRemovedDimmed:"#e8b4bc",arion:{cyan:"#0077aa",magenta:"#aa0077",yellow:"#b8860b",green:"#2c7a39",blue:"#5f97cd",red:"#ab2b3f",white:"#333333"}},symbols:{prompt:"\u276F",divider:"\u2500",success:"\u2713",error:"\u2717",warning:"\u26A0",info:"\u2139",pending:"\u25CB",bullet:"\u2022",arrow:"\u2192"},banner:{gradient:{start:"#0077aa",middle:"#aa0077",end:"#5f5fd7"},animationDuration:1600}}});var Nw,Ow=G(()=>{"use strict";Mf();Nw={...ea,name:"dark-accessible",displayName:"Dark (Accessible)",colors:{...ea.colors,success:"#006699",error:"#cc0000",warning:"#ffaa00",diffAdded:"#006699",diffAddedDimmed:"#003d5c",diffRemoved:"#cc0000",diffRemovedDimmed:"#660000"}}});var jw,Pw=G(()=>{"use strict";Df();jw={...Ic,name:"light-accessible",displayName:"Light (Accessible)",colors:{...Ic.colors,success:"#005588",error:"#aa0000",warning:"#996600",diffAdded:"#005588",diffAddedDimmed:"#b3d4e8",diffRemoved:"#aa0000",diffRemovedDimmed:"#e8b3b3"}}});var $w,Fw=G(()=>{"use strict";$w={name:"claude-dark",displayName:"Claude Dark",colors:{primary:"#5f97cd",secondary:"#888888",text:"#ffffff",textMuted:"#999999",textInverse:"#000000",success:"#4eba65",error:"#ff6b80",warning:"#ffc107",info:"#b1b9f9",diffAdded:"#225c2b",diffAddedDimmed:"#47584a",diffRemoved:"#7a2936",diffRemovedDimmed:"#69484d",arion:{cyan:"#b1b9f9",magenta:"#fd5db1",yellow:"#ffc107",green:"#4eba65",blue:"#5f97cd",red:"#ff6b80",white:"#ffffff"}},symbols:{prompt:"\u276F",divider:"\u2500",success:"\u2713",error:"\u2717",warning:"\u26A0",info:"\u2139",pending:"\u25CB",bullet:"\u2022",arrow:"\u2192"},banner:{gradient:{start:"#fd5db1",middle:"#5f97cd",end:"#b1b9f9"},animationDuration:1600}}});var Uw,Bw=G(()=>{"use strict";Uw={name:"claude-light",displayName:"Claude Light",colors:{primary:"#5f97cd",secondary:"#999999",text:"#000000",textMuted:"#666666",textInverse:"#ffffff",success:"#2c7a39",error:"#ab2b3f",warning:"#966c1e",info:"#5769f7",diffAdded:"#69db7c",diffAddedDimmed:"#c7e1cb",diffRemoved:"#ffa8b4",diffRemovedDimmed:"#fdd2d8",arion:{cyan:"#5769f7",magenta:"#ff0087",yellow:"#966c1e",green:"#2c7a39",blue:"#5f97cd",red:"#ab2b3f",white:"#333333"}},symbols:{prompt:"\u276F",divider:"\u2500",success:"\u2713",error:"\u2717",warning:"\u26A0",info:"\u2139",pending:"\u25CB",bullet:"\u2022",arrow:"\u2192"},banner:{gradient:{start:"#ff0087",middle:"#5f97cd",end:"#5769f7"},animationDuration:1600}}});var Hw,Ww=G(()=>{"use strict";Hw={name:"claude-dark-daltonized",displayName:"Claude Dark (Daltonized)",colors:{primary:"#5f97cd",secondary:"#888888",text:"#ffffff",textMuted:"#999999",textInverse:"#000000",success:"#3399ff",error:"#ff6666",warning:"#ffcc00",info:"#99ccff",diffAdded:"#004466",diffAddedDimmed:"#3e515b",diffRemoved:"#660000",diffRemovedDimmed:"#3e2c2c",arion:{cyan:"#99ccff",magenta:"#3399ff",yellow:"#ffcc00",green:"#3399ff",blue:"#5f97cd",red:"#ff6666",white:"#ffffff"}},symbols:{prompt:"\u276F",divider:"\u2500",success:"\u2713",error:"\u2717",warning:"\u26A0",info:"\u2139",pending:"\u25CB",bullet:"\u2022",arrow:"\u2192"},banner:{gradient:{start:"#3399ff",middle:"#5f97cd",end:"#99ccff"},animationDuration:1600}}});var qw,Gw=G(()=>{"use strict";qw={name:"claude-light-daltonized",displayName:"Claude Light (Daltonized)",colors:{primary:"#5f97cd",secondary:"#999999",text:"#000000",textMuted:"#666666",textInverse:"#ffffff",success:"#006699",error:"#cc0000",warning:"#ff9900",info:"#3366ff",diffAdded:"#99ccff",diffAddedDimmed:"#d1e7fd",diffRemoved:"#ffcccc",diffRemovedDimmed:"#ffe9e9",arion:{cyan:"#3366ff",magenta:"#0066cc",yellow:"#ff9900",green:"#006699",blue:"#5f97cd",red:"#cc0000",white:"#333333"}},symbols:{prompt:"\u276F",divider:"\u2500",success:"\u2713",error:"\u2717",warning:"\u26A0",info:"\u2139",pending:"\u25CB",bullet:"\u2022",arrow:"\u2192"},banner:{gradient:{start:"#0066cc",middle:"#5f97cd",end:"#3366cc"},animationDuration:1600}}});var Xw=G(()=>{"use strict"});function an(e){Md[e]&&(zw=Md[e])}function x(){return zw}function cn(){return Object.keys(Md)}function Dd(e){return Md[e]}var Md,zw,D=G(()=>{"use strict";Mf();Df();Ow();Pw();Fw();Bw();Ww();Gw();Xw();Md={dark:ea,light:Ic,"dark-accessible":Nw,"light-accessible":jw,"claude-dark":$w,"claude-light":Uw,"claude-dark-daltonized":Hw,"claude-light-daltonized":qw},zw=ea});var My={};Ln(My,{getAriaDir:()=>lr,getConfigPath:()=>Gf,loadAndMigrateConfig:()=>ky,loadConfig:()=>ue,saveConfig:()=>Le});import*as Pn from"fs";import*as vy from"os";import{getModelById as RC,getModelByShortName as AC,isValidTier as Iy}from"@aria-cli/models";import{log as Bd}from"@aria-cli/types";function lr(){return process.env.ARIA_HOME?process.env.ARIA_HOME:`${process.env.HOME||vy.homedir()}/.aria`}function Gf(){return`${lr()}/config.json`}function ky(){try{let e=Gf();if(Pn.existsSync(e)){let t=JSON.parse(Pn.readFileSync(e,"utf-8"));try{if(t.defaultModel&&!t.preferredTier){let n=RC(t.defaultModel)||AC(t.defaultModel);n||Bd.warn(`Unknown model "${t.defaultModel}" migrated to balanced tier (Sonnet 4.5)`);let o=n?.tier||"balanced";t.preferredTier=Iy(o)?o:"balanced",delete t.defaultModel,Le(t)}t.preferredTier!==void 0&&!Iy(t.preferredTier)&&(Bd.warn(`Invalid tier "${t.preferredTier}" corrected to balanced tier`),t.preferredTier="balanced",Le(t));let r=!1;!t.awsRegion&&process.env.AWS_REGION&&(t.awsRegion=process.env.AWS_REGION,r=!0),!t.awsProfile&&process.env.AWS_PROFILE&&(t.awsProfile=process.env.AWS_PROFILE,r=!0),r&&Le(t)}catch(r){Bd.warn("Config migration failed, using config as-is:",r instanceof Error?r.message:r)}return t}}catch(e){Bd.warn("[Config] Failed to load config file:",e)}return{}}function Le(e){let t=lr();Pn.existsSync(t)||Pn.mkdirSync(t,{recursive:!0}),Pn.writeFileSync(Gf(),JSON.stringify(e,null,2),"utf-8")}var ue,_r=G(()=>{"use strict";ue=ky});import{EOL as sa,homedir as IC,platform as Xf}from"os";import{readFileSync as vC,writeFileSync as kC}from"fs";import{join as Hd}from"path";import{spawnSync as MC}from"node:child_process";function Dy(){return ue().shiftEnterKeyBindingInstalled===!0}function As(){let e=(process.env.TERM_PROGRAM??"").toLowerCase();return Xf()==="darwin"&&e==="iterm.app"||e==="vscode"}function DC(){if(MC("defaults",["write","com.googlecode.iterm2","GlobalKeyMap","-dict-add","0xd-0x20000-0x24",`<dict>
|
|
320
|
-
<key>Text</key>
|
|
321
|
-
<string>\\n</string>
|
|
322
|
-
<key>Action</key>
|
|
323
|
-
<integer>12</integer>
|
|
324
|
-
<key>Version</key>
|
|
325
|
-
<integer>1</integer>
|
|
326
|
-
<key>Keycode</key>
|
|
327
|
-
<integer>13</integer>
|
|
328
|
-
<key>Modifiers</key>
|
|
329
|
-
<integer>131072</integer>
|
|
330
|
-
</dict>`]).status!==0)throw new Error("Failed to install iTerm2 Shift+Enter key binding");return`Installed iTerm2 Shift+Enter key binding${sa}See iTerm2 \u2192 Preferences \u2192 Keys${sa}`}function LC(){let e=Hd(IC(),Xf()==="win32"?Hd("AppData","Roaming","Code","User"):Xf()==="darwin"?Hd("Library","Application Support","Code","User"):Hd(".config","Code","User"),"keybindings.json"),t=[];try{let n=vC(e,"utf-8").trim();t=n?JSON.parse(n):[],Array.isArray(t)||(t=[])}catch{t=[]}return t.find(n=>n.key==="shift+enter"&&n.command==="workbench.action.terminal.sendSequence"&&n.when==="terminalFocus")?`Found existing VSCode terminal Shift+Enter key binding. Remove it to continue.${sa}See ${e}${sa}`:(t.push({key:"shift+enter",command:"workbench.action.terminal.sendSequence",args:{text:`\\\r
|
|
331
|
-
`},when:"terminalFocus"}),kC(e,JSON.stringify(t,null,2),"utf-8"),`Installed VSCode terminal Shift+Enter key binding${sa}See ${e}${sa}`)}function Wd(){if(!As())throw new Error("terminal-setup is supported only in iTerm2 (macOS) and VSCode terminal");let t=(process.env.TERM_PROGRAM??"").toLowerCase()==="vscode"?LC():DC(),r=ue();return r.shiftEnterKeyBindingInstalled=!0,Le(r),t}var qd=G(()=>{"use strict";_r()});function pT(e){let t=Qh.indexOf(e);return Qh[(t+1)%Qh.length]}function hT(e,t){let r=Il[e],n={};return t.showThinking!==r.showThinking&&(n.showThinking=t.showThinking),t.showCosts!==r.showCosts&&(n.showCosts=t.showCosts),t.showToolArgs!==r.showToolArgs&&(n.showToolArgs=t.showToolArgs),t.toolOutput!==r.toolOutput&&(n.toolOutput=t.toolOutput),t.showTraces!==r.showTraces&&(n.showTraces=t.showTraces),t.showPipelineTiming!==r.showPipelineTiming&&(n.showPipelineTiming=t.showPipelineTiming),t.showStatusBar!==r.showStatusBar&&(n.showStatusBar=t.showStatusBar),n}function gT(e,t){return{...Il[e],...t??{}}}var Il,Qh,Zh=G(()=>{"use strict";Il={minimal:{showThinking:!1,showCosts:!1,showToolArgs:!1,toolOutput:"hidden",showTraces:!1,showPipelineTiming:!1,showStatusBar:!1},standard:{showThinking:!0,showCosts:!0,showToolArgs:!0,toolOutput:"standard",showTraces:!1,showPipelineTiming:!1,showStatusBar:!0},debug:{showThinking:!0,showCosts:!0,showToolArgs:!0,toolOutput:"expanded",showTraces:!0,showPipelineTiming:!0,showStatusBar:!0}},Qh=["minimal","standard","debug"]});function kM(e){return typeof e!="string"||e.trim().length>0}function MM(e){let{toolCalls:t,...r}=e;return r}function DM(e,t,r){for(let n=t;n<e.length;n++){let o=e[n];if(o.role==="tool"&&o.toolCallId===r)return!0}return!1}function fi(e){let t=[];for(let r=0;r<e.length;r++){let n=e[r];if(n.role==="assistant"&&n.toolCalls?.length){let o=new Set(n.toolCalls.map(d=>d.id)),s=new Set,i=[],a=r+1;for(;a<e.length&&e[a].role==="tool";){let d=e[a];d.toolCallId&&o.has(d.toolCallId)&&!s.has(d.toolCallId)&&(s.add(d.toolCallId),i.push(d)),a++}let c=n.toolCalls.filter(d=>s.has(d.id)?!0:!DM(e,a,d.id)),l=c.filter(d=>!s.has(d.id));c.length===n.toolCalls.length?t.push(n):c.length>0?t.push({...n,toolCalls:c}):kM(n.content)&&t.push(MM(n)),t.push(...i);for(let d of l)t.push({role:"tool",content:`[Tool execution interrupted \u2014 no result for ${d.name}]`,toolCallId:d.id});r=a-1;continue}n.role!=="tool"&&t.push(n)}return t}var wT=G(()=>{"use strict"});var is,eg=G(()=>{"use strict";is=class e{textParts=[];thinkingBlocks=[];toolUseBlocks=[];handoffBlocks=[];toolResultMessages=[];seenToolIds=new Set;toolArgsAccumulator=new Map;thinkingInProgress=!1;pendingThinkingContent="";arion;verb;tokenUsage;snapshotMessages;previewAssistantId=`preview-${Date.now()}`;ingest(t){switch(t.type){case"text_delta":return this.textParts.push(t.content),"continue";case"thinking_start":return this.thinkingInProgress=!0,this.pendingThinkingContent="","continue";case"thinking_delta":return this.pendingThinkingContent+=t.content,"continue";case"thinking_end":{this.thinkingInProgress=!1;let r=Array.isArray(t.blocks)&&t.blocks.length>0?t.blocks[0]:void 0,n=typeof r?.thinking=="string"?r.thinking:this.pendingThinkingContent,o=n.split(/\s+/).filter(Boolean).length,s={type:"thinking",content:n,wordCount:o,durationMs:t.durationMs,verb:this.verb};return this.thinkingBlocks.push(s),this.pendingThinkingContent="","continue"}case"tool_start":{if(this.seenToolIds.has(t.id))return"continue";this.seenToolIds.add(t.id);let r={type:"tool_use",id:t.id,name:t.name,arguments:t.input??{}};return this.toolUseBlocks.push(r),"continue"}case"tool_args_delta":{let n=(this.toolArgsAccumulator.get(t.id)??"")+t.args;this.toolArgsAccumulator.set(t.id,n);try{let o=JSON.parse(n),s=this.toolUseBlocks.find(i=>i.type==="tool_use"&&i.id===t.id);s&&(s.arguments=o)}catch{}return"continue"}case"tool_result":{if(t.input){let i=this.toolUseBlocks.find(a=>a.type==="tool_use"&&a.id===t.id);if(i){let a=typeof t.input=="object"&&!Array.isArray(t.input)?t.input:{};Object.keys(i.arguments).length===0&&(i.arguments=a)}}let r=t.result,n="usage"in t&&t.usage&&typeof t.usage=="object"&&typeof t.usage.inputTokens=="number"&&typeof t.usage.outputTokens=="number"&&typeof t.usage.totalTokens=="number"&&typeof t.usage.estimatedCost=="number"?t.usage:void 0,o={type:"tool_result",toolUseId:t.id,content:typeof r.message=="string"?r.message:"",status:r.success===!0?"success":"error",durationMs:t.durationMs,resultData:r.data,usage:n},s={id:crypto.randomUUID(),role:"tool",content:[o],arion:this.arion,createdAt:new Date().toISOString()};return this.toolResultMessages.push(s),"continue"}case"handoff_start":{let r={type:"handoff",target:t.target,direction:"to"};return this.handoffBlocks.push(r),"continue"}case"handoff_result":{let r={type:"handoff",target:t.target,direction:"from"};return this.handoffBlocks.push(r),"continue"}case"turn_complete":return"flush";case"messages_snapshot":return this.snapshotMessages=t.messages,"continue";default:return"continue"}}flush(){let t=[];if(this.thinkingInProgress&&this.pendingThinkingContent){let o=this.pendingThinkingContent.trim(),s=o.length===0?0:o.split(/\s+/).length,i={type:"thinking",content:this.pendingThinkingContent,wordCount:s,verb:this.verb};this.thinkingBlocks.push(i)}let r=[];r.push(...this.thinkingBlocks);let n=this.textParts.join("");if(n&&r.push({type:"text",text:n}),r.push(...this.toolUseBlocks),r.push(...this.handoffBlocks),r.length>0){let o={id:crypto.randomUUID(),role:"assistant",content:r,arion:this.arion,tokenUsage:this.tokenUsage,createdAt:new Date().toISOString()};t.push(o)}if(t.push(...this.toolResultMessages),this.toolResultMessages.length>0&&this.toolUseBlocks.length>0){let o=new Set(this.toolResultMessages.flatMap(s=>s.content.filter(i=>i.type==="tool_result").map(i=>i.toolUseId)));for(let s of this.toolUseBlocks){let i=s.id;if(i&&!o.has(i)){let a={id:crypto.randomUUID(),role:"tool",content:[{type:"tool_result",toolUseId:i,content:"Tool execution cancelled by user.",status:"error"}],arion:this.arion,createdAt:new Date().toISOString()};t.push(a)}}}return this.textParts=[],this.thinkingBlocks=[],this.toolUseBlocks=[],this.handoffBlocks=[],this.toolResultMessages=[],this.seenToolIds=new Set,this.toolArgsAccumulator=new Map,this.thinkingInProgress=!1,this.pendingThinkingContent="",this.tokenUsage=void 0,this.verb=void 0,this.previewAssistantId=`preview-${Date.now()}`,t}snapshot(){let t=[];if(t.push(...this.thinkingBlocks.map(o=>({...o}))),this.thinkingInProgress&&this.pendingThinkingContent){let o=this.pendingThinkingContent,s={type:"thinking",content:o,wordCount:o.split(/\s+/).filter(Boolean).length,verb:this.verb};t.push(s)}let r=this.textParts.join("");if(r){let o=r.lastIndexOf(`
|
|
332
|
-
`);o>=0&&t.push({type:"text",text:r.slice(0,o+1)})}for(let o of this.toolUseBlocks){let s={...o};if(s.type==="tool_use"&&Object.keys(s.arguments).length===0){let i=this.toolArgsAccumulator.get(s.id);if(i){let a=e.tryParsePartialArgs(i);a&&(s.arguments=a)}}t.push(s)}t.push(...this.handoffBlocks.map(o=>({...o})));let n=[];return t.length>0&&n.push({id:this.previewAssistantId,role:"assistant",content:t,arion:this.arion,createdAt:new Date().toISOString()}),n.push(...this.toolResultMessages.map(o=>({...o,content:[...o.content]}))),n}getSnapshotMessages(){return this.snapshotMessages}hasPendingContent(){return this.textParts.length>0||this.thinkingBlocks.length>0||this.toolUseBlocks.length>0||this.handoffBlocks.length>0||this.toolResultMessages.length>0||this.thinkingInProgress}setArion(t){this.arion=t}setVerb(t){this.verb=t}setTokenUsage(t){this.tokenUsage?this.tokenUsage={input:this.tokenUsage.input+t.input,output:this.tokenUsage.output+t.output}:this.tokenUsage={...t}}static tryParsePartialArgs(t){let r=t.trim();if(!(!r.startsWith("{")||r.length<4)){try{return JSON.parse(r)}catch{}try{let n=JSON.parse(r+"}");if(Object.keys(n).length>0)return n}catch{}try{let n=JSON.parse(r+'"}');if(Object.keys(n).length>0)return n}catch{}for(let n=r.length-1;n>0;n--)if(r[n]===",")try{let o=JSON.parse(r.slice(0,n)+"}");if(Object.keys(o).length>0)return o}catch{}}}}});import{readFileSync as LM,existsSync as tg}from"node:fs";function rg(e){if(!tg(e))return[];let r=LM(e,"utf-8").split(`
|
|
333
|
-
`).filter(s=>s.trim().length>0),n=new is,o=[];for(let s of r){let i;try{i=JSON.parse(s)}catch{continue}if(!i.event||typeof i.event.type!="string")continue;if(i.event.type==="user_message"){n.hasPendingContent()&&o.push(...n.flush());let c=i.event.content??"",l=i.event.id,d=Gi(c);l&&(d.id=l),o.push(d);continue}if(n.ingest(i.event)==="flush"){let c=n.flush();o.push(...c)}}if(n.hasPendingContent()){let s=n.flush();o.push(...s)}return o}function yT(e){for(let r of e.content){if(r.type==="tool_use"&&r.id)return`tool_use:${r.id}`;if(r.type==="tool_result"&&r.toolUseId)return`tool_result:${r.toolUseId}`}let t=e.content.filter(r=>r.type==="text").map(r=>r.text).join("");return`${e.role}:${t}`}function wm(e,t){if(!t)return{messages:e,backfillMessages:[]};let r;try{r=rg(t)}catch{return{messages:e,backfillMessages:[]}}if(r.length===0)return{messages:e,backfillMessages:[]};if(e.length>=r.length)return{messages:e,backfillMessages:[]};let n=new Set(e.map(yT)),o=[];for(let i of r){let a=yT(i);n.has(a)||o.push(i)}return{messages:[...e,...o],backfillMessages:o}}function ym(e,t,r){let n=`${e}/arions/${t}/logs/${r}.jsonl`;if(tg(n))return n;let o=`${e}/logs/${r}.jsonl`;return tg(o)?o:null}var xT=G(()=>{"use strict";eg();Cc()});var ST={};Ln(ST,{ArionRefSchema:()=>Sf,ContentBlockSchema:()=>xf,ConversationMessageSchema:()=>Cd,SessionHistory:()=>Nn,TurnAccumulator:()=>is,conversationMessageToHistoryMessages:()=>Rw,createErrorMessage:()=>ee,createIncomingMessagePair:()=>Rd,createSystemMessage:()=>q,createUserMessage:()=>Gi,extractTextContent:()=>Ki,extractThinking:()=>Yi,extractToolCallId:()=>Ji,extractToolCalls:()=>Vi,findJsonlForSession:()=>ym,fromModelMessages:()=>Xi,fromV1Columns:()=>zi,mergeWithJsonlRecovery:()=>wm,repairToolCallPairing:()=>fi,replaySessionFromJsonl:()=>rg,toModelMessages:()=>Ad});var vl=G(()=>{"use strict";Tf();wT();Cc();eg();xT()});import{readFile as UM}from"fs/promises";import{join as _T}from"path";import{homedir as BM}from"os";async function CT(e){try{let t=await UM(e,"utf-8"),r=JSON.parse(t);if(r.mcp?.servers){for(let n of r.mcp.servers)if(n.env){for(let[o,s]of Object.entries(n.env))if(typeof s=="string"&&s.startsWith("${")&&s.endsWith("}")){let i=s.slice(2,-1);n.env[o]=process.env[i]||""}}}if(r.mcp?.servers)for(let n of r.mcp.servers){if(!n.name||typeof n.name!="string")throw new Error('Invalid MCP server config: missing "name" field');if(!n.transport)throw new Error(`MCP server "${n.name}": missing "transport" field`);if(n.transport&&!["stdio","sse"].includes(n.transport))throw new Error(`MCP server "${n.name}": unknown transport "${n.transport}"`);if(n.transport==="stdio"&&!n.command)throw new Error(`MCP server "${n.name}": stdio transport requires "command" field`);if(n.transport==="sse"&&!n.url)throw new Error(`MCP server "${n.name}": sse transport requires "url" field`)}return r}catch(t){if(t.code==="ENOENT")return null;throw t}}function RT(e,t){let r=e.mcp?.servers||[],n=t.mcp?.servers||[],o=new Set(n.map(s=>s.name));return{mcp:{servers:[...r.filter(s=>!o.has(s.name)),...n]}}}async function Sm(e){let t={...HM},r=_T(BM(),".aria","config.json"),n=await CT(r);if(n&&(t=RT(t,n)),e){let o=_T(e,"aria.config.json"),s=await CT(o);s&&(t=RT(t,s))}return t}var HM,AT=G(()=>{"use strict";HM={mcp:{servers:[]}}});import{readFileSync as WM}from"fs";import{join as qM}from"path";import{homedir as GM}from"os";import{parse as XM}from"yaml";import{log as zM}from"@aria-cli/types";function YM(){return{display:{...Il.standard,...VM},persistence:{...KM}}}function eD(e){return typeof e=="string"&&JM.has(e)}function tD(e){return typeof e=="string"&&QM.has(e)}function rD(e){return typeof e=="string"&&ZM.has(e)}function as(e){return typeof e=="boolean"}function cg(e){return typeof e=="number"&&Number.isInteger(e)&&e>0}function nD(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function oD(e){try{let t=WM(e,"utf-8"),r=XM(t);return r==null||typeof r!="object"?null:r}catch(t){if(t.code==="ENOENT")return null;throw t}}function sD(e){let t={};return eD(e.mode)&&(t.mode=e.mode),rD(e.theme)&&(t.theme=e.theme),as(e.thinking)&&(t.showThinking=e.thinking),as(e.costs)&&(t.showCosts=e.costs),as(e.toolArgs)&&(t.showToolArgs=e.toolArgs),tD(e.toolOutput)&&(t.toolOutput=e.toolOutput),as(e.traces)&&(t.showTraces=e.traces),as(e.pipelineTiming)&&(t.showPipelineTiming=e.pipelineTiming),as(e.statusBar)&&(t.showStatusBar=e.statusBar),as(e.syntaxHighlighting)&&(t.syntaxHighlighting=e.syntaxHighlighting),cg(e.maxToolOutputLines)&&(t.maxToolOutputLines=e.maxToolOutputLines),nD(e.maxThinkingPreview)&&(t.maxThinkingPreview=e.maxThinkingPreview),t}function iD(e){let t={};return as(e.jsonlEnabled)&&(t.jsonlEnabled=e.jsonlEnabled),(cg(e.jsonlRetentionDays)||e.jsonlRetentionDays===1/0)&&(t.jsonlRetentionDays=e.jsonlRetentionDays),(cg(e.jsonlMaxSizeMb)||e.jsonlMaxSizeMb===1/0)&&(t.jsonlMaxSizeMb=e.jsonlMaxSizeMb),e.otelEndpoint===null?t.otelEndpoint=null:typeof e.otelEndpoint=="string"&&e.otelEndpoint.length>0&&(t.otelEndpoint=e.otelEndpoint),t}function IT(e,t,r){return{...e,...t?lg(t):{},...r?lg(r):{}}}function dg(e){let t=YM(),r=e??qM(GM(),".aria","config.yaml"),n;try{n=oD(r)}catch(f){return zM.warn(`[AriaConfig] Failed to parse ${r}: ${f.message}. Using defaults.`),t}if(n===null)return t;let o=typeof n.display=="object"&&n.display!==null?n.display:{},s=sD(o),i=s.mode??t.display.mode,a=Il[i],c=IT(a,s),l=typeof n.persistence=="object"&&n.persistence!==null?n.persistence:{},d=iD(l);return{display:{...c,mode:i,theme:s.theme,syntaxHighlighting:s.syntaxHighlighting??t.display.syntaxHighlighting,maxToolOutputLines:s.maxToolOutputLines??t.display.maxToolOutputLines,maxThinkingPreview:s.maxThinkingPreview??t.display.maxThinkingPreview},persistence:{...t.persistence,...lg(d)}}}function lg(e){let t={};for(let[r,n]of Object.entries(e))n!==void 0&&(t[r]=n);return t}var KM,VM,JM,QM,ZM,vT=G(()=>{"use strict";Zh();KM={jsonlEnabled:!0,jsonlRetentionDays:1/0,jsonlMaxSizeMb:1/0,otelEndpoint:null},VM={mode:"standard",syntaxHighlighting:!0,maxToolOutputLines:5,maxThinkingPreview:80};JM=new Set(["minimal","standard","debug"]),QM=new Set(["hidden","collapsed","standard","expanded"]),ZM=new Set(["dark","light","dark-accessible","light-accessible","claude-dark","claude-light","claude-dark-daltonized","claude-light-daltonized"])});var ug=G(()=>{"use strict";AT();vT()});import{createRuntimeDefaultRouter as lD,getCliModels as bm,ModelDiscovery as dD}from"@aria-cli/models";import{createRuntimeAuthContext as uD}from"@aria-cli/auth";import{MemoriaPool as mD}from"@aria-cli/aria";async function cs(e){let t=ue(),r=await Sm(e?.cwd??process.cwd()),n=e?.startupMode??"interactive",o=t.awsRegion||process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION,s=t.awsProfile||process.env.AWS_PROFILE,i=!1;!t.awsRegion&&process.env.AWS_REGION&&(t.awsRegion=process.env.AWS_REGION,i=!0),!t.awsProfile&&process.env.AWS_PROFILE&&(t.awsProfile=process.env.AWS_PROFILE,i=!0),i&&Le(t),o&&!process.env.AWS_REGION&&(process.env.AWS_REGION=o),s&&!process.env.AWS_PROFILE&&(process.env.AWS_PROFILE=s);let c=uD({ariaHome:lr(),...o||s?{bedrock:{awsRegion:o,awsProfile:s}}:{}}).authResolver,l=await lD({ariaHome:lr(),authResolver:c,...o||s?{bedrock:{awsRegion:o,awsProfile:s}}:{}}),d=lr(),f=new mD(d,l),u=n!=="daemon"?await c.resolve("anthropic"):null,h=n!=="daemon"?await c.resolve("openai"):null,y=n!=="daemon"?await c.resolve("google"):null,S=n!=="daemon"?await c.resolve("github-copilot"):null,R=new dD({authResolver:c,googleApiKey:y?.apiKey||t.googleApiKey,anthropicApiKey:u?.apiKey||t.anthropicApiKey,openaiApiKey:h?.apiKey,awsRegion:o,awsProfile:s,cacheDir:d}),I=n==="daemon"?bm():bm(R.getCachedModels()),v=async T=>{if(n==="daemon")return bm();let E=T?await R.refresh(!0):await R.getCachedOrRefresh();return bm(E)},C={availableProviders:[...o?["bedrock","bedrock-converse"]:[],...u?.apiKey?["anthropic"]:[],...h?.apiKey?["openai"]:[],...S?.apiKey?["github-copilot"]:[],...y?.apiKey?["google"]:[]]};return{config:t,router:l,pool:f,memoriaFactory:f.toFactory(),ariaDir:d,projectConfig:r,discovery:R,availableModels:I,refreshAvailableModels:v,credentialHints:C,authResolver:c}}var Tm=G(()=>{"use strict";_r();ug()});import{RuntimeBootstrapRecordSchema as wY}from"@aria-cli/tools";function fD(e){return e==="control_ready"||e==="network_ready"||e==="mesh_ready"}function DT(e,t){if(t.nodeId!==e)throw new Error(`[local-control-client] Runtime bootstrap node mismatch for ${e}: received ${t.nodeId}`);if(!fD(t.phase))throw new Error(`[local-control-client] Runtime bootstrap for ${e} is not attachable (phase=${t.phase})`);return t}var LT=G(()=>{"use strict"});async function pD(){let e=lr();if(fg?.ariaDir===e)return fg.handler;let{CentralErrorHandler:t}=await import("@aria-cli/aria/error-handler"),r=new t({ariaDir:e});return fg={ariaDir:e,handler:r},r}async function NT(e,t){await(await pD()).report(e,{workingDir:process.cwd(),providerState:{lastProvider:"trusted-local-control",lastModel:t.endpoint,...typeof t.responseStatus=="number"?{lastStatusCode:t.responseStatus}:{}},configSnapshot:{transport:t.transport,endpoint:t.endpoint,...typeof t.responseStatus=="number"?{responseStatus:t.responseStatus}:{},payload:t.payload}})}var fg,OT=G(()=>{"use strict";_r()});var Rm={};Ln(Rm,{attachExistingLocalControlClient:()=>hg,attachLocalControlClient:()=>Dl,createResilientAttachedClient:()=>Cm,requestRuntimeSocketLease:()=>_m,resolveLocalControlClient:()=>Ll,resolveLocalControlClientSync:()=>gg});import*as UT from"node:net";import{appendFileSync as hD,mkdirSync as gD}from"node:fs";import{join as BT}from"node:path";import{randomUUID as wD}from"node:crypto";import{createRuntimeSocketAttachedLocalControlClient as HT,createRuntimeSocketLocalControlClient as yD,createTrustedRuntimeError as xD,AttachedClientLeaseGrantSchema as SD,LocalControlSocketAttachClientRequestSchema as bD,LocalControlSocketAttachClientResponseSchema as TD,LocalControlSocketRequestSchema as ED,LocalControlSocketResponseSchema as _D}from"@aria-cli/tools";async function WT(e){await new Promise(t=>setTimeout(t,Math.max(e,0)))}function AD(){return jT??=import("@aria-cli/server/runtime/host-supervisor"),jT}function ID(){return PT??=import("@aria-cli/server/runtime/node-metadata"),PT}function vD(){return $T??=import("@aria-cli/server/runtime/node-store"),$T}async function qT(e){let{resolveOrCreateNode:t}=await ID();return t({ariaHome:e})}async function Em(e,t){let{NodeStore:r}=await vD(),n=new r({ariaHome:e});try{return n.readRuntimeOwnerRecord(t)}finally{n.close()}}function pg(e){if(!(e instanceof Error))return!1;let t=e.message;return t.includes("connect ENOENT")||t.includes("ECONNREFUSED")||t.includes("Missing runtime owner record")||t.includes("not attachable")||t.includes("not control-ready")}async function Ml(e){let t=await Em(e.ariaHome,e.nodeId);if(!t)throw new Error(`[local-control-client] Missing runtime owner record for node ${e.nodeId}`);let r=kD({runtimeSocket:t.runtimeSocket,pollIntervalMs:e.pollIntervalMs}),n=DT(e.nodeId,await r.getRuntimeBootstrap()),o,s,i;e.clientKind&&(i=await Cm({runtimeSocket:t.runtimeSocket,clientKind:e.clientKind,logDir:BT(e.ariaHome,"logs")}),o=i.getClientId(),s=i.getClientAuthToken());let a=null;return{nodeId:e.nodeId,runtimeId:n.runtimeId,port:n.controlEndpoint.port,ownership:e.ownership,...o?{attachedClientId:o}:{},...s?{attachedClientAuthToken:s}:{},control:i?i.api:r,release:async c=>a||(a=(async()=>{let l=i;i=void 0,o=void 0,s=void 0,await l?.release().catch(()=>{}),await e.release(c)})(),a)}}async function _m(e,t){let r=ED.parse({id:wD(),method:"attachClient",payload:t});return new Promise((n,o)=>{let s=UT.createConnection(e),i="",a=!1,c=!1,l,d=new Promise(u=>{l=u}),f=()=>{c||(c=!0,l?.(),a||(a=!0,o(new Error("Local control socket closed before establishing an attached-client lease"))))};s.setEncoding("utf8"),s.once("connect",()=>{s.write(`${JSON.stringify(r)}
|
|
334
|
-
`)}),s.once("error",u=>{if(!a){a=!0,o(u);return}f()}),s.once("end",f),s.once("close",f),s.on("data",async u=>{i+=u;let h=i.indexOf(`
|
|
335
|
-
`);if(!(h===-1||a))try{let y=_D.parse(JSON.parse(i.slice(0,h)));if(y.id!==r.id){a=!0,s.destroy(),o(new Error("Local control socket response ID mismatch"));return}if(!y.ok){let R=xD(y.error,y.diagnostic);await NT(R,{endpoint:"attachClient",responseStatus:null,payload:y,transport:"runtime_socket_attach"}),a=!0,s.destroy(),o(R);return}let S=SD.parse(TD.parse(y.payload));a=!0,n({clientId:S.clientId,clientAuthToken:S.clientAuthToken,release:async()=>{c||s.destroy(),await d}})}catch(y){a=!0,s.destroy(),o(y)}})})}async function hg(e){let t=await qT(e.ariaHome);if(!await Em(e.ariaHome,t.nodeId))return null;let r=Date.now()+CD;for(;Date.now()<r;)try{return await Ml({ariaHome:e.ariaHome,nodeId:t.nodeId,ownership:"reattached",release:async()=>{},pollIntervalMs:e.pollIntervalMs,clientKind:e.clientKind})}catch(n){if(!pg(n))throw n;if(!await Em(e.ariaHome,t.nodeId))return null;await WT(RD)}return null}function kD(e){return e.auth?HT({runtimeSocket:e.runtimeSocket,pollIntervalMs:e.pollIntervalMs,auth:e.auth}):yD(e)}async function Dl(e){let t=async(i,a)=>{let c=e.pollIntervalMs??100,l=Date.now()+Math.max(c*20,2e3),d=null;for(;Date.now()<l;){if(e.signal?.aborted)throw new Error(`[local-control-client] Attach-only client ${a} aborted while waiting for a live runtime owner on node ${i}`);try{if(!await Em(e.ariaHome,i))d=new Error(`[local-control-client] No live runtime owner available for attach-only client ${a} on node ${i}`);else return await Ml({ariaHome:e.ariaHome,nodeId:i,ownership:"reattached",release:async()=>{},pollIntervalMs:e.pollIntervalMs,clientKind:a})}catch(f){if(!pg(f))throw f;d=f}await WT(c)}throw d??new Error(`[local-control-client] No live runtime owner available for attach-only client ${a} on node ${i}`)},{getHostSupervisor:r,HostSupervisorSplitBrainError:n}=await AD(),o=r(),s;try{s=await o.attach({ariaHome:e.ariaHome,arionName:e.arionName,clientKind:e.clientKind,memoriaFactory:e.memoriaFactory,router:e.router,authResolver:e.authResolver,runSessionConfig:e.runSessionConfig,mcpServers:e.mcpServers,daemonSafetyPolicy:e.daemonSafetyPolicy,autonomousIntervalMs:e.autonomousIntervalMs,signal:e.signal,silent:e.silent,runtimeLifecycle:e.runtimeLifecycle,port:e.port})}catch(i){if(i instanceof n)return Ml({ariaHome:e.ariaHome,nodeId:i.nodeId,ownership:"reattached",release:async()=>{},pollIntervalMs:e.pollIntervalMs,clientKind:e.clientKind});throw i}try{return await s.runtime.waitForInitialDiscovery(),await Ml({ariaHome:e.ariaHome,nodeId:s.nodeId,ownership:s.ownership,pollIntervalMs:e.pollIntervalMs,clientKind:e.clientKind,release:i=>s.release(i)})}catch(i){throw await s.release(),i}}async function Ll(e){let t=await qT(e.ariaHome);try{return(await Ml({ariaHome:e.ariaHome,nodeId:t.nodeId,ownership:"reattached",release:async()=>{},pollIntervalMs:e.pollIntervalMs})).control}catch(r){if(pg(r))return null;throw r}}function gg(e){return null}function Za(e){if(!(e instanceof Error))return!1;let t=e.message;return!!(t.includes("attached-local-client-only")||t.includes("ECONNRESET")||t.includes("ECONNREFUSED")||t.includes("EPIPE")||t.includes("connect ENOENT")||t.includes("socket hang up")||t.includes("closed before"))}function FT(e){return e<=0?Promise.resolve():new Promise(t=>{setTimeout(t,e).unref?.()})}async function Cm(e){let{runtimeSocket:t,clientKind:r="local-api"}=e,n=!1,o,s,i=null,a=null,c=y=>{if(e.logDir)try{gD(e.logDir,{recursive:!0}),hD(BT(e.logDir,"reattach.jsonl"),JSON.stringify({ts:new Date().toISOString(),pid:process.pid,...y})+`
|
|
336
|
-
`)}catch{}};async function l(){a&&(await a().catch(()=>{}),a=null);let y=await _m(t,bD.parse({clientKind:r,lease:!0,pid:process.pid,displayName:e.displayName}));o=y.clientId,s=y.clientAuthToken,a=()=>y.release(),i=HT({runtimeSocket:t,auth:{clientId:y.clientId,clientAuthToken:y.clientAuthToken}}),c({event:"lease_acquired",clientId:y.clientId})}await l();async function d(y,S){if(n)throw new Error("ResilientAttachedClient has been released");try{return await S(i)}catch(R){if(!Za(R))throw R;c({event:"reattach_start",method:y,error:R.message});for(let I=0;I<ls.length;I++){if(n)throw new Error("ResilientAttachedClient has been released");await FT(ls[I]??0);try{await l();let v=await S(i);return c({event:"reattach_success",method:y,attempt:I}),v}catch(v){if(c({event:"reattach_retry_failed",method:y,attempt:I,error:v.message,willRetry:Za(v)&&I<ls.length-1}),!Za(v)||I===ls.length-1)throw v}}throw R}}async function*f(y,S){if(n)throw new Error("ResilientAttachedClient has been released");try{yield*S(i);return}catch(R){if(!Za(R))throw R;c({event:"reattach_stream_start",method:y,error:R.message});for(let I=0;I<ls.length;I++){if(n)throw new Error("ResilientAttachedClient has been released");await FT(ls[I]??0);try{await l(),yield*S(i),c({event:"reattach_stream_success",method:y,attempt:I});return}catch(v){if(c({event:"reattach_stream_retry_failed",method:y,attempt:I,error:v.message,willRetry:Za(v)&&I<ls.length-1}),!Za(v)||I===ls.length-1)throw v}}}}let u=new Set(["streamRun","subscribeRuntimeEvents","subscribeInbox","subscribePeers","subscribeDirectClientInbox"]);return{api:new Proxy({},{get(y,S){if(!(S==="then"||S==="catch"||S==="finally"))return u.has(S)?(...R)=>f(S,I=>I[S](...R)):(...R)=>d(S,I=>I[S](...R))}}),getClientId:()=>o,getClientAuthToken:()=>s,release:async()=>{n=!0;let y=new Error("release() caller").stack;a&&(await a().catch(()=>{}),a=null),c({event:"released",clientId:o,releaseStack:y})}}}var CD,RD,jT,PT,$T,ls,Nl=G(()=>{"use strict";LT();OT();CD=1e4,RD=250;ls=[0,250,500,1e3]});var GT={};Ln(GT,{attachExistingLocalControlClient:()=>hg,attachLocalControlClient:()=>Dl,createResilientAttachedClient:()=>Cm,requestRuntimeSocketLease:()=>_m,resolveLocalControlClient:()=>Ll,resolveLocalControlClientSync:()=>gg});var Am=G(()=>{"use strict";Nl()});import{HEADLESS_OPERATION_SCHEMAS as MD}from"@aria-cli/tools";function F(e,t,r){let n=MD[t].result.safeParse(r);if(!n.success)throw new Error(`Invalid headless result for ${t}: ${n.error.issues.map(o=>`${o.path.join(".")||"<root>"} ${o.message}`).join("; ")}`);return{kind:"result",requestId:e,op:t,ok:!0,result:n.data}}function ie(e,t,r,n,o){return{kind:"result",requestId:e,op:t,ok:!1,error:{code:r,message:n,...o?{details:o}:{}}}}function pe(e,t){return async function*(r){yield ie(r,t,"MISSING_SERVICE",`Kernel service ${e} is not configured for ${t}.`)}}var Er=G(()=>{"use strict"});function DD(e){return{name:e.name??"ARIA",...e.emoji?{emoji:e.emoji}:{},personality:{traits:["helpful","curious"],style:"friendly"},...e.description?{profile:{background:e.description}}:{},createdBy:"headless"}}function LD(e,t){let r=t?.trim();return r?`I want to create a new arion named "${e}". ${r}`:`I want to create a new arion named "${e}". Help me design their personality.`}function wg(e){let t=e.arionManager;return!t?.list||!t.hatch||!t.get||!t.wake||!t.rest?{"arion.list":pe("arionManager","arion.list"),"arion.hatch":pe("arionManager","arion.hatch"),"arion.become":pe("arionManager","arion.become"),"arion.rest":pe("arionManager","arion.rest"),"arion.wake":pe("arionManager","arion.wake"),"arion.create":pe("arionManager","arion.create")}:{"arion.list":async function*(r){let n=t.list;yield F(r,"arion.list",{arions:await n()})},"arion.hatch":async function*(r,n){let o=t.get,s=n.name?.trim(),i=n.description?.trim();if(!s){yield ie(r,"arion.hatch","ARION_HATCH_FAILED","arion.hatch requires a name");return}if(await o(s)){yield ie(r,"arion.hatch","ARION_ALREADY_EXISTS",`An arion named "${s}" already exists.`);return}yield F(r,"arion.hatch",{mode:"guided",prompt:LD(s,i),name:s,...i?{description:i}:{}})},"arion.create":async function*(r,n){let o=t.hatch,s=await o(DD(n));yield F(r,"arion.create",{arion:s})},"arion.become":async function*(r,n){let o=t.get,s=t.wake,i=n.name?.trim();if(!i){yield ie(r,"arion.become","ARION_BECOME_FAILED","arion.become requires a name");return}let a=await o(i);if(!a){yield ie(r,"arion.become","ARION_NOT_FOUND",`Arion ${i} not found`);return}a.status==="resting"&&await s(i),await e.config?.setActiveArion?.(i);let c=await e.config?.getActiveArion?.()??i;yield F(r,"arion.become",{arion:a,activeArion:c})},"arion.rest":async function*(r,n){let o=t.rest,s=n.name?.trim();if(!s){yield ie(r,"arion.rest","ARION_REST_FAILED","arion.rest requires a name");return}await o(s),yield F(r,"arion.rest",{success:!0,name:s})},"arion.wake":async function*(r,n){let o=t.wake,s=n.name?.trim();if(!s){yield ie(r,"arion.wake","ARION_WAKE_FAILED","arion.wake requires a name");return}await o(s),yield F(r,"arion.wake",{success:!0,name:s})}}}var yg=G(()=>{"use strict";Er()});function xg(e,t){let r=e.auth;return!r?.status||!r.login||!r.logout?{"auth.status":pe("auth","auth.status"),"auth.login":pe("auth","auth.login"),"auth.logout":pe("auth","auth.logout")}:{"auth.status":async function*(n){let o=await r.status();yield F(n,"auth.status",{...o&&typeof o=="object"?o:{}})},"auth.login":async function*(n,o,s){yield*t.login(n,o,s)},"auth.logout":async function*(n,o){yield*t.logout(n,o)}}}var Sg=G(()=>{"use strict";Er()});import{ensureAuthProfileStore as ec,syncExternalCliCredentials as Ol,isProfileInCooldown as ND,upsertAuthProfile as so,updateAuthProfileStoreWithLockSync as OD,refreshBedrockSsoToken as jD,loginBedrockSso as PD,listProfilesForProvider as tc,loginWithGitHubCopilotToken as bg,readClaudeCodeCredentialsCached as XT,readCodexCredentialsCached as zT,readGeminiCredentialsCached as KT,normalizeProviderId as $D,OPENAI_CODEX_OAUTH_PROFILE_ID as FD}from"@aria-cli/auth";import{spawnSync as km}from"node:child_process";function UD(){try{let e=km("gh",["auth","token","-h","github.com"],{encoding:"utf8",timeout:5e3});if(e.error)return{error:e.error.message};if(e.status!==0){let r=(e.stderr||"").trim(),n=(e.stdout||"").trim();return{error:r||n||`gh auth token exited with status ${e.status}`}}let t=(e.stdout||"").trim();return t.length<8?{error:"gh auth token returned an empty/short token"}:{token:t}}catch(e){return{error:e instanceof Error?e.message:String(e)}}}function BD(e="github.com"){try{let t=km("gh",["auth","status","-h",e],{encoding:"utf8",timeout:5e3}),r=`${t.stdout||""}
|
|
337
|
-
${t.stderr||""}`,n=new Set;for(let o of r.split(/\r?\n/)){let s=o.match(/Logged in to .* account\s+([^\s]+)/i);s?.[1]&&n.add(s[1])}return[...n]}catch{return[]}}function HD(e,t="github.com"){try{let r=km("gh",["auth","token","-h",t,"-u",e],{encoding:"utf8",timeout:5e3});if(r.error)return{error:r.error.message};if(r.status!==0)return{error:(r.stderr||r.stdout||"").trim()||"gh token failed"};let n=(r.stdout||"").trim();return n.length<8?{error:"empty/short token"}:{token:n}}catch(r){return{error:r instanceof Error?r.message:String(r)}}}function WD(){try{let e=`${process.env.HOME||""}/.copilot/config.json`,r=(km("node",["-e",`const fs=require('fs');const p=${JSON.stringify(e)};if(!fs.existsSync(p)){process.exit(0);}const j=JSON.parse(fs.readFileSync(p,'utf8'));const login=j?.last_logged_in_user?.login||j?.logged_in_users?.[0]?.login||'';if(login)process.stdout.write(login);`],{encoding:"utf8",timeout:5e3}).stdout||"").trim();return r?{login:r}:{}}catch(e){return{error:e instanceof Error?e.message:String(e)}}}function qD(e){let t=e?.trim()??"";if(!t)return{useGhToken:!0,autoSelectSource:!0};let r=t.split(/\s+/).filter(Boolean),n,o,s=!0,i=!1,a=c=>{let l=r[c+1];return l&&!l.startsWith("--")?l:void 0};for(let c=0;c<r.length;c+=1){let l=r[c];if(l==="--profile"||l==="--label"){let d=a(c);d&&(o=d,c+=1);continue}if(l.startsWith("--profile=")||l.startsWith("--label=")){o=l.split("=",2)[1]?.trim()||o;continue}if(l==="--source"){let d=a(c)?.toLowerCase();d==="device"?s=!1:d==="auto"&&(i=!0),c+=d?1:0;continue}if(l.startsWith("--source=")){let d=l.split("=",2)[1]?.toLowerCase();d==="device"?s=!1:d==="auto"&&(i=!0);continue}!l.startsWith("--")&&!n&&(n=l,s=!1)}return n&&n.length>0&&(s=!1),{token:n,profileLabel:o,useGhToken:s,autoSelectSource:i}}function vm(e){let t=(e||"").trim();if(t)return t.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||void 0}function VT(){let e=[],t=new Set,r=["GH_TOKEN","GITHUB_TOKEN","COPILOT_GITHUB_TOKEN"];for(let a of r){let c=process.env[a]?.trim();if(c&&c.length>=8){let l=`env:${a}`;t.has(l)||(e.push({id:l,label:`Using ${a} from environment`,source:"env",token:c,status:"connected"}),t.add(l));break}}let n=BD("github.com");for(let a of n){let c=HD(a,"github.com").token,l=`GitHub CLI account: ${a}`,d=`gh:${a}`;t.has(d)||(e.push({id:d,label:l,source:"gh",login:a,token:c,profileLabel:vm(a),status:c?"connected":"none"}),t.add(d))}let o=ec();Ol(o);let s=tc(o,"github-copilot");for(let a of s){let c=o.profiles[a];if(!c)continue;let l=a.split(":").slice(1).join(":")||a,d=`profile:${l}`;if(t.has(d))continue;let f=c.type==="oauth"&&c.refresh?c.refresh:void 0,u=c.type==="oauth"&&Date.now()<c.expires;e.push({id:d,label:`Copilot profile: ${l}`,source:"copilot",login:l,token:f,profileLabel:vm(l),status:u||f?"connected":"none"}),t.add(d)}let i=WD();if(i.login){let a=`copilot:${i.login}`;!t.has(a)&&!t.has(`profile:${i.login}`)&&(e.push({id:a,label:`Copilot CLI last login: ${i.login}`,source:"copilot",login:i.login,profileLabel:vm(i.login),status:"connected"}),t.add(a))}return e.push({id:"device:new",label:"Sign in with a new GitHub account (device flow)",source:"device",status:"none"}),e}function GD(){let e=[],t=process.env.ANTHROPIC_API_KEY?.trim();if(t&&t.length>8){let s=t.startsWith("sk-ant-api");e.push({id:"env-key",label:"Using ANTHROPIC_API_KEY from environment",description:s?"API key detected":"Key format unrecognized",method:"env-key",status:s?"connected":"none"})}let r=ec();Ol(r);let n=tc(r,"anthropic");for(let s of n){let i=r.profiles[s];if(!i)continue;let a=(i.type==="oauth"||i.type==="token")&&"expires"in i&&typeof i.expires=="number"&&i.expires>Date.now();e.push({id:`profile:${s}`,label:`Saved profile: ${s}`,description:a?"Credentials active":"Credentials expired \u2014 will refresh on use",method:"api-key",status:a?"connected":"available"})}let o=XT();if(o){let s=o.expires>Date.now();e.push({id:"claude-cli",label:"Import from Claude Code CLI",description:s?"Use existing Claude Code credentials from keychain":"Credentials expired, will refresh",method:"claude-cli",status:s?"connected":"available"})}e.push({id:"subscription",label:"Claude account with subscription",description:"Pro, Max, Team, or Enterprise",method:"subscription",status:Tg("anthropic")==="connected"?"connected":"none"}),e.push({id:"console",label:"Anthropic Console account",description:"API usage billing",method:"console",status:"none"}),e.push({id:"setup-token",label:"Paste setup-token",description:"From `claude setup-token` or admin provisioning",method:"setup-token",status:"none"});{let s=Tg("bedrock"),i=!!process.env.AWS_PROFILE?.trim();e.push({id:"bedrock",label:"3rd-party platform",description:i?`Amazon Bedrock (AWS_PROFILE=${process.env.AWS_PROFILE})`:"Amazon Bedrock \u2014 set AWS_PROFILE to configure",method:"bedrock",status:s==="connected"?"connected":i?"available":"none"})}return e}async function XD(e){switch(e){case"subscription":return{mode:"oauth",provider:"anthropic"};case"console":case"api-key":return{mode:"anthropic_key_input",provider:"anthropic"};case"setup-token":return{mode:"anthropic_setup_token",provider:"anthropic"};case"env-key":{let t=process.env.ANTHROPIC_API_KEY?.trim();return t?(so({profileId:"anthropic:env",credential:{type:"api_key",provider:"anthropic",key:t}}),{mode:"direct",result:{success:!0,message:"Saved ANTHROPIC_API_KEY from environment"}}):{mode:"direct",result:{success:!1,message:"ANTHROPIC_API_KEY not set in environment"}}}case"claude-cli":{let t=XT();return t?t.type==="oauth"?(so({profileId:"anthropic:claude-cli",credential:{type:"oauth",provider:"anthropic",access:t.access,refresh:t.refresh,expires:t.expires}}),{mode:"direct",result:{success:!0,message:"Imported Claude Code OAuth credentials"}}):t.type==="token"?(so({profileId:"anthropic:claude-cli",credential:{type:"token",provider:"anthropic",token:t.token,expires:t.expires}}),{mode:"direct",result:{success:!0,message:"Imported Claude Code token"}}):{mode:"direct",result:{success:!1,message:"Unknown Claude Code credential type"}}:{mode:"direct",result:{success:!1,message:"No Claude Code credentials found. Run `claude login` first."}}}case"bedrock":return YT();default:return e.startsWith("profile:")?{mode:"direct",result:{success:!0,message:`Selected profile: ${e.replace("profile:","")}`}}:{mode:"direct",result:{success:!1,message:`Unknown method: ${e}`}}}}function zD(){let e=[],t=process.env.OPENAI_API_KEY?.trim();if(t&&t.length>8){let s=t.startsWith("sk-");e.push({id:"env-key",label:"Using OPENAI_API_KEY from environment",description:s?"API key detected":"Key format unrecognized",method:"env-key",status:s?"connected":"none"})}let r=ec();Ol(r);let n=new Set;for(let s of["openai","openai-codex"]){let i=tc(r,s);for(let a of i){if(n.has(a))continue;n.add(a);let c=r.profiles[a];if(!c)continue;let l=(c.type==="oauth"||c.type==="token")&&"expires"in c&&typeof c.expires=="number"&&c.expires>Date.now();e.push({id:`profile:${a}`,label:`Saved profile: ${a}`,description:l?"Credentials active":"Credentials expired \u2014 will refresh on use",method:"profile",status:l?"connected":"available"})}}let o=zT();if(o){let s=o.expires>Date.now();e.push({id:"codex-import",label:"Import from Codex CLI",description:s?"Use existing Codex credentials":"Credentials expired, will refresh",method:"codex-import",status:s?"connected":"available"})}return e.push({id:"api-key",label:"Paste API key",description:"Enter your OpenAI sk-* API key",method:"api-key",status:"none"}),e}async function KD(e){switch(e){case"api-key":return{mode:"openai_key_input",provider:"openai"};case"env-key":{let t=process.env.OPENAI_API_KEY?.trim();return t?(so({profileId:"openai:env",credential:{type:"api_key",provider:"openai",key:t}}),{mode:"direct",result:{success:!0,message:"Saved OPENAI_API_KEY from environment"}}):{mode:"direct",result:{success:!1,message:"OPENAI_API_KEY not set in environment"}}}case"codex-import":{let t=zT();return t?(so({profileId:FD,credential:{type:"oauth",provider:"openai",access:t.access,refresh:t.refresh,expires:t.expires}}),{mode:"direct",result:{success:!0,message:"Imported Codex CLI OAuth credentials"}}):{mode:"direct",result:{success:!1,message:"No Codex CLI credentials found. Run `codex auth` first."}}}default:return e.startsWith("profile:")?{mode:"direct",result:{success:!0,message:`Selected profile: ${e.replace("profile:","")}`}}:{mode:"direct",result:{success:!1,message:`Unknown method: ${e}`}}}}function VD(){let e=[],t=(process.env.GOOGLE_API_KEY??process.env.GEMINI_API_KEY)?.trim();if(t&&t.length>8){let s=t.startsWith("AIza");e.push({id:"env-key",label:`Using ${process.env.GOOGLE_API_KEY?"GOOGLE_API_KEY":"GEMINI_API_KEY"} from environment`,description:s?"API key detected":"Key format unrecognized",method:"env-key",status:s?"connected":"none"})}let r=ec();Ol(r);let n=tc(r,"google");for(let s of n){let i=r.profiles[s];if(!i)continue;let a=(i.type==="oauth"||i.type==="token")&&"expires"in i&&typeof i.expires=="number"&&i.expires>Date.now();e.push({id:`profile:${s}`,label:`Saved profile: ${s}`,description:a?"Credentials active":"Credentials expired \u2014 will refresh on use",method:"profile",status:a?"connected":"available"})}let o=KT();if(o){let s=o.expires>Date.now();e.push({id:"gemini-import",label:"Import from Gemini CLI",description:s?"Use existing Gemini CLI credentials":"Credentials expired, will refresh",method:"gemini-import",status:s?"connected":"available"})}return e.push({id:"api-key",label:"Paste API key",description:"Enter your Google AIza* API key",method:"api-key",status:"none"}),e.push({id:"oauth",label:"Gemini CLI OAuth",description:"Sign in via browser-based OAuth flow",method:"oauth",status:"none"}),e}async function YD(e){switch(e){case"api-key":return{mode:"google_key_input",provider:"google"};case"oauth":return{mode:"oauth",provider:"google"};case"env-key":{let t=(process.env.GOOGLE_API_KEY??process.env.GEMINI_API_KEY)?.trim();return t?(so({profileId:"google:env",credential:{type:"api_key",provider:"google",key:t}}),{mode:"direct",result:{success:!0,message:"Saved Google API key from environment"}}):{mode:"direct",result:{success:!1,message:"GOOGLE_API_KEY / GEMINI_API_KEY not set in environment"}}}case"gemini-import":{let t=KT();return t?(so({profileId:"google:gemini-cli",credential:{type:"oauth",provider:"google",access:t.access,refresh:t.refresh,expires:t.expires}}),{mode:"direct",result:{success:!0,message:"Imported Gemini CLI OAuth credentials"}}):{mode:"direct",result:{success:!1,message:"No Gemini CLI credentials found. Run `gemini auth` first."}}}default:return e.startsWith("profile:")?{mode:"direct",result:{success:!0,message:`Selected profile: ${e.replace("profile:","")}`}}:{mode:"direct",result:{success:!1,message:`Unknown method: ${e}`}}}}function QD(e){return Eg.includes(e)}function Tg(e){let t=OD({updater:s=>Ol(s)})??ec(),r=$D(e),n=tc(t,r);for(let s of n){let i=t.profiles[s];if(i&&!ND(t,s)){if(i.type==="api_key"&&i.key?.trim())return"connected";if(i.type==="oauth"&&"expires"in i){let a=i.expires;if(a&&a<Date.now())continue;return"connected"}if(i.type==="token"){let a=i.expires;if(!a||Date.now()<a)return"connected";continue}return"connected"}}let o=ZD[r]??[];for(let s of o)if(process.env[s]?.trim())return"connected";return n.length>0?"expired":"none"}function pi(){return Eg.map(e=>{let t=Tg(e),r=ec(),n=tc(r,e),o;for(let s of n){let i=r.profiles[s];if(i?.email){o=i.email;break}}return{id:e,label:JD[e],status:t,...o?{email:o}:{}}})}async function YT(e){return await jD(e)?{mode:"direct",result:{success:!0,message:"Bedrock SSO token refreshed (silent)"}}:await PD(e)?{mode:"direct",result:{success:!0,message:"Bedrock SSO login succeeded \u2014 credentials refreshed"}}:{mode:"direct",result:{success:!1,message:["Bedrock SSO login failed.","Try running manually: aws sso login --profile "+(e||process.env.AWS_PROFILE||"default")].join(`
|
|
338
|
-
`)}}}function Im(e,t){if(t.length<8)return{mode:"direct",result:{success:!1,message:"API key too short (minimum 8 characters)"}};let r=`${e}:manual`;return so({profileId:r,credential:{type:"api_key",provider:e,key:t}}),{mode:"direct",result:{success:!0,message:`Saved ${e} API key (profile: ${r})`}}}function eL(e){if(e.length<8)return{mode:"direct",result:{success:!1,message:"Setup token too short (minimum 8 characters)"}};let t="anthropic:setup-token";return so({profileId:t,credential:{type:"api_key",provider:"anthropic",key:e}}),{mode:"direct",result:{success:!0,message:`Saved Anthropic setup token (profile: ${t})`}}}async function tL(e,t){if(!QD(e))return{mode:"direct",result:{success:!1,message:`Unknown provider "${e}". Supported: ${Eg.join(", ")}`}};if(e==="bedrock"){let n=t?.trim()||void 0;return YT(n)}if(e==="github-copilot"){let n=qD(t);if(!n.token&&!n.profileLabel&&n.autoSelectSource)return{mode:"copilot_source_picker",provider:"github-copilot",options:VT()};if(n.token){let o=await bg({githubToken:n.token,profileLabel:n.profileLabel});return{mode:"direct",result:{success:o.success,message:o.message}}}if(n.useGhToken){let o=UD();if(o.token){let s=await bg({githubToken:o.token,profileLabel:n.profileLabel});return s.success?{mode:"direct",result:{success:!0,message:`${s.message} (imported from gh auth token)`}}:{mode:"copilot_device",provider:"github-copilot",profileLabel:n.profileLabel,message:`gh auth token import failed: ${s.message}
|
|
339
|
-
Falling back to interactive device login...`}}return{mode:"copilot_device",provider:"github-copilot",profileLabel:n.profileLabel,...o.error?{message:`Could not read gh auth token: ${o.error}`}:{}}}return{mode:"copilot_device",provider:"github-copilot",profileLabel:n.profileLabel}}if(e==="anthropic"){let n=t?.trim();if(n?.startsWith("--setup-token")){let s=n.replace(/^--setup-token\s*/,"").trim();return eL(s)}if(n?.startsWith("--method")){let s=n.replace(/^--method\s*/,"").trim();return XD(s)}return n?Im(e,n):{mode:"anthropic_method_picker",provider:"anthropic",options:GD()}}if(e==="openai"){let n=t?.trim();if(n?.startsWith("--method")){let s=n.replace(/^--method\s*/,"").trim();return KD(s)}return n?Im(e,n):{mode:"openai_method_picker",provider:"openai",options:zD()}}if(e==="google"){let n=t?.trim();if(n?.startsWith("--method")){let s=n.replace(/^--method\s*/,"").trim();return YD(s)}return n?Im(e,n):{mode:"google_method_picker",provider:"google",options:VD()}}let r=t?.trim();return r?Im(e,r):{mode:"oauth",provider:e}}async function Mm(e){let t=e.trim().split(/\s+/),r=t[0]?.toLowerCase()||"",n=t.slice(1).join(" ").trim();if(!r)return{mode:"picker",providers:pi()};if(r==="github-copilot"&&n.startsWith("--from ")){let o=n.slice(7).trim(),i=VT().find(a=>a.id===o);if(!i)return{mode:"direct",result:{success:!1,message:`Unknown Copilot source: ${o}`}};if(i.source==="device")return{mode:"copilot_device",provider:"github-copilot",profileLabel:i.profileLabel};if(i.token){let a=await bg({githubToken:i.token,profileLabel:i.profileLabel});return{mode:"direct",result:{success:a.success,message:a.message}}}if(i.login)return{mode:"copilot_device",provider:"github-copilot",profileLabel:vm(i.login)}}return tL(r,n||void 0)}var Eg,JD,ZD,Dm=G(()=>{"use strict";Eg=["bedrock","anthropic","google","openai","github-copilot"],JD={bedrock:"Bedrock (AWS SSO)",anthropic:"Anthropic",google:"Google (Gemini)",openai:"OpenAI","github-copilot":"GitHub Copilot"};ZD={anthropic:["ANTHROPIC_API_KEY"],openai:["OPENAI_API_KEY"],google:["GOOGLE_API_KEY","GEMINI_API_KEY"],"github-copilot":["GH_TOKEN","GITHUB_TOKEN","COPILOT_GITHUB_TOKEN"],bedrock:["AWS_PROFILE"]}});import{ensureAuthProfileStore as JT,listProfilesForProvider as rL,updateAuthProfileStoreWithLockSync as QT}from"@aria-cli/auth";function nL(e){let t=JT(),r=rL(t,e);if(r.length===0)return{success:!1,message:`No credentials found for "${e}"`};QT({updater:o=>{for(let s of r){let i=o.profiles[s]?.provider;delete o.profiles[s],i&&o.lastGood&&delete o.lastGood[i]}if(o.usageStats)for(let s of r)delete o.usageStats[s];return!0}});let n=r.length===1?"profile":"profiles";return{success:!0,message:`Disconnected ${e} (removed ${r.length} ${n})`}}function oL(){let e=JT(),t=Object.keys(e.profiles).length;return t===0?{success:!1,message:"No providers connected"}:(QT({updater:n=>(n.profiles={},n.lastGood=void 0,n.usageStats=void 0,!0)}),{success:!0,message:`Cleared all credentials (${t} ${t===1?"profile":"profiles"} removed)`})}function Lm(e){let t=e.trim().toLowerCase();if(t==="all")return{mode:"direct",result:oL()};if(t)return{mode:"direct",result:nL(t)};let n=pi().filter(o=>o.status!=="none");return n.length===0?{mode:"direct",result:{success:!0,message:"No providers connected"}}:{mode:"picker",providers:n}}var _g=G(()=>{"use strict";Dm()});function ZT(){return pi()}async function eE(e){return Mm(e)}function tE(e){return Lm(e)}function rE(e){if(typeof e.args=="string"&&e.args.trim().length>0)return e.args.trim();let t=[];return typeof e.provider=="string"&&e.provider.trim().length>0&&t.push(e.provider.trim()),typeof e.method=="string"&&e.method.trim().length>0&&t.push(e.method.trim()),typeof e.source=="string"&&e.source.trim().length>0&&t.push("--source",e.source.trim()),typeof e.profileLabel=="string"&&e.profileLabel.trim().length>0&&t.push("--profile",e.profileLabel.trim()),typeof e.credential=="string"&&e.credential.trim().length>0&&t.push(e.credential.trim()),t.join(" ")}function nE(e){return typeof e.args=="string"&&e.args.trim().length>0?e.args.trim():typeof e.provider=="string"&&e.provider.trim().length>0?e.provider.trim():""}var oE=G(()=>{"use strict";Dm();_g()});function sE(e){return"listAttachedClients"in e&&typeof e.listAttachedClients=="function"&&"listDirectClientInbox"in e&&typeof e.listDirectClientInbox=="function"}function Cg(e){return{"client.list":async function*(t){if(!sE(e.localControl)){yield ie(t,"client.list","MISSING_SERVICE","Attached local-control client directory is unavailable.");return}yield F(t,"client.list",{clients:await e.localControl.listAttachedClients()})},"client.inbox.list":async function*(t,r){if(!sE(e.localControl)){yield ie(t,"client.inbox.list","MISSING_SERVICE","Attached local-control client inbox is unavailable.");return}yield F(t,"client.inbox.list",{events:await e.localControl.listDirectClientInbox(r)})}}}var Rg=G(()=>{"use strict";Er()});function Ag(e){let t=e.config;return!t?.getTheme||!t.setTheme||!t.getAutonomy||!t.setAutonomy?{"config.theme.get":pe("config","config.theme.get"),"config.theme.set":pe("config","config.theme.set"),"config.autonomy.get":pe("config","config.autonomy.get"),"config.autonomy.set":pe("config","config.autonomy.set")}:{"config.theme.get":async function*(r){try{yield F(r,"config.theme.get",{theme:await t.getTheme()})}catch(n){yield ie(r,"config.theme.get","CONFIG_THEME_GET_FAILED",n instanceof Error?n.message:String(n))}},"config.theme.set":async function*(r,n){let o=n.theme?.trim();if(!o){yield ie(r,"config.theme.set","CONFIG_THEME_SET_FAILED","config.theme.set requires a theme");return}try{let s=await t.setTheme(o);yield F(r,"config.theme.set",{theme:o,...s&&typeof s=="object"?s:{}})}catch(s){yield ie(r,"config.theme.set","CONFIG_THEME_SET_FAILED",s instanceof Error?s.message:String(s))}},"config.autonomy.get":async function*(r){try{yield F(r,"config.autonomy.get",{autonomy:await t.getAutonomy()})}catch(n){yield ie(r,"config.autonomy.get","CONFIG_AUTONOMY_GET_FAILED",n instanceof Error?n.message:String(n))}},"config.autonomy.set":async function*(r,n){let o=n.autonomy?.trim();if(!o){yield ie(r,"config.autonomy.set","CONFIG_AUTONOMY_SET_FAILED","config.autonomy.set requires an autonomy level");return}try{let s=await t.setAutonomy(o);yield F(r,"config.autonomy.set",{autonomy:o,...s&&typeof s=="object"?s:{}})}catch(s){yield ie(r,"config.autonomy.set","CONFIG_AUTONOMY_SET_FAILED",s instanceof Error?s.message:String(s))}}}}var Ig=G(()=>{"use strict";Er()});function iE(e){let t=e.daemon;return!t?.start||!t.status||!t.stop?{"daemon.start":pe("daemon","daemon.start"),"daemon.status":pe("daemon","daemon.status"),"daemon.stop":pe("daemon","daemon.stop")}:{"daemon.start":async function*(r,n){try{yield F(r,"daemon.start",await t.start(n))}catch(o){yield ie(r,"daemon.start","DAEMON_START_FAILED",o instanceof Error?o.message:String(o))}},"daemon.status":async function*(r,n){try{yield F(r,"daemon.status",await t.status(n))}catch(o){yield ie(r,"daemon.status","DAEMON_STATUS_FAILED",o instanceof Error?o.message:String(o))}},"daemon.stop":async function*(r,n){try{yield F(r,"daemon.stop",await t.stop(n))}catch(o){yield ie(r,"daemon.stop","DAEMON_STOP_FAILED",o instanceof Error?o.message:String(o))}}}}var aE=G(()=>{"use strict";Er()});function vg(e){let t=e.memoria;return t?{"memory.remember":async function*(r,n){let o=n.text?.trim();if(!o){yield ie(r,"memory.remember","MEMORY_REMEMBER_FAILED","memory.remember requires text");return}let s=await t.remember(o);if(!s?.id){yield ie(r,"memory.remember","MEMORY_REMEMBER_FAILED","Failed to store memory");return}let i=await t.count(),a=o.length>50?`${o.slice(0,50)}...`:o;yield F(r,"memory.remember",{success:!0,message:`Remembered: "${a}"`,data:{id:s.id,count:i}})},"memory.recall":async function*(r,n){let o=n.query?.trim();if(!o){yield ie(r,"memory.recall","MEMORY_RECALL_FAILED","memory.recall requires a query");return}let s=await t.recall(o),i=Array.isArray(s.memories)?s.memories:[];if(i.length===0){yield F(r,"memory.recall",{success:!0,message:"No memories found matching your query.",count:0,memories:[]});return}yield F(r,"memory.recall",{success:!0,message:`Found ${i.length} memories:`,count:i.length,memories:i})},"memory.list":async function*(r,n){let o=n,s=await t.list({...typeof o.limit=="number"?{limit:o.limit}:{},...typeof o.offset=="number"?{offset:o.offset}:{}}),i=typeof o.query=="string"&&o.query.trim().length>0?s.filter(a=>a.content.toLowerCase().includes(o.query.trim().toLowerCase())):s;yield F(r,"memory.list",{memories:i,count:i.length})},"memory.forget":async function*(r,n){let o=n.id?.trim();if(!o){yield ie(r,"memory.forget","MEMORY_FORGET_FAILED","memory.forget requires an id");return}let s=await t.deleteMemory(o);yield F(r,"memory.forget",{success:!0,message:s?`Deleted memory ${o}.`:`Memory ${o} not found or already deleted.`,deleted:s})},"memory.recall_knowledge":async function*(r,n){let o=n,s=o.topic?.trim();if(!s){yield ie(r,"memory.recall_knowledge","MEMORY_RECALL_KNOWLEDGE_FAILED","memory.recall_knowledge requires a topic");return}let i=await t.recallTools({query:s,...typeof o.limit=="number"?{limit:o.limit}:{}});yield F(r,"memory.recall_knowledge",{tools:i,count:i.length})}}:{"memory.remember":pe("memoria","memory.remember"),"memory.recall":pe("memoria","memory.recall"),"memory.list":pe("memoria","memory.list"),"memory.forget":pe("memoria","memory.forget"),"memory.recall_knowledge":pe("memoria","memory.recall_knowledge")}}var kg=G(()=>{"use strict";Er()});import{randomUUID as lE}from"node:crypto";import{OutboundMessageSchema as sL}from"@aria-cli/tools";function iL(e){let t=e.trim();if(!t)return null;let r=t.indexOf(" ");if(r<=0)return null;let n=t.slice(0,r).trim(),o=t.slice(r+1).trim();return!n||!o?null:{recipient:n,content:o}}function rc(e){return e.displayNameSnapshot?.trim()||e.nodeId}function Mg(e){return e.displayLabel.trim()||e.clientId}function cE(e){let t=Mg(e);return t===e.clientId?e.clientId:`${t} (${e.clientId})`}function dE(e){let t=e.trim().replace(/^@/,""),r=t.indexOf("#");if(r>0)return{peer:t.slice(0,r),client:t.slice(r+1)||void 0};let n=t.indexOf("/");return n>0?{peer:t.slice(0,n),arion:t.slice(n+1)||void 0}:{peer:t}}function aL(e,t){let{peer:r}=dE(t),n=e.find(s=>s.nodeId.toLowerCase()===r);if(n)return n;let o=e.filter(s=>rc(s).toLowerCase()===r);return o.length===1?o[0]:null}function cL(e,t){let r=t.trim().toLowerCase().replace(/^@/,"");return e.filter(n=>rc(n).toLowerCase()===r).length>1}function lL(e,t){let r=t.trim().toLowerCase().replace(/^@/,"");return e.find(n=>n.clientId.toLowerCase()===r)??null}function dL(e,t){let r=t.trim().toLowerCase();return e.find(n=>Mg(n).toLowerCase()===r)??null}function uL(e){let t={};e.targetArion&&(t.targetArion=e.targetArion),e.targetClient&&(t.targetClient=e.targetClient);let r=Object.keys(t).length>0;return{rawMessage:{version:1,id:`headless-send-${lE()}`,sender:{id:e.senderNodeId,name:e.senderName,type:"arion"},recipient:{id:e.recipient.nodeId,name:rc(e.recipient),type:"peer"},type:"message",content:e.content,timestamp:Date.now(),priority:2,...r?{metadata:t}:{}},to:e.recipient.nodeId,type:"message",content:e.content,priority:2,...r?{metadata:t}:{}}}function mL(e){return{rawMessage:{version:1,id:`headless-send-${lE()}`,sender:{id:e.senderNodeId,name:e.senderName,type:"arion"},recipient:{id:e.recipient.clientId,name:Mg(e.recipient),type:"client"},type:"message",content:e.content,timestamp:Date.now(),priority:2},recipientInbox:{kind:"client",clientId:e.recipient.clientId},type:"message",content:e.content,priority:2}}async function fL(e,t){let r=typeof t.args=="string"&&t.args.trim().length>0?iL(t.args):t.recipient&&t.content?{recipient:t.recipient,content:t.content}:null;if(!r)return{ok:!1,code:"MESSAGE_SEND_FAILED",message:"Usage: /send <peer-name|node-id|client-id> <message>"};let[n,o,s]=await Promise.all([e.localControl.listPeers(),e.localControl.listAttachedClients(),e.localControl.getRuntimeStatus()]),i=t.senderName?.trim()||"ARIA",a=lL(o,r.recipient);if(a)return a.self?{ok:!1,code:"MESSAGE_SEND_FAILED",message:"Cannot send a same-home message to yourself."}:{ok:!0,outbound:mL({senderNodeId:s.nodeId,senderName:i,recipient:a,content:r.content}),message:`Sent message to ${cE(a)}.`};if(cL(n,r.recipient))return{ok:!1,code:"MESSAGE_SEND_FAILED",message:`Multiple peers match "${r.recipient}". Use the nodeId instead.`};let c=aL(n,r.recipient);if(!c){let f=dL(o,r.recipient);return f?{ok:!1,code:"MESSAGE_SEND_FAILED",message:`Same-home clients require the exact clientId. Use /clients to choose ${cE(f)}.`}:{ok:!1,code:"MESSAGE_SEND_FAILED",message:`Recipient "${r.recipient}" not found.`}}let l=dE(r.recipient),d=l.arion?`${rc(c)}/${l.arion}`:l.client?`${rc(c)}#${l.client}`:rc(c);return{ok:!0,outbound:uL({senderNodeId:s.nodeId,senderName:i,recipient:c,content:r.content,targetArion:l.arion,targetClient:l.client}),message:`Sent message to ${d}.`}}function pL(e,t){return e.deliveryState==="queued_for_route"?t.replace(/^Sent/,"Queued"):e.deliveryState==="dispatching"?`${t.slice(0,-1)}; awaiting acknowledgement.`:e.delivered?t.replace(/^Sent/,"Delivered"):t}function Dg(e){return{"message.send":async function*(t,r){let n=sL.safeParse(r);if(n.success){yield F(t,"message.send",{receipt:await e.localControl.sendDurable(n.data)});return}if(!(r&&typeof r=="object"&&(typeof r.args=="string"||typeof r.recipient=="string"||typeof r.content=="string"))){yield ie(t,"message.send","INVALID_INPUT","Invalid input for message.send");return}let s=await fL(e,r);if(!s.ok){yield ie(t,"message.send",s.code,s.message);return}let i=await e.localControl.sendDurable(s.outbound);yield F(t,"message.send",{receipt:i,message:pL(i,s.message)})},"message.inbox.list":async function*(t,r){yield F(t,"message.inbox.list",{events:await e.localControl.listInbox(r)})}}}var Lg=G(()=>{"use strict";Er()});function Ng(e){let t=e.modelDiscovery;return!t?.listAvailable||!t.refresh||!t.setCurrentModel?{"model.list":pe("modelDiscovery","model.list"),"model.set":pe("modelDiscovery","model.set"),"model.refresh":pe("modelDiscovery","model.refresh")}:{"model.list":async function*(r){let n=t.listAvailable;yield F(r,"model.list",{models:await n(),currentModel:await t.getCurrentModel?.()})},"model.set":async function*(r,n){let o=t.setCurrentModel,s=n.model?.trim();if(!s){yield ie(r,"model.set","MODEL_SET_FAILED","model.set requires a model");return}let i=await o(s);yield F(r,"model.set",{currentModel:s,...i&&typeof i=="object"?i:{}})},"model.refresh":async function*(r){let n=t.refresh;yield F(r,"model.refresh",{models:await n(!0)})}}}var Og=G(()=>{"use strict";Er()});function jg(e){return{"peer.list":async function*(t){yield F(t,"peer.list",{peers:await e.localControl.listPeers()})},"peer.list_nearby":async function*(t){yield F(t,"peer.list_nearby",{peers:await e.localControl.listNearbyPeers()})},"peer.pending.list":async function*(t){yield F(t,"peer.pending.list",{requests:await e.localControl.listPendingPairRequests()})},"peer.pending.respond":async function*(t,r){yield F(t,"peer.pending.respond",{response:await e.localControl.respondToPairRequest(r)})},"peer.invite":async function*(t,r){yield F(t,"peer.invite",{invite:await e.localControl.createInvite(r)})},"peer.connect":async function*(t,r){yield F(t,"peer.connect",{invite:await e.localControl.invitePeer(r)})},"peer.accept_invite":async function*(t,r){yield F(t,"peer.accept_invite",{accepted:await e.localControl.acceptInviteToken(r)})},"peer.direct_pair":async function*(t,r){yield F(t,"peer.direct_pair",{pair:await e.localControl.directPair(r)})},"peer.repair":async function*(t,r){yield F(t,"peer.repair",{repair:await e.localControl.repairPeer(r)})},"peer.revoke":async function*(t,r){yield F(t,"peer.revoke",{revoke:await e.localControl.revokePeer(r)})}}}var Pg=G(()=>{"use strict";Er()});function $g(e){return{"run.start":async function*(t,r,n){yield*e.start(t,r,n?.signal)},"run.resume":async function*(t,r,n){yield*e.resume(t,r,n?.signal)},"run.abort":async function*(t,r,n){yield*e.abort(t,r,n?.activeRunController)},"interaction.respond":async function*(t,r,n){let o=r&&typeof r=="object"&&"kind"in r?r:{kind:"interaction.respond",requestId:t,...r};yield*e.respond(o,n?.signal)}}}var uE=G(()=>{"use strict"});var pE={};Ln(pE,{buildSessionForkResult:()=>fE,buildSessionListResult:()=>Fg,buildSessionLoadResult:()=>Bg,buildSessionReadResult:()=>Ug,createSessionOperationHandlers:()=>Nm});function hL(e){return{...e,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString(),...e.completedAt?{completedAt:e.completedAt.toISOString()}:{}}}function mE(e){let t=e.sessionId;return typeof t=="string"?t.trim():""}function Fg(e,t,r){let n=r,o=typeof n.query=="string"&&n.query.trim().length>0?t.searchSessionSummaries(n.query,n.limit??20,n.offset??0):t.listSessions(n.limit??20,n.offset??0);return F(e,"session.list",{sessions:o.map(hL)})}function Ug(e,t,r){let n=mE(r);if(!n)return ie(e,"session.read","SESSION_READ_FAILED","session.read requires a sessionId");let o=t.findSessionByPrefix(n)??n,s=t.loadSessionMessages(o);return s?F(e,"session.read",{session:s}):ie(e,"session.read","SESSION_NOT_FOUND",`Session ${n} not found`)}function Bg(e,t,r){let n=mE(r);if(!n)return ie(e,"session.load","SESSION_LOAD_FAILED","session.load requires a sessionId");let o=t.findSessionByPrefix(n)??n,s=t.loadSession(o);return s?F(e,"session.load",{session:s.session,loaded:!0,...s.runtimeState?{runtimeState:s.runtimeState}:{},...s.pendingInteraction?{pendingInteraction:s.pendingInteraction}:{}}):ie(e,"session.load","SESSION_NOT_FOUND",`Session ${n} not found`)}function fE(e,t,r){let n=r,o=typeof n.sessionId=="string"?n.sessionId.trim():"";if(!o)return ie(e,"session.fork","SESSION_FORK_FAILED","session.fork requires a sessionId");let s=t.findSessionByPrefix(o)??o;try{let i=t.forkSession(s,{messageLimit:n.messageLimit});return F(e,"session.fork",{newSessionId:i.newSessionId,sourceSessionId:i.sourceSessionId,messagesCopied:i.messagesCopied,title:i.title})}catch(i){return ie(e,"session.fork","SESSION_NOT_FOUND",i.message)}}function Nm(e){return{"session.list":async function*(t,r){yield Fg(t,e.sessionLedger,r)},"session.read":async function*(t,r){yield Ug(t,e.sessionLedger,r)},"session.load":async function*(t,r){yield Bg(t,e.sessionLedger,r)},"session.fork":async function*(t,r){yield fE(t,e.sessionLedger,r)}}}var jl=G(()=>{"use strict";Er()});var hE=G(()=>{"use strict";yg();Sg();Rg();Ig();kg();Lg();Og();Pg();uE();jl()});function gE(e){let t=e.hook;return!t?.extract||!t.reflect||!t.consolidate||!t.ingest||!t.harvest?{"hook.extract":pe("hook","hook.extract"),"hook.reflect":pe("hook","hook.reflect"),"hook.consolidate":pe("hook","hook.consolidate"),"hook.ingest":pe("hook","hook.ingest"),"hook.harvest":pe("hook","hook.harvest")}:{"hook.extract":async function*(r,n,o){try{yield F(r,"hook.extract",await t.extract(n,{signal:o?.signal}))}catch(s){yield ie(r,"hook.extract","HOOK_EXTRACT_FAILED",s instanceof Error?s.message:String(s))}},"hook.reflect":async function*(r,n,o){try{yield F(r,"hook.reflect",await t.reflect(n,{signal:o?.signal}))}catch(s){yield ie(r,"hook.reflect","HOOK_REFLECT_FAILED",s instanceof Error?s.message:String(s))}},"hook.consolidate":async function*(r,n,o){try{yield F(r,"hook.consolidate",await t.consolidate(n,{signal:o?.signal}))}catch(s){yield ie(r,"hook.consolidate","HOOK_CONSOLIDATE_FAILED",s instanceof Error?s.message:String(s))}},"hook.ingest":async function*(r,n,o){try{yield F(r,"hook.ingest",await t.ingest(n,{signal:o?.signal}))}catch(s){yield ie(r,"hook.ingest","HOOK_INGEST_FAILED",s instanceof Error?s.message:String(s))}},"hook.harvest":async function*(r,n,o){try{yield F(r,"hook.harvest",await t.harvest(n,{signal:o?.signal}))}catch(s){yield ie(r,"hook.harvest","HOOK_HARVEST_FAILED",s instanceof Error?s.message:String(s))}}}}var wE=G(()=>{"use strict";Er()});function yE(e){let t=e.system;return!t?.restart||!t.terminalSetup?{"system.restart":pe("system","system.restart"),"system.terminal_setup":pe("system","system.terminal_setup")}:{"system.restart":async function*(r,n){yield F(r,"system.restart",await t.restart(n))},"system.terminal_setup":async function*(r){yield F(r,"system.terminal_setup",await t.terminalSetup())}}}var xE=G(()=>{"use strict";Er()});var TE={};Ln(TE,{createDaemonService:()=>Pl});import{spawn as gL}from"node:child_process";import{existsSync as SE,mkdirSync as wL,openSync as yL,closeSync as xL}from"node:fs";import bE from"node:path";import{fileURLToPath as Hg}from"node:url";function TL(e){return new Promise(t=>setTimeout(t,Math.max(e,0)))}function EL(){let e=Hg(new URL("../../../server/dist/daemon-launcher.js",import.meta.url));if(SE(e))return{command:process.execPath,args:[e]};try{let r=Hg(import.meta.resolve("@aria-cli/server/daemon-launcher"));if(SE(r))return{command:process.execPath,args:[r]}}catch{}let t=Hg(new URL("../../../server/src/daemon-launcher.ts",import.meta.url));return{command:process.execPath,args:["--import","tsx",t]}}function _L(e,t,r){return(typeof r.arion=="string"?r.arion.trim():"")||t||e.config.activeArion?.trim()||"ARIA"}function CL(e){return{...typeof e.intervalMs=="number"?{intervalMs:e.intervalMs}:{},...e.allowedToolCategories||e.allowedShellCommands||typeof e.maxWriteOpsPerMinute=="number"||typeof e.maxGitPushesPerHour=="number"?{safetyPolicy:{...Array.isArray(e.allowedToolCategories)?{allowedToolCategories:e.allowedToolCategories}:{},...Array.isArray(e.allowedShellCommands)?{allowedShellCommands:e.allowedShellCommands}:{},...typeof e.maxWriteOpsPerMinute=="number"?{maxWriteOpsPerMinute:e.maxWriteOpsPerMinute}:{},...typeof e.maxGitPushesPerHour=="number"?{maxGitPushesPerHour:e.maxGitPushesPerHour}:{}}}:{}}}async function RL(e){let t=Date.now()+SL,r=null;for(;Date.now()<t;){try{let n=await Ll({ariaHome:e.ariaHome});if(n){let o=await n.getRuntimeStatus();if(!e.requireRunning||o.autonomousLoop.status==="running")return o}}catch(n){r=n instanceof Error?n:new Error(String(n))}await TL(bL)}throw new Error(r?.message??"Timed out waiting for the daemon runtime to become reachable")}function AL(e){let t=EL(),r=[...t.args,"--arion",e.arionName];typeof e.input.port=="number"&&r.push("--port",String(e.input.port)),typeof e.input.intervalMs=="number"&&r.push("--interval-ms",String(e.input.intervalMs)),Array.isArray(e.input.allowedToolCategories)&&e.input.allowedToolCategories.length>0&&r.push("--allowed-tool-categories",e.input.allowedToolCategories.join(",")),Array.isArray(e.input.allowedShellCommands)&&e.input.allowedShellCommands.length>0&&r.push("--allowed-shell-commands",e.input.allowedShellCommands.join(",")),typeof e.input.maxWriteOpsPerMinute=="number"&&r.push("--max-write-ops-per-minute",String(e.input.maxWriteOpsPerMinute)),typeof e.input.maxGitPushesPerHour=="number"&&r.push("--max-git-pushes-per-hour",String(e.input.maxGitPushesPerHour));let n=bE.join(e.ariaHome,"logs");wL(n,{recursive:!0});let o=yL(bE.join(n,"daemon-stderr.log"),"a");gL(t.command,r,{cwd:e.cwd,env:{...process.env,ARIA_HOME:e.ariaHome},detached:!0,stdio:["ignore","ignore",o]}).unref(),xL(o)}function Pl(e){let t=e.cli.ariaDir,r=!1,n=()=>e.getArionName?.()??e.arionName??"ARIA",o=i=>{let a=typeof i.arion=="string"?i.arion.trim():"",c=n();if(a&&a!==c)throw new Error(`daemon operations are scoped to ${c}; switch scope with arion.become before targeting ${a}`);return a||c},s=async()=>{if(!e.localControl)return null;try{return await e.localControl.getRuntimeStatus(),e.localControl}catch{return null}};return{async start(i){let a=_L(e.cli,o(i),i),c=await s();if(!c)return r=!0,AL({ariaHome:t,cwd:e.cwd,arionName:a,input:i}),RL({ariaHome:t,requireRunning:!0});let l=await c.getRuntimeStatus();if(l.autonomousLoop.status==="running")return r=!1,l;if(!c.startAutonomousLoop)throw new Error("Live runtime does not expose autonomous-loop start control");return r=!0,c.startAutonomousLoop(CL(i))},async status(i={}){o(i);let a=await s();if(!a)throw new Error("No live runtime is available for daemon.status");return a.getRuntimeStatus()},async stop(i={}){o(i);let a=await s();if(!a)throw new Error("No live runtime is available for daemon.stop");if(!a.stopAutonomousLoop)throw new Error("Live runtime does not expose autonomous-loop stop control");return r=!1,a.stopAutonomousLoop()},shouldStopOnShutdown(){return r},async releaseAll(){}}}var SL,bL,Om=G(()=>{"use strict";Am();SL=15e3,bL=250});import{lightReflection as IL}from"@aria-cli/aria";import{ingestClaudeCodeHistory as vL}from"@aria-cli/memoria-bridge";function Me(e){if(!e?.aborted)return;let t=e.reason instanceof Error&&e.reason.message?e.reason.message:"The operation was aborted",r=new Error(t);throw r.name="AbortError",r}function ML(e={}){let t={preHarvest:e.preHarvest===!0,feedback:e.feedback===!0,extract:e.extract===!0,stats:e.stats===!0,cleanup:e.cleanup===!0,cost:e.cost===!0,all:e.all===!0,limit:typeof e.limit=="number"&&Number.isInteger(e.limit)&&e.limit>0?e.limit:50};return t.all&&(t.preHarvest=!0,t.extract=!0,t.stats=!0),t}async function _E(e,t,r={}){if(Me(r.signal),!t)return{output:{error:"no input on stdin"},exitCode:1};let n;try{if(n=JSON.parse(t),!Array.isArray(n))throw new Error("expected array")}catch{return{output:{error:"stdin must be JSON array of {user, assistant} pairs"},exitCode:1}}if(n.length>EE)return{output:{error:`hook.extract accepts at most ${EE} pairs per request`},exitCode:1};let o=[],s=0,i=Array.from({length:Math.min(kL,n.length)},async()=>{for(;;){Me(r.signal);let a=s;if(s+=1,a>=n.length)return;let c=n[a];if(!c.user||!c.assistant){o[a]={user:c.user??"",extracted:0,error:"missing user or assistant"};continue}try{let l=await e.extractFromConversation(c.user,c.assistant);Me(r.signal);let d=l?.learned;o[a]={user:c.user.slice(0,80),extracted:Array.isArray(d)?d.length:0}}catch(l){Me(r.signal),o[a]={user:c.user.slice(0,80),extracted:0,error:l instanceof Error?l.message:String(l)}}}});return await Promise.all(i),{output:{extracted:o}}}async function Wg(e,t,r,n={}){Me(n.signal);let o=[];if(r)try{let s=JSON.parse(r);if(Array.isArray(s))for(let i of s)i.role&&i.content&&o.push({role:i.role,content:typeof i.content=="string"?i.content:JSON.stringify(i.content)})}catch{o.push({role:"user",content:"Session review"}),o.push({role:"assistant",content:r})}if(o.length<2)return{output:{findings:null,reason:"insufficient conversation"}};try{let s=await IL(t,e,o);return Me(n.signal),{output:{findings:s}}}catch(s){return Me(n.signal),{output:{findings:null,error:s instanceof Error?s.message:String(s)}}}}async function CE(e,t={}){Me(t.signal);try{let r=await e.reflect({full:!1});return Me(t.signal),{output:r}}catch(r){return Me(t.signal),{output:{error:r instanceof Error?r.message:String(r)}}}}async function RE(e,t={}){Me(t.signal);try{let r=await vL(e);return Me(t.signal),{output:r}}catch(r){return Me(t.signal),{output:{error:r instanceof Error?r.message:String(r)}}}}async function AE(e,t,r={},n={}){Me(n.signal);let o=ML(r);if(!o.preHarvest&&!o.feedback&&!o.extract&&!o.stats&&!o.cleanup&&!o.cost)return{output:{help:"Use hook.harvest via `aria call` or the persistent headless server.",actions:["--pre-harvest: session quality scoring + tool intelligence (DuckDB, no LLM)","--extract: session extraction WITH LLM","--stats: health dashboard (includes learning velocity + dupe rate)","--cost: cost intelligence by model/project/day","--cleanup: garbage removal","--all: pre-harvest + extract + stats","--feedback: (deprecated, no-op)"]}};let s={};if(o.preHarvest){process.stderr.write(`[harvest] Running pre-harvest DuckDB analytics...
|
|
340
|
-
`);try{let{createAnalytics:i,scoreSessionQuality:a,mineToolFrequencies:c,mineWorkflowPatterns:l,detectTemporalDrift:d,getCostIntelligence:f}=await import("@aria-cli/memoria-bridge/analytics"),u=null;Me(n.signal);try{u=await i();let h=u.expandPath("~/.claude/projects/**/*.jsonl");Me(n.signal);let y=await a(u,h);Me(n.signal);let S=await c(u,h);Me(n.signal);let R=await l(u,h);Me(n.signal);let I=await d(u,h);Me(n.signal);let v=await f(u,h);Me(n.signal),s.preHarvest={score:y,toolFreq:S,workflows:R,drift:I,cost:v}}catch(h){Me(n.signal),s.preHarvest={error:h instanceof Error?h.message:String(h)}}finally{await u?.close().catch(()=>{})}}catch(i){Me(n.signal),s.preHarvest={error:i instanceof Error?i.message:String(i)}}}if(o.cost&&!o.preHarvest){process.stderr.write(`[harvest] Running standalone cost analytics...
|
|
341
|
-
`);try{let{createAnalytics:i,getCostIntelligence:a}=await import("@aria-cli/memoria-bridge/analytics"),c=null;try{Me(n.signal),c=await i();let l=c.expandPath("~/.claude/projects/**/*.jsonl");Me(n.signal),s.cost=await a(c,l),Me(n.signal)}finally{await c?.close().catch(()=>{})}}catch(i){Me(n.signal),s.cost={error:i instanceof Error?i.message:String(i)}}}if(o.extract&&(process.stderr.write(`[harvest] Running extraction...
|
|
342
|
-
`),Me(n.signal),s.extract=DL(await Wg(e,t,"",n))),o.stats)try{Me(n.signal),s.stats=await e.reflect({full:!1}),Me(n.signal)}catch(i){Me(n.signal),s.stats={error:i instanceof Error?i.message:String(i)}}return o.cleanup&&(s.cleanup={skipped:!0,message:"cleanup remains a no-op in headless cutover"}),o.cost&&o.preHarvest&&(s.cost=s.preHarvest?.cost??null),o.feedback&&(process.stderr.write(`[harvest] --feedback is deprecated and has no effect. Use --pre-harvest instead.
|
|
343
|
-
`),s.feedback={deprecated:!0}),{output:s}}function DL(e){return e.output}var EE,kL,IE=G(()=>{"use strict";EE=50,kL=5});import LL from"node:path";function NL(e){return LL.join("arions",e,"memory.db")}function $l(e){return e.output&&typeof e.output=="object"?e.output:{value:e.output}}function vE(e){let t=()=>process.env.ARIA_MEMORY_PATH||NL(e.getArionName?.()??e.arionName),r=async n=>{let o=await e.cli.pool.get(e.resolveMemoriaPath?await e.resolveMemoriaPath():t());return n(o)};return{async extract(n,o){return r(async s=>$l(await _E(s,JSON.stringify(n.pairs??[]),{signal:o?.signal})))},async reflect(n,o){let s=typeof n.conversation=="string"?n.conversation:JSON.stringify(n.messages??[]);return r(async i=>$l(await Wg(i,e.cli.router,s,o)))},async consolidate(n,o){return r(async s=>$l(await CE(s,o)))},async ingest(n,o){return r(async s=>$l(await RE(s,o)))},async harvest(n,o){return r(async s=>$l(await AE(s,e.cli.router,n,o)))}}}var kE=G(()=>{"use strict";IE()});import{randomUUID as ME}from"node:crypto";import{buildAuthorizeUrl as OL,completeGitHubCopilotDeviceFlow as jL,exchangeCodeForTokens as PL,generatePkce as $L,generateState as FL,getOAuthConfig as UL,requestGitHubCopilotDeviceCode as BL,upsertAuthProfile as HL}from"@aria-cli/auth";function Je(e,t,r,n,o){return{kind:"result",requestId:e,op:t,ok:!1,error:{code:r,message:n,...o?{details:o}:{}}}}function nc(e,t,r){return{kind:"result",requestId:e,op:t,ok:!0,result:r}}function DE(e){return e.map(t=>({id:t.id,label:t.label,...t.email||t.status?{description:[t.status,t.email].filter(Boolean).join(" \xB7 ")}:{}}))}function LE(e){return e.map(t=>({id:t.id,label:t.label,...t.description||t.status?{description:[t.description,t.status].filter(Boolean).join(" \xB7 ")}:{}}))}function qg(e){return{interactionId:e.interactionId,source:e.source,interaction:e.interaction}}function WL(e,t){return{...e,__authPending:t}}function qL(e){let t=e.__authPending;return!t||typeof t!="object"?null:t}var jm,NE=G(()=>{"use strict";jm=class{auth;sessionLedger;getActiveArionName;constructor(t,r,n){this.auth=t,this.sessionLedger=r,this.getActiveArionName=n}async*login(t,r,n){if(!this.auth?.login||!this.auth.status){yield Je(t,"auth.login","MISSING_SERVICE","Kernel service auth is not configured for auth.login.");return}let o=await this.auth.login(r);yield*this.framesForInitialLoginResult(t,"auth.login",o,n)}async*logout(t,r){if(!this.auth?.logout){yield Je(t,"auth.logout","MISSING_SERVICE","Kernel service auth is not configured for auth.logout.");return}let n=await this.auth.logout(r);if(n.mode==="direct"){if(n.result.success){yield nc(t,"auth.logout",n.result);return}yield Je(t,"auth.logout","AUTH_LOGOUT_FAILED",n.result.message);return}let o=await this.persistNewInteraction(t,{pending:{type:"logout-provider"},interaction:{kind:"selection",prompt:"Choose a provider to disconnect.",options:DE(n.providers)}});yield o,yield Je(t,"auth.logout","INTERACTION_REQUIRED","auth.logout requires additional interaction before it can continue.",qg(o))}async*respond(t,r){let n=this.sessionLedger.getInteraction(t.interactionId);if(!n||n.source!=="auth"){yield Je(t.requestId,"interaction.respond","INTERACTION_NOT_FOUND",`Unknown interaction ${t.interactionId}`);return}let o=qL(n.prompt);if(!o){yield Je(t.requestId,"interaction.respond","INVALID_INTERACTION_STATE",`Interaction ${t.interactionId} is missing auth resume state.`);return}let s=`auth:${t.requestId}`,i=this.sessionLedger.claimSessionForMutation(n.sessionId,s,3e4),a=!1,c=()=>{a||(a=!0,this.sessionLedger.releaseSessionClaim(n.sessionId,s))};try{if(t.response.kind==="cancel"){this.sessionLedger.cancelInteraction(n.sessionId,n.interactionId,{ownerId:s,expectedRevision:i.revision}),c(),yield Je(t.requestId,"interaction.respond","INTERACTION_CANCELED","Interaction canceled.");return}switch(o.type){case"login-provider":{if(t.response.kind!=="selection"){c(),yield Je(t.requestId,"interaction.respond","INVALID_INTERACTION_RESPONSE","Provider selection requires a selection response.");return}let l=await this.auth?.login?.({args:t.response.selected});this.sessionLedger.recordInteractionResponse(n.sessionId,n.interactionId,t.response,{ownerId:s,expectedRevision:i.revision}),yield*this.framesForContinuedLoginResult(t.requestId,l,n.sessionId,s,i.revision+1,r);return}case"logout-provider":{if(t.response.kind!=="selection"){c(),yield Je(t.requestId,"interaction.respond","INVALID_INTERACTION_RESPONSE","Provider selection requires a selection response.");return}let l=await this.auth?.logout?.({args:t.response.selected});if(this.sessionLedger.recordInteractionResponse(n.sessionId,n.interactionId,t.response,{ownerId:s,expectedRevision:i.revision}),this.sessionLedger.completeRun(n.sessionId,{success:l.mode==="direct"?l.result.success:!1,message:l.mode==="direct"?l.result.message:"auth.logout requires additional interaction."},{ownerId:s,expectedRevision:i.revision+1}),c(),l.mode==="direct"&&l.result.success){yield nc(t.requestId,"interaction.respond",l.result);return}yield Je(t.requestId,"interaction.respond","AUTH_LOGOUT_FAILED",l.mode==="direct"?l.result.message:"auth.logout requires interaction.");return}case"login-method":{if(t.response.kind!=="selection"){c(),yield Je(t.requestId,"interaction.respond","INVALID_INTERACTION_RESPONSE","Method selection requires a selection response.");return}let l=await this.auth?.login?.({args:`${o.provider} --method ${t.response.selected}`});this.sessionLedger.recordInteractionResponse(n.sessionId,n.interactionId,t.response,{ownerId:s,expectedRevision:i.revision}),yield*this.framesForContinuedLoginResult(t.requestId,l,n.sessionId,s,i.revision+1,r);return}case"copilot-source":{if(t.response.kind!=="selection"){c(),yield Je(t.requestId,"interaction.respond","INVALID_INTERACTION_RESPONSE","GitHub Copilot source selection requires a selection response.");return}let l=await this.auth?.login?.({args:`github-copilot --from ${t.response.selected}`});this.sessionLedger.recordInteractionResponse(n.sessionId,n.interactionId,t.response,{ownerId:s,expectedRevision:i.revision}),yield*this.framesForContinuedLoginResult(t.requestId,l,n.sessionId,s,i.revision+1,r);return}case"credential-input":{if(t.response.kind!=="credential_input"){c(),yield Je(t.requestId,"interaction.respond","INVALID_INTERACTION_RESPONSE","Credential input requires a credential_input response.");return}let l=t.response.values[o.fieldKey];if(typeof l!="string"||l.trim().length===0){c(),yield Je(t.requestId,"interaction.respond","INVALID_INTERACTION_RESPONSE",`Missing credential field ${o.fieldKey}.`);return}let d=await this.auth?.login?.({args:`${o.commandPrefix} ${l.trim()}`.trim()});this.sessionLedger.recordInteractionResponse(n.sessionId,n.interactionId,t.response,{ownerId:s,expectedRevision:i.revision}),yield*this.framesForContinuedLoginResult(t.requestId,d,n.sessionId,s,i.revision+1,r);return}case"oauth-code":{if(t.response.kind!=="credential_input"){c(),yield Je(t.requestId,"interaction.respond","INVALID_INTERACTION_RESPONSE","OAuth code entry requires a credential_input response.");return}let l=t.response.values[o.fieldKey];if(typeof l!="string"||l.trim().length===0){c(),yield Je(t.requestId,"interaction.respond","INVALID_INTERACTION_RESPONSE",`Missing credential field ${o.fieldKey}.`);return}this.sessionLedger.recordInteractionResponse(n.sessionId,n.interactionId,t.response,{ownerId:s,expectedRevision:i.revision});let d=await PL(o.provider,l.trim(),o.codeVerifier);HL({profileId:`${o.provider}:oauth`,credential:{type:"oauth",provider:o.provider,access:d.access,refresh:d.refresh,expires:d.expires}}),this.sessionLedger.completeRun(n.sessionId,{success:!0,message:`Logged in to ${o.provider} successfully`},{ownerId:s,expectedRevision:i.revision+1}),c(),yield nc(t.requestId,"interaction.respond",{success:!0,message:`Logged in to ${o.provider} successfully`});return}case"copilot-device":{if(t.response.kind!=="oauth_device"){c(),yield Je(t.requestId,"interaction.respond","INVALID_INTERACTION_RESPONSE","GitHub Copilot device flow requires an oauth_device response.");return}this.sessionLedger.recordInteractionResponse(n.sessionId,n.interactionId,t.response,{ownerId:s,expectedRevision:i.revision});let l=await jL({deviceCode:o.deviceCode,profileLabel:o.profileLabel,signal:r?.signal});if(this.sessionLedger.completeRun(n.sessionId,l,{ownerId:s,expectedRevision:i.revision+1}),c(),l.success){yield nc(t.requestId,"interaction.respond",l);return}yield Je(t.requestId,"interaction.respond","AUTH_LOGIN_FAILED",l.message);return}}}catch(l){c(),yield Je(t.requestId,"interaction.respond","AUTH_INTERACTION_FAILED",l instanceof Error?l.message:String(l))}}async*framesForInitialLoginResult(t,r,n,o){if(n.mode==="direct"){if(n.result.success){yield nc(t,r,n.result);return}yield Je(t,r,"AUTH_LOGIN_FAILED",n.result.message);return}let s=await this.buildLoginInteractionSpec(n,o),i=await this.persistNewInteraction(t,s);yield i,yield Je(t,r,"INTERACTION_REQUIRED","auth.login requires additional interaction before it can continue.",qg(i))}async*framesForContinuedLoginResult(t,r,n,o,s,i){if(r.mode==="direct"){if(this.sessionLedger.completeRun(n,r.result,{ownerId:o,expectedRevision:s}),this.sessionLedger.releaseSessionClaim(n,o),r.result.success){yield nc(t,"interaction.respond",r.result);return}yield Je(t,"interaction.respond","AUTH_LOGIN_FAILED",r.result.message);return}let a=await this.buildLoginInteractionSpec(r,i),c=this.persistContinuedInteraction(t,a,n,o,s);yield c,yield Je(t,"interaction.respond","INTERACTION_REQUIRED","auth.login requires additional interaction before it can continue.",qg(c))}async buildLoginInteractionSpec(t,r){switch(t.mode){case"picker":return{pending:{type:"login-provider"},interaction:{kind:"selection",prompt:"Choose a provider to sign in with.",options:DE(t.providers)}};case"anthropic_method_picker":case"openai_method_picker":case"google_method_picker":return{pending:{type:"login-method",provider:t.provider},interaction:{kind:"selection",prompt:`Choose how to sign in to ${t.provider}.`,options:LE(t.options)}};case"copilot_source_picker":return{pending:{type:"copilot-source"},interaction:{kind:"selection",prompt:"Choose a GitHub Copilot credential source.",options:LE(t.options)}};case"anthropic_key_input":case"openai_key_input":case"google_key_input":return{pending:{type:"credential-input",commandPrefix:t.provider,fieldKey:"apiKey"},interaction:{kind:"credential_input",prompt:`Enter the API key for ${t.provider}.`,provider:t.provider,fields:[this.secretField("apiKey",`${t.provider} API key`)]}};case"anthropic_setup_token":return{pending:{type:"credential-input",commandPrefix:"anthropic --setup-token",fieldKey:"setupToken"},interaction:{kind:"credential_input",prompt:"Enter the Anthropic setup token.",provider:"anthropic",fields:[this.secretField("setupToken","Anthropic setup token")]}};case"oauth":{let{codeVerifier:n,codeChallenge:o}=$L(),s=UL(t.provider),i=s.redirectUri.startsWith("http://127.0.0.1")?FL():n,a=OL(t.provider,o,i);return{pending:{type:"oauth-code",provider:t.provider,fieldKey:"authorizationCode",codeVerifier:n},interaction:{kind:"credential_input",prompt:`Sign in to ${t.provider} to continue.`,provider:t.provider,mode:"oauth_authorization_code",authorizeUrl:a,callbackMode:s.redirectUri.startsWith("http://127.0.0.1")?"local_callback":"manual_code",...s.redirectUri.startsWith("http://127.0.0.1")?{expectedState:i}:{},fields:[{key:"authorizationCode",label:"Authorization code"}]}}}case"copilot_device":{let n=await BL({signal:r?.signal});return{pending:{type:"copilot-device",profileLabel:t.profileLabel,deviceCode:n},interaction:{kind:"oauth_device",prompt:t.message??"Open the verification URL, enter the device code, then confirm to continue.",provider:"github-copilot",...t.profileLabel?{profileLabel:t.profileLabel}:{},verificationUri:n.verificationUri,userCode:n.userCode,expiresAt:new Date(n.expiresAt).toISOString(),intervalSeconds:Math.ceil(n.intervalMs/1e3)}}}}}async persistNewInteraction(t,r){let n=`auth:${ME()}`;this.sessionLedger.loadSession(n)||this.sessionLedger.createSession(await this.getActiveArionName(),"auth",n);let o=`auth:${t}`,s=this.sessionLedger.claimSessionForMutation(n,o,3e4);try{return this.persistInteractionRecord(t,n,o,s.revision,r.pending,r.interaction)}finally{this.sessionLedger.releaseSessionClaim(n,o)}}persistContinuedInteraction(t,r,n,o,s){let i=this.persistInteractionRecord(t,n,o,s,r.pending,r.interaction);return this.sessionLedger.releaseSessionClaim(n,o),i}persistInteractionRecord(t,r,n,o,s,i){let a=`auth:${ME()}`;return this.sessionLedger.recordPausedRun(r,`auth:${r}`,{kind:"auth"},{kind:"auth"},{interactionId:a,requestId:t,source:"auth",kind:i.kind,prompt:WL(i,s)},{ownerId:n,expectedRevision:o}),{kind:"interaction.required",requestId:t,interactionId:a,source:"auth",interaction:i}}secretField(t,r){return{key:t,label:r,secret:!0}}}});import{randomUUID as OE}from"node:crypto";import{isDeepStrictEqual as GL}from"node:util";import{resolveTrustedRuntimeErrorMessage as XL}from"@aria-cli/tools";function KL(){return{output:"",messages:[],toolCalls:[],usage:void 0,turnCount:0,thinking:[],nativeToolResults:[],pipelineTiming:void 0,guardrailEvents:[],handoffs:[],pausedState:null}}function VL(e){return{success:!e.pausedState,...e.output?{output:e.output}:{},...e.messages.length>0?{messages:e.messages}:{},...e.toolCalls.length>0?{toolCalls:e.toolCalls}:{},...e.usage!==void 0?{usage:e.usage}:{},...e.turnCount>0?{turnCount:e.turnCount}:{},...e.thinking.length>0?{thinking:e.thinking}:{},...e.nativeToolResults.length>0?{nativeToolResults:e.nativeToolResults}:{},...e.pipelineTiming!==void 0?{pipelineTiming:e.pipelineTiming}:{},...e.guardrailEvents.length>0?{guardrailEvents:e.guardrailEvents}:{},...e.handoffs.length>0?{handoffs:e.handoffs}:{},...e.pausedState?{state:e.pausedState}:{}}}function YL(e,t,r){return{code:e,message:t,...r?{details:r}:{}}}function or(e,t,r,n,o){return{kind:"result",requestId:e,op:t,ok:!1,error:YL(r,n,o)}}function Gg(e,t,r){return{kind:"result",requestId:e,op:t,ok:!0,result:r}}function PE(e){return{...e.arion?{arion:e.arion}:{},...e.cwd?{cwd:e.cwd}:{},...e.requestedModel?{requestedModel:e.requestedModel}:{},...e.preferredTier?{preferredTier:e.preferredTier}:{},...typeof e.budget=="number"?{budget:e.budget}:{},...typeof e.maxTurns=="number"?{maxTurns:e.maxTurns}:{},...e.autonomy?{autonomy:e.autonomy}:{},...e.allowedTools?{allowedTools:e.allowedTools}:{},...e.deniedTools?{deniedTools:e.deniedTools}:{},...typeof e.noMemory=="boolean"?{noMemory:e.noMemory}:{},...e.systemPrompt?{systemPrompt:e.systemPrompt}:{}}}function $E(e,t){return e.arion||!t?e:{...e,arion:t}}function JL(e){let{sessionId:t,...r}=e;return r}function QL(e){let{sessionId:t,...r}=e;return r}function FE(e,t){return e.requestedModel||!t?e:{...e,requestedModel:t}}function ds(e,t,r){!Array.isArray(r)||r.length===0||e.replaceConversationMessages(t,Xi(r))}function Xg(e,t,r){if((r.pendingUserQuestions?.length??0)>0){let n=`${t}:questionnaire:${OE()}`,o={kind:"questionnaire",questions:r.pendingUserQuestions??[]};return{record:{interactionId:n,requestId:e,source:"run",kind:o.kind,prompt:o},frame:{kind:"interaction.required",requestId:e,interactionId:n,source:"run",interaction:o}}}if((r.pendingToolCalls?.length??0)>0){let n=r.pendingToolCalls[0],o=`${t}:tool-approval:${OE()}`,s={kind:"tool_approval",toolName:n.name,toolInput:n.arguments,prompt:`Approval required for ${n.name}`};return{record:{interactionId:o,requestId:e,source:"run",kind:s.kind,prompt:s},frame:{kind:"interaction.required",requestId:e,interactionId:o,source:"run",interaction:s}}}return null}function ZL(e,t,r,n,o){let s={state:e,...o??{}};if(t.kind==="tool_approval"){if(r.response.kind!=="confirm")throw new Error(`Interaction ${t.interactionId} requires a confirm response`);return{...s,approvalMode:r.response.approved?"approve":"deny",...n>=0?{}:{}}}if(t.kind==="questionnaire"){if(r.response.kind!=="questionnaire")throw new Error(`Interaction ${t.interactionId} requires a questionnaire response`);return{...s,askUserAnswers:r.response.answers}}throw new Error(`Unsupported run interaction kind ${t.kind}`)}var jE,zL,Pm,UE=G(()=>{"use strict";_d();Cc();jE=3e4,zL=1e4;Pm=class e{ctx;constructor(t){this.ctx=t}renewSessionLease(t,r){let n=this.ctx.sessionLedger;return typeof n.renewSessionClaim=="function"?n.renewSessionClaim(t,r,jE):n.claimSessionForMutation(t,r,jE)}clearRunningSession(t,r,n){let o=this.ctx.sessionLedger;return typeof o.clearActiveRun=="function"?o.clearActiveRun(t,{ownerId:r,expectedRevision:n}):o.completeRun(t,{},{ownerId:r,expectedRevision:n})}releaseClaimOnce(t,r){let n=!1;return()=>{n||(n=!0,this.ctx.sessionLedger.releaseSessionClaim(t,r))}}static isAbortError(t){return t instanceof Error&&(t.name==="AbortError"||t.message==="The operation was aborted"||t.message==="This operation was aborted")}static createAbortReason(t,r){let n=new Error(r);return n.name="AbortError",n.code=t,n}static getAbortCode(t,r){let n=t?.aborted?t.reason:r;return n&&typeof n=="object"&&"code"in n&&typeof n.code=="string"?n.code:t?.aborted||e.isAbortError(r)?"RUN_ABORTED":null}static getAbortMessage(t,r){let n=t?.aborted?t.reason:r;return n instanceof Error&&n.message?n.message:"Run aborted before completion."}async*start(t,r,n){let o=r.sessionId?.trim()||t,s=`headless:${t}`,i=this.ctx.getSessionModel?.(),a=this.ctx.getSessionArion?.(),c=FE($E(r,a),i),l=c.arion??this.ctx.getSessionArion?.()??"ARIA",d=c.requestedModel??c.preferredTier??"balanced",f=PE(c);this.ctx.sessionLedger.loadSession(o)||this.ctx.sessionLedger.createSession(l,d,o);let u=this.ctx.sessionLedger.claimSessionForMutation(o,s,3e4),h=this.releaseClaimOnce(o,s),y=KL(),S=new AbortController,R=null,I=null,v=null;if(n){let C=()=>{S.abort(e.createAbortReason("CONNECTION_CLOSED","Connection closed before request completed"))};n.aborted?C():(n.addEventListener("abort",C,{once:!0}),R=()=>n.removeEventListener("abort",C))}I=setInterval(()=>{try{u=this.renewSessionLease(o,s)}catch(C){S.abort(e.createAbortReason("SESSION_LEASE_LOST",C instanceof Error?C.message:String(C)))}},zL);try{for await(let T of this.ctx.localControl.streamRun(JL(c),S.signal)){if(S.signal.aborted){h();return}this.consumeRunEvent(y,T),yield{kind:"event",requestId:t,seq:y.turnCount+y.toolCalls.length+y.thinking.length,op:"run.start",event:T}}if(S.signal.aborted){ds(this.ctx.sessionLedger,o,y.messages),this.clearRunningSession(o,s,u.revision),h();let T=e.getAbortCode(S.signal);T!=="CONNECTION_CLOSED"&&(yield or(t,"run.start",T??"RUN_ABORTED",e.getAbortMessage(S.signal),{sessionId:o,runId:`run:${o}`}));return}if(y.pausedState){ds(this.ctx.sessionLedger,o,y.pausedState.messages);let T=Xg(t,o,y.pausedState);this.ctx.sessionLedger.recordPausedRun(o,`run:${o}`,y.pausedState,f,T?.record,{ownerId:s,expectedRevision:u.revision}),h(),T&&(yield T.frame),yield or(t,"run.start","INTERACTION_REQUIRED","Run paused and requires interaction before it can continue.",{sessionId:o,...T?{interactionId:T.frame.interactionId,source:T.frame.source,interaction:T.frame.interaction}:{}});return}let C=VL(y);v=()=>{let T=Array.isArray(C.messages)?C.messages.length:0;cr(`orchestrator:persistTranscript(${T} msgs)`);let E=performance.now();ds(this.ctx.sessionLedger,o,C.messages);let _=performance.now();cr("orchestrator:completeRun"),this.ctx.sessionLedger.completeRun(o,C,{ownerId:s,expectedRevision:u.revision});let P=performance.now();Kt(),h();let Z=P-E;if(Z>100)try{process.stderr.write(`[Orchestrator][DIAG] deferredPersistence: total=${Z.toFixed(0)}ms transcript=${(_-E).toFixed(0)}ms completeRun=${(P-_).toFixed(0)}ms msgs=${T}
|
|
344
|
-
`)}catch{}},yield Gg(t,"run.start",C)}catch(C){try{(S.signal.aborted||e.isAbortError(C))&&(ds(this.ctx.sessionLedger,o,y.messages),this.clearRunningSession(o,s,u.revision)),h()}catch{}if(S.signal.aborted||e.isAbortError(C)){let T=e.getAbortCode(S.signal,C);T!=="CONNECTION_CLOSED"&&(yield or(t,"run.start",T??"RUN_ABORTED",e.getAbortMessage(S.signal,C),{sessionId:o,runId:`run:${o}`}));return}yield or(t,"run.start","RUN_START_FAILED",C instanceof Error?C.message:String(C))}finally{if(I&&clearInterval(I),R?.(),v){let C=v;v=null,setTimeout(()=>{try{cr("orchestrator:deferredPersistence");let T=performance.now();C();let E=performance.now()-T;if(Kt(),E>200)try{process.stderr.write(`[Orchestrator][DIAG] deferredPersistence blocked ${E.toFixed(0)}ms
|
|
345
|
-
`)}catch{}}catch{Kt(),h()}},0)}}}async*resume(t,r,n){let o=r.sessionId?.trim(),s=`headless:${t}`,i=this.ctx.getSessionModel?.(),a=this.ctx.getSessionArion?.(),c=FE($E(r,a),i),l=QL(c),d=PE(l),f=!1,u=null;try{if(n?.aborted)return;o&&(this.ctx.sessionLedger.loadSession(o)||(this.ctx.sessionLedger.createSession(c.arion??this.ctx.getSessionArion?.()??"ARIA",c.requestedModel??c.preferredTier??"balanced",o),f=!0),u=this.ctx.sessionLedger.claimSessionForMutation(o,s,3e4));let h=await this.ctx.localControl.resumeRun(l);if(n?.aborted){o&&u&&(this.ctx.sessionLedger.releaseSessionClaim(o,s),f&&this.ctx.sessionLedger.deleteSession(o));return}if(o&&u){if(h.state){let y=h.state;ds(this.ctx.sessionLedger,o,y.messages);let S=Xg(t,o,y);this.ctx.sessionLedger.recordPausedRun(o,`run:${o}`,y,d,S?.record,{ownerId:s,expectedRevision:u.revision}),this.ctx.sessionLedger.releaseSessionClaim(o,s),S&&(yield S.frame),yield or(t,"run.resume","INTERACTION_REQUIRED","Run paused and requires interaction before it can continue.",{sessionId:o,...S?{interactionId:S.frame.interactionId,source:S.frame.source,interaction:S.frame.interaction}:{}});return}ds(this.ctx.sessionLedger,o,h.messages),this.ctx.sessionLedger.completeRun(o,h,{ownerId:s,expectedRevision:u.revision}),this.ctx.sessionLedger.releaseSessionClaim(o,s)}yield Gg(t,"run.resume",h)}catch(h){if(o&&u)try{this.ctx.sessionLedger.releaseSessionClaim(o,s),f&&this.ctx.sessionLedger.deleteSession(o)}catch{}if(n?.aborted||e.isAbortError(h))return;yield or(t,"run.resume","RUN_RESUME_FAILED",h instanceof Error?h.message:String(h))}}async*abort(t,r,n){if(await(n??this.ctx.activeRunController)?.abort(r)){yield{kind:"result",requestId:t,op:"run.abort",ok:!0,result:{aborted:!0,...r.runId?{runId:r.runId}:{},...r.sessionId?{sessionId:r.sessionId}:{}}};return}yield or(t,"run.abort","RUN_NOT_FOUND","No active run matched the requested runId or sessionId.",{...r.runId?{runId:r.runId}:{},...r.sessionId?{sessionId:r.sessionId}:{}})}async*respond(t,r){let n=this.ctx.sessionLedger.getInteraction(t.interactionId);if(!n){yield or(t.requestId,"interaction.respond","INTERACTION_NOT_FOUND",`Unknown interaction ${t.interactionId}`);return}if(n.source!=="run"){yield or(t.requestId,"interaction.respond","UNSUPPORTED_INTERACTION_SOURCE",`Interaction source ${n.source} is not handled by the run orchestrator`);return}let o=this.ctx.sessionLedger.getSessionRuntimeState(n.sessionId);if(!o?.pausedState){yield or(t.requestId,"interaction.respond","SESSION_NOT_PAUSED",`Session ${n.sessionId} is not paused`);return}let s=`headless:${t.requestId}`;try{if(r?.aborted)return;let i=this.ctx.sessionLedger.claimSessionForMutation(n.sessionId,s,3e4),a=t.response,c=i.revision;if(n.status==="pending")this.ctx.sessionLedger.recordInteractionResponse(n.sessionId,n.interactionId,a,{ownerId:s,expectedRevision:i.revision}),c+=1;else if(n.status==="answered"){if(!n.response){this.ctx.sessionLedger.releaseSessionClaim(n.sessionId,s),yield or(t.requestId,"interaction.respond","INVALID_INTERACTION_STATE",`Interaction ${n.interactionId} is missing its recorded response`);return}if(!GL(n.response,a)){this.ctx.sessionLedger.releaseSessionClaim(n.sessionId,s),yield or(t.requestId,"interaction.respond","INTERACTION_ALREADY_ANSWERED",`Interaction ${n.interactionId} was already answered with a different response`);return}a=n.response}else{this.ctx.sessionLedger.releaseSessionClaim(n.sessionId,s),yield or(t.requestId,"interaction.respond","INTERACTION_NOT_PENDING",`Interaction ${n.interactionId} is not resumable in state ${n.status}`);return}let l=ZL(o.pausedState,n,{...t,response:a},o.revision,o.policySnapshot),d=await this.ctx.localControl.resumeRun(l);if(r?.aborted){this.ctx.sessionLedger.releaseSessionClaim(n.sessionId,s);return}if(d.state){let f=d.state;ds(this.ctx.sessionLedger,n.sessionId,f.messages);let u=Xg(t.requestId,n.sessionId,f);this.ctx.sessionLedger.recordPausedRun(n.sessionId,o.activeRunId??`run:${n.sessionId}`,f,o.policySnapshot??{},u?.record,{ownerId:s,expectedRevision:c}),this.ctx.sessionLedger.releaseSessionClaim(n.sessionId,s),u&&(yield u.frame),yield or(t.requestId,"interaction.respond","INTERACTION_REQUIRED","Run paused again and requires another interaction.",{sessionId:n.sessionId,...u?{interactionId:u.frame.interactionId,source:u.frame.source,interaction:u.frame.interaction}:{}});return}ds(this.ctx.sessionLedger,n.sessionId,d.messages),this.ctx.sessionLedger.completeRun(n.sessionId,d,{ownerId:s,expectedRevision:c}),this.ctx.sessionLedger.releaseSessionClaim(n.sessionId,s),yield Gg(t.requestId,"interaction.respond",d)}catch(i){try{this.ctx.sessionLedger.releaseSessionClaim(n.sessionId,s)}catch{}if(r?.aborted||e.isAbortError(i))return;yield or(t.requestId,"interaction.respond","INTERACTION_RESPONSE_FAILED",i instanceof Error?i.message:String(i))}}consumeRunEvent(t,r){switch(r.type){case"text_delta":t.output+=r.content;break;case"tool_result":t.toolCalls.push({id:r.id,name:r.name,input:r.input,result:r.result,durationMs:r.durationMs});break;case"usage_update":t.usage=r.usage;break;case"turn_complete":t.turnCount=r.turnNumber;break;case"guardrail_rejected":t.guardrailEvents.push({stage:r.stage,message:r.message});break;case"pipeline_timing":t.pipelineTiming=r.report;break;case"messages_snapshot":t.messages=Array.isArray(r.messages)?r.messages:[];break;case"thinking_end":r.blocks&&t.thinking.push(...r.blocks);break;case"native_tool_result":t.nativeToolResults.push(r.metadata);break;case"handoff_start":t.handoffs.push({type:"start",target:r.target,id:r.id});break;case"handoff_result":t.handoffs.push({type:"result",target:r.target,id:r.id,result:r.result});break;case"paused":t.pausedState=r.state;break;case"error":throw new Error(XL(r.error.message,"diagnostic"in r.error?r.error.diagnostic:void 0)??r.error.message);default:break}}}});var XE={};Ln(XE,{HeadlessKernel:()=>oc,createHeadlessKernelHandlers:()=>GE,createHeadlessKernelRuntime:()=>Kg});import eN,{join as Fm}from"node:path";import{appendFileSync as tN,mkdirSync as rN}from"node:fs";import{ArionManager as nN,ArionStorage as oN,MemoriaPool as sN}from"@aria-cli/aria";import{selectRunnableModelVariant as gi}from"@aria-cli/models";import{HEADLESS_OPERATION_SCHEMAS as BE}from"@aria-cli/tools";async function iN(e){let t=[];for(let r of e.sessionLedgers??[])try{r?.close()}catch(n){t.push(n)}for(let r of e.attachedClients??[])try{await r?.release()}catch(n){t.push(n)}try{await e.daemon?.releaseAll?.()}catch(r){t.push(r)}try{await e.managerPool?.closeAll()}catch(r){t.push(r)}try{await e.cli?.pool.closeAll()}catch(r){t.push(r)}if(t.length===1)throw t[0];if(t.length>1)throw new AggregateError(t,"Failed to release headless kernel bootstrap resources")}function hi(e){if(!(e instanceof Error))return!1;let t=e.message;return!!(t.includes("attached-local-client-only")||t.includes("ECONNRESET")||t.includes("ECONNREFUSED")||t.includes("EPIPE")||t.includes("connect ENOENT")||t.includes("socket hang up")||t.includes("closed before")||t.includes("has been released")||t.includes("no daemon found"))}function zg(e){if(!hi(e))return e instanceof Error?e:new Error(String(e));let t=e,r=t.message,n=t.reason??"",o=r.includes("ECONNRESET")||r.includes("ECONNREFUSED")||r.includes("EPIPE")||r.includes("connect ENOENT")||r.includes("socket hang up")||r.includes("closed before"),s=o?"Lost connection to the ARIA daemon. It may have restarted. Run `aria` again to reconnect.":n==="invalid_or_expired_lease"||n===""?"The ARIA daemon restarted and your session could not be restored. Run `aria` again to start a new session.":n==="missing_client_id"||n==="missing_proof"?"Client credentials were not sent. This is likely a bug \u2014 please report it.":n==="no_authority"?"The daemon has no attached-client authority configured. It may still be starting up.":`Session authentication failed (${n}). Run \`aria\` again to start a new session.`;return Object.assign(new Error(`Session expired: ${s} (${t.message})`),{code:"ARIA_SESSION_EXPIRED",reason:o?"connection_lost":n,cause:t},t.diagnostic!==void 0?{diagnostic:t.diagnostic}:{})}function Qr(e,t){try{$m||($m=Fm(e,"logs"),rN($m,{recursive:!0}));let r=JSON.stringify({ts:new Date().toISOString(),pid:process.pid,...t});tN(Fm($m,"reattach.jsonl"),r+`
|
|
346
|
-
`)}catch{}}function HE(e){return e<=0?Promise.resolve():new Promise(t=>{setTimeout(t,e).unref?.()})}function qE(e,t,r){let n=null,o=()=>(n||(n=e()),n),s=()=>{n=null,t?.()};async function i(c){try{let l=await o();return await c(l)}catch(l){if(!hi(l))throw l;let d=l instanceof Error?l.message:String(l),f=l.reason;r&&Qr(r,{event:"reattach_start",trigger:d,reason:f,maxAttempts:En.length});for(let u=0;u<En.length;u++){await HE(En[u]??0),s();try{let h=await o();return r&&Qr(r,{event:"reattach_success",attempt:u,trigger:d}),await c(h)}catch(h){let y=h instanceof Error?h.message:String(h);if(r&&Qr(r,{event:"reattach_retry_failed",attempt:u,error:y,willRetry:hi(h)&&u<En.length-1}),!hi(h)||u===En.length-1)throw r&&Qr(r,{event:"reattach_exhausted",attempts:u+1,finalError:y}),zg(h)}}throw zg(l)}}async function*a(c){let l;try{let u=await o();yield*c(u);return}catch(u){if(!hi(u))throw u;l=u instanceof Error?u:new Error(String(u))}let d=l?.message??"unknown",f=l?.reason;r&&Qr(r,{event:"reattach_stream_start",trigger:d,reason:f,maxAttempts:En.length});for(let u=0;u<En.length;u++){await HE(En[u]??0),s();try{let h=await o();r&&Qr(r,{event:"reattach_stream_success",attempt:u,trigger:d}),yield*c(h);return}catch(h){let y=h instanceof Error?h.message:String(h);if(r&&Qr(r,{event:"reattach_stream_retry_failed",attempt:u,error:y,willRetry:hi(h)&&u<En.length-1}),!hi(h)||u===En.length-1)throw r&&Qr(r,{event:"reattach_stream_exhausted",attempts:u+1,finalError:y}),zg(h)}}}return{submitRun(c){return i(l=>l.submitRun(c))},resumeRun(c){return i(l=>l.resumeRun(c))},async*streamRun(c,l){yield*a(d=>d.streamRun(c,l))},async*subscribeRuntimeEvents(c){yield*a(l=>l.subscribeRuntimeEvents(c))},sendBestEffort(c){return i(l=>l.sendBestEffort(c))},sendDurable(c){return i(l=>l.sendDurable(c))},listInbox(c){return i(l=>l.listInbox(c))},async*subscribeInbox(c){yield*a(l=>l.subscribeInbox(c))},listPeers(){return i(c=>c.listPeers())},listNearbyPeers(){return i(c=>c.listNearbyPeers())},async*subscribePeers(){yield*a(c=>c.subscribePeers())},getRuntimeStatus(){return i(c=>c.getRuntimeStatus())},getRuntimeBootstrap(){return i(c=>c.getRuntimeBootstrap())},listPendingPairRequests(){return i(c=>c.listPendingPairRequests())},respondToPairRequest(c){return i(l=>l.respondToPairRequest(c))},createInvite(c){return i(l=>l.createInvite(c))},listPendingInvites(){return i(c=>c.listPendingInvites())},acceptInviteToken(c){return i(l=>l.acceptInviteToken(c))},cancelInvite(c){return i(l=>l.cancelInvite(c))},invitePeer(c){return i(l=>l.invitePeer(c))},acceptInvite(c){return i(l=>l.acceptInvite(c))},directPair(c){return i(l=>l.directPair(c))},revokePeer(c){return i(l=>l.revokePeer(c))},repairPeer(c){return i(l=>l.repairPeer(c))},listAttachedClients(){return i(c=>c.listAttachedClients())},listDirectClientInbox(c){return i(l=>l.listDirectClientInbox(c))},async*subscribeDirectClientInbox(c){yield*a(l=>l.subscribeDirectClientInbox(c))}}}function cN(e,t,r){return new Promise((n,o)=>{let s=setTimeout(()=>{o(new Error(r))},t);s.unref?.(),e.then(i=>{clearTimeout(s),n(i)},i=>{clearTimeout(s),o(i)})})}function WE(e,t,r,n,o){return{kind:"result",requestId:e,op:t,ok:!1,error:{code:r,message:n,...o?{details:o}:{}}}}function lN(e,t,r){let n=e.trim().toLowerCase();if(!n)return;let o=[...t].sort((u,h)=>u.shortName.localeCompare(h.shortName)),s=o.find(u=>`${u.provider}/${u.shortName}`.toLowerCase()===n);if(s)return s;let i=o.find(u=>u.shortName.toLowerCase()===n);if(i)return gi(i,r);let a=o.find(u=>u.shortName.toLowerCase().startsWith(n));if(a)return gi(a,r);let c=o.find(u=>`${u.provider}/${u.shortName}`.toLowerCase().startsWith(n));if(c)return c;let l=o.find(u=>u.tier.toLowerCase()===n);if(l)return gi(l,r);let d=o.find(u=>u.displayName.toLowerCase().includes(n));if(d)return gi(d,r);let f=o.find(u=>u.provider.toLowerCase().includes(n));return f?gi(f,r):void 0}function GE(e){let t=new Pm({localControl:e.localControl,sessionLedger:e.sessionLedger,activeRunController:e.activeRunController,getSessionModel:e.getSessionModel,getSessionArion:e.getSessionArion}),r=new jm(e.auth,e.sessionLedger,async()=>await e.config?.getActiveArion?.()??e.cli?.config?.activeArion??"ARIA"),n=$g(t),o=vg(e),s=wg(e),i=Ng(e),a=xg(e,r),c=Ag(e),l=iE(e),d=gE(e),f=yE(e),u=jg(e),h=Cg(e),y=Dg(e),S=Nm(e);return{"run.start":n["run.start"],"run.resume":n["run.resume"],"run.abort":n["run.abort"],"interaction.respond":async function*(R,I,v){let C=I&&typeof I=="object"&&"kind"in I?I:{kind:"interaction.respond",requestId:R,...I};if(e.sessionLedger.getInteraction(C.interactionId)?.source==="auth"){yield*r.respond(C,v);return}yield*n["interaction.respond"](R,C,v)},"session.list":S["session.list"],"session.read":S["session.read"],"session.load":S["session.load"],"session.fork":S["session.fork"],"memory.remember":o["memory.remember"],"memory.recall":o["memory.recall"],"memory.list":o["memory.list"],"memory.forget":o["memory.forget"],"memory.recall_knowledge":o["memory.recall_knowledge"],"arion.list":s["arion.list"],"arion.hatch":s["arion.hatch"],"arion.become":s["arion.become"],"arion.rest":s["arion.rest"],"arion.wake":s["arion.wake"],"arion.create":s["arion.create"],"model.list":i["model.list"],"model.set":i["model.set"],"model.refresh":i["model.refresh"],"auth.status":a["auth.status"],"auth.login":a["auth.login"],"auth.logout":a["auth.logout"],"peer.list":u["peer.list"],"peer.list_nearby":u["peer.list_nearby"],"peer.pending.list":u["peer.pending.list"],"peer.pending.respond":u["peer.pending.respond"],"peer.invite":u["peer.invite"],"peer.connect":u["peer.connect"],"peer.accept_invite":u["peer.accept_invite"],"peer.direct_pair":u["peer.direct_pair"],"peer.repair":u["peer.repair"],"peer.revoke":u["peer.revoke"],"client.list":h["client.list"],"client.inbox.list":h["client.inbox.list"],"message.send":y["message.send"],"message.inbox.list":y["message.inbox.list"],"config.theme.get":c["config.theme.get"],"config.theme.set":c["config.theme.set"],"config.autonomy.get":c["config.autonomy.get"],"config.autonomy.set":c["config.autonomy.set"],"system.restart":f["system.restart"],"system.terminal_setup":f["system.terminal_setup"],"daemon.start":l["daemon.start"],"daemon.status":l["daemon.status"],"daemon.stop":l["daemon.stop"],"hook.extract":d["hook.extract"],"hook.reflect":d["hook.reflect"],"hook.consolidate":d["hook.consolidate"],"hook.ingest":d["hook.ingest"],"hook.harvest":d["hook.harvest"]}}async function Kg(e){let t=null,r=null,n=null,o=new Map,s=new Map,i=new Set,a=!1,c=async()=>{if(a)return;a=!0;let l=await Promise.allSettled([...s.values(),...i.values()]);await iN({sessionLedgers:[...o.values()],attachedClients:l.flatMap(d=>d.status==="fulfilled"?[d.value]:[]),daemon:n,managerPool:r,cli:t})};try{t=await cs({cwd:e?.cwd,skipDiscoveryRefresh:!0});let l=t,d=e?.arionName??l.config.activeArion??"ARIA",f,u=()=>d,h=()=>f,y=N=>{d=N;let A=ue();A.activeArion=N,Le(A)},S=N=>{let A=o.get(N);return A||(A=new Nn(Nn.resolvePerArionPath(l.ariaDir,N)),o.set(N,A)),A},R=async()=>{try{let{resolveRuntimeRootDirectory:N,findRuntimeOwnerRecordByAriaHome:A}=await import("@aria-cli/server"),{createResilientAttachedClient:$}=await Promise.resolve().then(()=>(Am(),GT)),he=N(),ae=A(he,l.ariaDir);if(!ae?.runtimeSocket)return null;let oe=await $({runtimeSocket:ae.runtimeSocket,clientKind:"local-api",logDir:Fm(l.ariaDir,"logs")});return{nodeId:ae.nodeId,runtimeId:ae.runtimeId??"daemon",port:0,ownership:"reattached",control:oe.api,attachedClientId:oe.getClientId(),attachedClientAuthToken:oe.getClientAuthToken(),release:()=>oe.release()}}catch(N){return Qr(l.ariaDir,{event:"daemon_socket_connect_failed",error:N instanceof Error?N.message:String(N)}),null}},I=async N=>{let A=s.get(N);return A||(A=(async()=>{let $=await R();if($)return Qr(l.ariaDir,{event:"ensureAttachedClient_resolved",path:"daemon_socket",arionName:N}),a&&await $.release().catch(()=>{}),$;Qr(l.ariaDir,{event:"ensureAttachedClient_fallback",path:"attachLocalControlClient",arionName:N});let he;try{he=await Dl({ariaHome:l.ariaDir,arionName:N,clientKind:"local-api",runtimeLifecycle:"scoped",memoriaFactory:l.memoriaFactory,router:l.router,authResolver:l.authResolver,runSessionConfig:l.config,mcpServers:l.projectConfig.mcp?.servers,silent:!0})}catch(ae){throw ae instanceof Error&&ae.message.includes("already in use")?new Error("A daemon is running but could not be reached. Ensure ARIA_HOME matches the daemon's home directory, or stop the daemon with: aria-stop"):ae}return a&&await he.release().catch(()=>{}),he})(),s.set(N,A)),cN(A,aN,`Timed out attaching local control for ${N}`).catch($=>{throw i.add(A),A.finally(()=>{i.delete(A)}),s.delete(N),$})},v=qE(async()=>(await I(u())).control,()=>{let N=u(),A=s.get(N);A&&(i.add(A),A.then($=>$.release().catch(()=>{})).finally(()=>i.delete(A)),s.delete(N))},l.ariaDir),C=new Proxy({},{get(N,A){let $=S(u()),he=$[A];return typeof he=="function"?he.bind($):he}});S(d),r=new sN(l.ariaDir);let T=new nN(new oN(l.ariaDir),r.toFactory());T.setRouter(l.router),await T.initialize();let E=l.availableModels,_=async()=>{let N=u();return(await T.get(N))?.memoriaPath??eN.join("arions",N,"memory.db")},P=async()=>await l.pool.get(await _()),Z=new Proxy({},{get(N,A){return async(...$)=>{let he=await P(),ae=he[A];return typeof ae!="function"?ae:ae.apply(he,$)}}});n=Pl({cli:l,cwd:e?.cwd??process.cwd(),arionName:u(),getArionName:u,localControl:v});let nt=vE({cli:l,arionName:u(),getArionName:u,resolveMemoriaPath:_}),ze={cli:l,localControl:v,sessionLedger:C,arionManager:{list:()=>T.list(),hatch:N=>T.hatch(N),get:N=>T.get(N),wake:N=>T.wake(N),rest:(N,A)=>T.rest(N,A)},memoria:Z,config:{async getTheme(){return ue().theme??x().name},async setTheme(N){if(!cn().includes(N))throw new Error(`Unknown theme: ${N}`);an(N);let $=ue();return $.theme=N,Le($),{theme:N}},async getAutonomy(){return ue().autonomy??"balanced"},async setAutonomy(N){if(!["minimal","balanced","high","full"].includes(N))throw new Error(`Invalid autonomy level: ${N}`);let A=ue();return A.autonomy=N,Le(A),{autonomy:N}},async getActiveArion(){return u()},async setActiveArion(N){y(N)}},auth:{async status(){return{providers:ZT()}},async login(N){return eE(rE(N))},async logout(N){return tE(nE(N))}},modelDiscovery:{async listAvailable(){return E},async refresh(N){return E=await l.refreshAvailableModels(N),E},async getCurrentModel(){if(f)return f;let N=await T.get(u());if(N?.preferredModel)return f=N.preferredModel,f;let A=ue().preferredTier??l.config.preferredTier;return A?(f=gi(E.find($=>$.tier===A)??E[0],l.credentialHints)?.shortName??E[0]?.shortName,f):E[0]?.shortName},async setCurrentModel(N){let A=lN(N,E,l.credentialHints);if(!A)throw new Error(`Unknown model: ${N}`);f=A.shortName;let $=u();await T.get($)&&await T.setPreferredModel($,A.shortName);let ae=ue();return ae.preferredTier=A.tier,Le(ae),{currentModel:A.shortName,tier:A.tier}},async getSessionModel(){return f}},daemon:n,hook:nt,system:{async restart(N){return{accepted:!0,reason:typeof N.reason=="string"&&N.reason.trim().length>0?N.reason.trim():"Restart requested"}},async terminalSetup(){return As()?{supported:!0,output:Wd().trim()}:{supported:!1,message:"terminal-setup is supported only in iTerm2 (macOS) and VSCode terminal."}}},getSessionModel:h,getSessionArion:u},le=await T.get(u());if(le?.preferredModel)f=le.preferredModel;else{let N=ue().preferredTier??l.config.preferredTier;f=gi(E.find(A=>A.tier===N)??E[0],l.credentialHints)?.shortName??E[0]?.shortName}return{kernel:new oc(ze),ctx:ze,async release(){await c()}}}catch(l){try{await c()}catch(d){throw new AggregateError([l,d],"Headless kernel bootstrap failed and resource cleanup also failed")}throw l}}var En,$m,aN,oc,Um=G(()=>{"use strict";Tm();_r();vl();Am();yg();Sg();oE();Rg();Ig();aE();hE();wE();kg();Lg();Og();Pg();jl();xE();Om();kE();NE();UE();qd();D();En=[0,250,500,1e3,2e3,3e3];aN=1e4;oc=class{ctx;handlers;constructor(t,r){if(this.ctx=t,!r){let n=!1,o=t.localControl;t.localControl=qE(async()=>{if(!n)return o;let{createResilientAttachedClient:s}=await Promise.resolve().then(()=>(Nl(),Rm)),i=await import("@aria-cli/server"),a=i.resolveRuntimeRootDirectory(),c=i.findRuntimeOwnerRecordByAriaHome(a,t.cli.ariaDir);if(!c?.runtimeSocket)throw new Error("Cannot reconnect: no daemon found after restart");return(await s({runtimeSocket:c.runtimeSocket,clientKind:"local-api",logDir:Fm(t.cli.ariaDir,"logs")})).api},()=>{n=!0},t.cli.ariaDir)}this.handlers=r??GE(t)}async*dispatch(t,r={}){if(t.kind==="interaction.respond"){let s=BE["interaction.respond"].input.safeParse({interactionId:t.interactionId,response:t.response});if(!s.success){yield WE(t.requestId,"interaction.respond","INVALID_INPUT",s.error.issues.map(i=>`${i.path.join(".")||"<root>"} ${i.message}`).join("; "));return}yield*this.handlers["interaction.respond"](t.requestId,t,r);return}let n=t,o=BE[n.op].input.safeParse(n.input);if(!o.success){yield WE(n.requestId,n.op,"INVALID_INPUT",o.error.issues.map(s=>`${s.path.join(".")||"<root>"} ${s.message}`).join("; "));return}yield*this.handlers[n.op](n.requestId,o.data,r)}getContext(){return this.ctx}}});var c0={};Ln(c0,{ensureDaemon:()=>Gm});import a0 from"node:path";function nO(e){try{return process.kill(e,0),!0}catch{return!1}}function i0(e){return(async()=>{try{let{resolveRuntimeRootDirectory:t,findRuntimeOwnerRecordByAriaHome:r,removeRuntimeOwnerRecord:n}=await import("@aria-cli/server"),o=t(),s=r(o,e);if(!s?.runtimeSocket)return null;if(!nO(s.runtimePid))return n(o,s.nodeId),null;let{createResilientAttachedClient:i}=await Promise.resolve().then(()=>(Nl(),Rm)),a=await i({runtimeSocket:s.runtimeSocket,clientKind:"local-api",logDir:a0.join(e,"logs")});try{let c=await a.api.getRuntimeBootstrap();if(!oO.has(c.phase))return await a.release(),n(o,s.nodeId),null}catch{return await a.release(),null}return{control:a.api,release:()=>a.release()}}catch{return null}})()}async function Gm(e){let t=await i0(e.ariaDir);if(t)return t;let{createDaemonService:r}=await Promise.resolve().then(()=>(Om(),TE)),n=e.config.activeArion??"ARIA";await r({cli:e,cwd:process.cwd(),arionName:n}).start({});let{resolveRuntimeRootDirectory:s}=await import("@aria-cli/server"),i=s(),a=a0.join(i,"owners"),c=Date.now()+15e3,l=null,d=null;try{let{watch:f,mkdirSync:u,existsSync:h}=await import("node:fs");h(a)||u(a,{recursive:!0,mode:448});try{l=f(a,()=>d?.()),l.on("error",()=>{})}catch{}let y=50;for(;Date.now()<c;){let S=await i0(e.ariaDir);if(S)return S;await new Promise(R=>{d=R,setTimeout(R,y)}),d=null,y=Math.min(Math.round(y*1.5),200)}}finally{l?.close()}throw new Error("Daemon started but socket not reachable. Check ARIA_HOME.")}var oO,rw=G(()=>{"use strict";oO=new Set(["control_ready","network_ready","mesh_ready"])});var S0={};Ln(S0,{runRuntimeCutoverReset:()=>y0,runtimeCutoverResetCommand:()=>x0});import*as Ve from"node:fs";import*as xe from"node:path";import{resolveRuntimeRootDirectory as h0,runtimeSocketsDirectory as SO}from"@aria-cli/server";import g0 from"better-sqlite3";function bO(e){let t=xe.resolve(e);try{return Ve.realpathSync.native(t)}catch{return t}}function w0(){return xe.join(process.env.HOME??"/tmp",".aria")}function Xm(e){return xe.join(e,"node","node-state.db")}function TO(e){return`${Xm(e)}.lock`}function EO(e){return xe.join(e,"node","runtime-cutover-last-report.json")}function lw(e){if(!Number.isFinite(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}function wt(e,t){if(!Ve.existsSync(e)){t.skippedPaths.push(e);return}Ve.rmSync(e,{recursive:!0,force:!0}),t.removedPaths.push(e)}function Ul(e,t){for(let r of[e,`${e}-wal`,`${e}-shm`])wt(r,t)}function _O(e){let t=xe.join(e,"arions");return Ve.existsSync(t)?Ve.readdirSync(t,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>xe.join(t,r.name)):[]}function CO(e){let t=xe.join(e,"owners");if(!Ve.existsSync(t))return[];let r=new Set;for(let n of Ve.readdirSync(t))if(n.endsWith(".json"))try{let o=Ve.readFileSync(xe.join(t,n),"utf8"),s=JSON.parse(o);typeof s.runtimePid=="number"&&lw(s.runtimePid)&&r.add(s.runtimePid)}catch{}return[...r]}function RO(e,t,r){if(!Ve.existsSync(e))return[];let n=new Set;for(let o of Ve.readdirSync(e))if(t(o))try{let s=JSON.parse(Ve.readFileSync(xe.join(e,o),"utf8")),i=r(s);i!==null&&lw(i)&&n.add(i)}catch{}return[...n]}function AO(e){return RO(e,t=>t.startsWith("presence-")&&t.endsWith(".json"),t=>typeof t=="object"&&t!==null&&"pid"in t&&typeof t.pid=="number"?t.pid:null)}function IO(e){let t=Xm(e);if(!Ve.existsSync(t))return[];let r=new g0(t,{readonly:!0});try{return r.prepare(`SELECT runtime_pid
|
|
347
|
-
FROM runtime_owner_records`).all().map(o=>o.runtime_pid).filter(o=>Number.isFinite(o)&&lw(o))}catch{return[]}finally{r.close()}}function vO(e,t){let r=w0(),n=AO(r),o=CO(t),s=IO(e),i=[...new Set([...n,...o,...s])];if(i.length>0)throw new Error(`[runtime-cutover-reset] refuse live runtime mutation while runtime is live (pids: ${i.join(", ")}). Stop all ARIA daemons/clients first.`)}function kO(e,t){let r=Xm(e);if(!Ve.existsSync(r))return{runtimeOwnerRecords:0,runtimeEvents:0};let n=new g0(r);try{let o=n.prepare("DELETE FROM runtime_owner_records").run().changes,s=n.prepare("DELETE FROM runtime_events").run().changes;return t.preservedPaths.push(r),{runtimeOwnerRecords:o,runtimeEvents:s}}finally{n.close()}}function MO(e,t){let r=w0();wt(xe.join(r,"mesh-events.db"),t),wt(xe.join(r,"mesh-events.db-wal"),t),wt(xe.join(r,"mesh-events.db-shm"),t),wt(xe.join(r,"event_queue"),t),wt(xe.join(r,"event_queue.db"),t),wt(xe.join(r,"event_queue.db-wal"),t),wt(xe.join(r,"event_queue.db-shm"),t),wt(xe.join(h0(),"host-supervisor.sock"),t);let n=[...new Set([r,e])];for(let o of n)if(Ve.existsSync(o))for(let s of Ve.readdirSync(o)){let i=s.startsWith("daemon-info-")&&(s.endsWith(".json")||s.endsWith(".json.lock")),a=o===r&&s.startsWith("presence-")&&s.endsWith(".json");(i||a)&&wt(xe.join(o,s),t)}}function DO(e,t,r,n){Ul(xe.join(e,"network","state.db"),n),wt(xe.join(e,"network","trusted-cas"),n),wt(xe.join(e,"server-session-history.json"),n),wt(xe.join(e,"sessions"),n),Ul(xe.join(e,"history.db"),n);for(let o of _O(e))Ul(xe.join(o,"memory.db"),n),Ul(xe.join(o,"history.db"),n),wt(xe.join(o,"daemon"),n),wt(xe.join(o,"logs"),n);return wt(xe.join(t,"owners"),n),wt(SO(t),n),r?(Ul(Xm(e),n),wt(TO(e),n),wt(xe.join(e,"network","config.json"),n),wt(xe.join(e,"network","tls"),n),{runtimeOwnerRecords:0,runtimeEvents:0}):(n.preservedPaths.push(xe.join(e,"network","config.json")),n.preservedPaths.push(xe.join(e,"network","tls")),kO(e,n))}function LO(e){return Ve.mkdirSync(xe.dirname(e.reportPath),{recursive:!0}),Ve.writeFileSync(e.reportPath,`${JSON.stringify(e,null,2)}
|
|
348
|
-
`,"utf8"),e}function NO(e){console.log("[runtime-cutover-reset] completed"),console.log(` ariaHome: ${e.ariaHome}`),console.log(` fullReset: ${e.fullReset?"yes":"no"}`),console.log(` preserveLocalNodeIdentity: ${e.preserveLocalNodeIdentity?"yes":"no"}`),console.log(` deleted: ${e.deletedPaths.length}`),console.log(` preserved: ${e.preservedPaths.length}`),console.log(` cleared runtime owner records: ${e.cleared.runtimeOwnerRecords}`),console.log(` cleared runtime journal events: ${e.cleared.runtimeEvents}`),console.log(` report: ${e.reportPath}`)}async function y0(e={}){let t=bO(e.ariaHome??lr()),r=h0(),n=e.fullNodeReset??e.fullReset??!1,o=e.preserveLocalNodeIdentity??!n;vO(t,r);let s={ariaHome:t,runtimeRoot:r,generatedAt:new Date().toISOString(),fullReset:n,fullNodeReset:n,preserveLocalNodeIdentity:o,reportPath:EO(t),removedPaths:[],deletedPaths:[],preservedPaths:[],skippedPaths:[],cleared:{runtimeOwnerRecords:0,runtimeEvents:0}};return MO(t,s),s.cleared=DO(t,r,n,s),s.deletedPaths=[...s.removedPaths],LO(s)}async function x0(e={}){let t=await y0(e);if(e.json){console.log(JSON.stringify(t,null,2));return}NO(t)}var dw=G(()=>{"use strict";_r()});Tf();import{jsx as tw}from"react/jsx-runtime";import{useState as U,useCallback as V,useEffect as lt,useRef as Ae,useMemo as Fl}from"react";import{render as bN,useApp as TN}from"ink";import{jsx as Kh,jsxs as dM}from"react/jsx-runtime";import{useMemo as uM,useState as mM}from"react";import{Box as fM,useStdout as pM}from"ink";import{jsx as re,jsxs as mi,Fragment as sM}from"react/jsx-runtime";import{useState as os,useCallback as eo,useMemo as ss,useEffect as Jr}from"react";import{Box as Tn,Static as iM,Text as to,useApp as aM,useInput as cM}from"ink";import{jsxs as mt,jsx as st,Fragment as xo}from"react/jsx-runtime";import{Box as Ef,Text as De}from"ink";import{toShortName as i_}from"@aria-cli/models";var On={colors:{cyan:"cyan",magenta:"magenta",yellow:"yellow",green:"green",blue:"blue",red:"red",white:"white",gray:"gray",dim:"gray"},prompt:{symbol:"\u276F"},divider:{char:"\u2500"}};function Ac(e){return!e||!(e in On.colors)?On.colors.white:On.colors[e]}function Iw(e){return i_(e)}var Zi={"opus-4.6":"#B4A0FF","opus-4.5":"#A08AFF","sonnet-4.6":"#5FA8FF","sonnet-4.5":"#4A96FF","haiku-4.5":"#5CE0D0","gemini-3.1-pro":"#FFB84D","gemini-3-pro":"#FFA833","gemini-2.5-pro":"#FF9E22","gemini-3-flash":"#8AE065","gemini-2.5-flash":"#7BD055","gpt-5.4":"#5CD17A","gpt-5.2":"#50C878","gpt-5.1":"#45B86A","gpt-5.3-codex":"#20B2AA","gpt-5.2-codex":"#1CA8A0","gpt-5.1-codex":"#189090"};function Id(e){if(Zi[e])return Zi[e];let t=e.replace(/^bedrock-/,"").replace(/^claude-/,"").replace(/-copilot$/,"");if(Zi[t])return Zi[t];let r=t.split("-");for(let n=r.length-1;n>=2;n--){let o=r.slice(0,n).join("-");if(Zi[o])return Zi[o]}}var vw={anthropic:{icon:"\u25C6",color:"#B4A0FF"},google:{icon:"\u25B2",color:"#4285F4"},bedrock:{icon:"\u2B22",color:"#FF9900"},"bedrock-converse":{icon:"\u2B22",color:"#FF9900"},openai:{icon:"\u25CE",color:"#50C878"},"openai-codex":{icon:"\u25C8",color:"#20B2AA"},"github-copilot":{icon:"\u22A1",color:"#6E40C9"},local:{icon:"\u25CB",color:"gray"}};function kw(e){return vw[e]??{icon:"\u25CB",color:"gray"}}function a_(e){if(e.startsWith("bedrock-"))return"bedrock";if(e.endsWith("-copilot"))return e.includes("gpt-")&&e.includes("-codex")?"openai-codex":e.includes("gemini-")?"google":"github-copilot";if(e.startsWith("gemini-"))return"google";if(e.includes("-codex"))return"openai-codex";if(e.startsWith("gpt-")||e.startsWith("o1")||e.startsWith("o3"))return"openai";if(/^(opus|sonnet|haiku)-/.test(e))return"anthropic"}function Mw(e){let t=a_(e);if(t)return vw[t]}var c_="balanced";function kd(e){if(e<1e3)return String(e);if(e<1e6){let r=e/1e3;return r>=100?`${Math.round(r)}k`:`${r.toFixed(1)}k`}let t=e/1e6;return t>=100?`${Math.round(t)}M`:`${t.toFixed(1)}M`}function Rf(e){return`$${e.toFixed(2)}`}function l_(e){if(e<60)return`${e.toFixed(1)}s`;let t=Math.floor(e/60),r=Math.round(e%60);return`${t}m ${r}s`}function d_(e,t){return t<=0?0:Math.min(100,Math.round(e/t*100))}var _f="#B4A0FF",vd={low:{bars:"\u258C",color:"blue"},medium:{bars:"\u258C\u258C",color:"cyan"},high:{bars:"\u258C\u258C\u258C",color:"yellow"},max:{bars:"\u258C\u258C\u258C\u258C",color:"magenta"}},u_={minimal:{symbol:"\u25B8",label:"confirm all",color:"green"},balanced:{symbol:"\u25B8\u25B8",label:"confirm risky",color:"yellow"},high:{symbol:"\u25B8\u25B8\u25B8",label:"auto-approve",color:"magenta"},full:{symbol:"\u23F5\u23F5",label:"full bypass",color:"red"}},Cf=8,jn=" \xB7 ";function Af({arion:e,model:t,maxContextTokens:r=0,responseTime:n,metrics:o,showCosts:s=!0,displayMode:i,activeArion:a,effortLevel:c,autonomyLevel:l=c_,meshMessageCount:d=0}){let f=Ac(e.color),u=Iw(t),h=Id(u),y=Mw(u),S=i==="debug",R=o&&o.turnCount>0,I=R?o.contextTokens:0,v=r>0?d_(I,r):0,C=Math.min(Cf,Math.round(v/100*Cf)),T=Cf-C,E=R?`${v}%`:"\u2013",_=u_[l];return mt(Ef,{justifyContent:"space-between",children:[mt(Ef,{children:[mt(De,{children:[e.emoji," "]}),st(De,{color:f,bold:!0,children:e.name}),st(De,{dimColor:!0,children:jn}),R?mt(xo,{children:[y&&mt(De,{color:y.color,children:[y.icon," "]}),st(De,{color:h,dimColor:!h,children:u}),c&&mt(xo,{children:[st(De,{dimColor:!0,children:jn}),st(De,{color:vd[c].color,children:vd[c].bars})]}),st(De,{dimColor:!0,children:jn}),mt(De,{dimColor:!0,children:["Turn ",o.turnCount]}),st(De,{dimColor:!0,children:jn}),mt(De,{color:o.contextStale?void 0:_f,dimColor:o.contextStale,children:[o.contextStale?"~":"",kd(o.contextTokens)]}),r>0&&mt(De,{dimColor:!0,children:["/",kd(r)]}),S&&s&&mt(xo,{children:[st(De,{dimColor:!0,children:jn}),st(De,{dimColor:!0,children:Rf(o.estimatedCost)})]}),S&&mt(xo,{children:[st(De,{dimColor:!0,children:jn}),st(De,{dimColor:!0,children:l_(o.wallTimeSeconds)})]}),a&&a!==e.name&&mt(xo,{children:[st(De,{dimColor:!0,children:jn}),st(De,{dimColor:!0,children:a})]})]}):mt(xo,{children:[y&&mt(De,{color:y.color,children:[y.icon," "]}),st(De,{color:h,dimColor:!h,children:u}),c&&mt(xo,{children:[st(De,{dimColor:!0,children:jn}),st(De,{color:vd[c].color,children:vd[c].bars})]}),n!==void 0&&mt(xo,{children:[st(De,{dimColor:!0,children:jn}),mt(De,{dimColor:!0,children:[n.toFixed(1),"s"]})]})]})]}),mt(Ef,{gap:1,children:[d>0&&mt(De,{color:"yellow",bold:!0,children:["msg ",d]}),mt(De,{color:_.color,children:[_.symbol," ",_.label]}),st(De,{dimColor:!0,children:"ctx"}),st(De,{color:_f,children:"\u2588".repeat(C)}),st(De,{dimColor:!0,children:"\u2591".repeat(T)}),st(De,{color:_f,children:E})]})]})}import{jsx as Dw,jsxs as If}from"react/jsx-runtime";import{Box as Lw,Text as vf}from"ink";function kf({userName:e}){return e?If(Lw,{children:[Dw(vf,{color:On.colors.cyan,children:e}),If(vf,{children:[" ",On.prompt.symbol," "]})]}):Dw(Lw,{children:If(vf,{color:On.colors.cyan,children:[On.prompt.symbol," "]})})}import{jsx as Jj,jsxs as Qj}from"react/jsx-runtime";import{Box as eP,Text as tP}from"ink";D();import ln,{Chalk as oy}from"chalk";import sy from"color-name";import f_ from"katex";import{Marked as p_}from"marked";import{markedTerminal as h_}from"marked-terminal";import{highlight as Kw,supportsLanguage as Vw}from"cli-highlight";function Lf(e,t){let r=m_(t);return Vw(r)?Kw(e,{language:r}):Vw("markdown")?Kw(e,{language:"markdown"}):e}function m_(e){let t={js:"javascript",jsx:"javascript",ts:"typescript",tsx:"typescript",sh:"bash",shell:"bash",zsh:"bash",yml:"yaml",py:"python",rb:"ruby",rs:"rust",go:"go",md:"markdown",dockerfile:"docker"},r=e.toLowerCase().trim();return t[r]??r}D();import{marked as jj}from"marked";var Yw=["\u2022","\u25E6","\u25AA","\u25AB"];function St(e,t={}){let r=Z_(e),n=t.mode==="streaming"?tC(r):r,{content:o,placeholders:s}=w_(n),i=x_(t.colorWordMode),a=new p_;a.use(h_({showSectionPrefix:!1,reflowText:!1,emoji:!1,unescape:!0,width:t.width??(process.stdout.columns||80),tab:2,hr:()=>ln.dim("\u2500".repeat(t.width??40))})),a.use({renderer:{text(d){return"tokens"in d&&d.tokens?this.parser.parseInline(d.tokens):py(d.text,i)},paragraph(d){return this.parser.parseInline(d.tokens)+`
|
|
349
|
-
|
|
350
|
-
`},code(d){let f=x(),u=d.lang||"text";try{return`
|
|
351
|
-
`+Lf(d.text,u)+`
|
|
352
|
-
|
|
353
|
-
`}catch{return`
|
|
354
|
-
`+ln.hex(f.colors.info)(d.text)+`
|
|
355
|
-
|
|
356
|
-
`}},codespan(d){let f=x();return ln.hex(f.colors.info)(d.text)},link(d){let f=x(),u=this.parser.parseInline(d.tokens),h=d.href;return g_()?`\x1B]8;;${h}\x07${ln.hex(f.colors.info).underline(u)}\x1B]8;;\x07`:u===h?ln.hex(f.colors.info).underline(u):`${ln.hex(f.colors.info).underline(u)} (${ln.dim(h)})`},list(d){let f=d.items,u=d.ordered,h=typeof d.start=="number"?d.start:1,y=this._listDepth??0;return`
|
|
357
|
-
`+f.map((R,I)=>{let v=u?`${h+I}.`:Yw[y%Yw.length],C=" ".repeat(y),T=this._listDepth;this._listDepth=y+1;let E=this.parser.parse(R.tokens).trim();return this._listDepth=T,`${C}${v} ${E}`}).join(`
|
|
358
|
-
`)+`
|
|
359
|
-
|
|
360
|
-
`},blockquote(d){return this.parser.parse(d.tokens).split(`
|
|
361
|
-
`).filter(h=>h.trim()).map(h=>ln.dim.italic(`\u2502 ${h}`)).join(`
|
|
362
|
-
`)+`
|
|
363
|
-
|
|
364
|
-
`},table(d){let f=t.width??(process.stdout.columns||80),u=d.header.length;if(u===0)return`
|
|
365
|
-
`;let h=d.header.map(T=>this.parser.parseInline(T.tokens)),y=d.rows.map(T=>T.map(E=>this.parser.parseInline(E.tokens))),S=new Array(u).fill(0),R=new Array(u).fill(0);for(let T=0;T<u;T++){let E=[h[T]??"",...y.map(_=>_[T]??"")];S[T]=Nc(h[T]??"");for(let _ of E)S[T]=Math.max(S[T],Nc(_));R[T]=cC(E)}let I=u+1+u*2;S.reduce((T,E)=>T+E,0)+I>f&&iC(S,f-I,R);let v=(T,E,_)=>T+S.map(P=>"\u2500".repeat(P+2)).join(E)+_,C=[v("\u250C","\u252C","\u2510")];C.push(...ny(h,S,d.align)),C.push(v("\u251C","\u253C","\u2524"));for(let T=0;T<y.length;T++)C.push(...ny(y[T],S,d.align)),T<y.length-1&&C.push(v("\u251C","\u253C","\u2524"));return C.push(v("\u2514","\u2534","\u2518")),C.join(`
|
|
366
|
-
`)+`
|
|
367
|
-
|
|
368
|
-
`}}});let c=a.parse(o);return S_(c,s,y_(t.mathRenderer),i).replace(/\n{3,}/g,`
|
|
369
|
-
|
|
370
|
-
`).trimEnd()}function g_(){let e=process.env.TERM_PROGRAM??"";return["iTerm.app","WezTerm","Hyper","vscode"].some(r=>e.includes(r))}function w_(e){let t=[],r="",n=0;for(;n<e.length;){let o=C_(e,n);if(o){r+=o.segment,n=o.end;continue}let s=R_(e,n);if(s){r+=s.segment,n=s.end;continue}let i=b_(e,n);if(i){let l=`ARIAMATHTOKEN${t.length}X`;t.push({marker:l,original:i.segment,kind:i.kind}),r+=l,n=i.end;continue}let a=A_(e,n);if(a){let l=`ARIAMATHTOKEN${t.length}X`;t.push({marker:l,original:a.segment,kind:"bare_math"}),r+=l,n=a.end;continue}let c=Ld(e,n);if(c){let l=`ARIAMATHTOKEN${t.length}X`;t.push({marker:l,original:c.segment,kind:"latex_command"}),r+=l,n=c.end;continue}r+=e[n],n+=1}return{content:r,placeholders:t}}function y_(e){if(e)return e;let t=(process.env.ARIA_MARKDOWN_MATH_RENDERER??"").trim().toLowerCase();return t==="katex"||t==="fast"?t:"fast"}function x_(e){if(e)return e;let t=(process.env.ARIA_MARKDOWN_COLOR_WORD_MODE??"").trim().toLowerCase();return t==="always"||t==="never"||t==="auto"?t:"auto"}function S_(e,t,r,n){let o=x(),s=e;for(let i of t){let a=v_(i,r),c=a.style?ln.hex(o.colors.info)(a.text):a.text;c=py(c,n),s=s.split(i.marker).join(c)}return s}function b_(e,t){if(e[t]!=="$"||ta(e,t))return null;if(e[t+1]==="$"&&!ta(e,t+1)){let o=E_(e,"$$",t+2);return o===-1||!e.slice(t+2,o).trim()?null:{segment:e.slice(t,o+2),end:o+2,kind:"display_math"}}let r=T_(e,t+1);if(r===-1)return null;let n=e.slice(t+1,r);return __(n)?{segment:e.slice(t,r+1),end:r+1,kind:"inline_math"}:null}function T_(e,t){for(let r=t;r<e.length;r+=1){let n=e[r];if(n===`
|
|
371
|
-
`)return-1;if(n==="$"&&!ta(e,r))return r}return-1}function E_(e,t,r){let n=e.indexOf(t,r);for(;n!==-1;){if(!ta(e,n))return n;n=e.indexOf(t,n+t.length)}return-1}function ta(e,t){let r=0;for(let n=t-1;n>=0&&e[n]==="\\";n-=1)r+=1;return r%2===1}function __(e){let t=e.trim();return t?/\\/.test(t)||/[{}^_=<>+\-*/]/.test(t)?!0:!/\s/.test(t):!1}function C_(e,t){if(!eC(e,t))return null;let n=e.slice(t).match(/^(```+|~~~+)[^\n]*\n/);if(!n)return null;let o=n[1],s=t+n[0].length;for(;s<e.length;){let i=e.indexOf(`
|
|
372
|
-
`,s),a=i===-1?e.length:i;if(e.slice(s,a).trim().startsWith(o)){let l=i===-1?e.length:i+1;return{segment:e.slice(t,l),end:l}}if(i===-1)break;s=i+1}return{segment:e.slice(t),end:e.length}}function R_(e,t){if(e[t]!=="`")return null;let r=1;for(;e[t+r]==="`";)r+=1;let n="`".repeat(r),o=e.indexOf(n,t+r);return o===-1?null:{segment:e.slice(t,o+r),end:o+r}}function Ld(e,t){if(e[t]!=="\\")return null;let r=e[t+1];if(!r)return null;if(/[A-Za-z]/.test(r)){let n=t+2;for(;n<e.length&&/[A-Za-z]/.test(e[n]);)n+=1;return{segment:e.slice(t,n),end:n}}return/[,:;!{}%$#&_ ]/.test(r)?{segment:e.slice(t,t+2),end:t+2}:null}function A_(e,t){if(e[t]!=="\\")return null;let r=Ld(e,t);if(!r)return null;let n=r.segment.slice(1);if(!I_(n))return null;let o=r.end;for(;o<e.length;){let i=e[o];if(i===`
|
|
373
|
-
`||i==="$")break;if(i==="\\"){let a=Ld(e,o);if(!a)break;o=a.end;continue}if(/[A-Za-z0-9^_{}()[\]+\-*/=.,:; ]/.test(i)){o+=1;continue}break}let s=e.slice(t,o).trimEnd();return s.length<=r.segment.length?null:{segment:s,end:t+s.length}}function I_(e){return e?Dc[e]||Pf.has(e)?!0:["frac","binom","sqrt","left","right","text"].includes(e):!1}var Dc={alpha:"\u03B1",beta:"\u03B2",gamma:"\u03B3",delta:"\u03B4",epsilon:"\u03B5",varepsilon:"\u03B5",zeta:"\u03B6",eta:"\u03B7",theta:"\u03B8",vartheta:"\u03D1",iota:"\u03B9",kappa:"\u03BA",lambda:"\u03BB",mu:"\u03BC",nu:"\u03BD",xi:"\u03BE",pi:"\u03C0",varpi:"\u03D6",rho:"\u03C1",varrho:"\u03F1",sigma:"\u03C3",varsigma:"\u03C2",tau:"\u03C4",upsilon:"\u03C5",phi:"\u03D5",varphi:"\u03C6",chi:"\u03C7",psi:"\u03C8",omega:"\u03C9",Gamma:"\u0393",Delta:"\u0394",Theta:"\u0398",Lambda:"\u039B",Xi:"\u039E",Pi:"\u03A0",Sigma:"\u03A3",Upsilon:"\u03A5",Phi:"\u03A6",Psi:"\u03A8",Omega:"\u03A9",int:"\u222B",sum:"\u2211",prod:"\u220F",infty:"\u221E",partial:"\u2202",nabla:"\u2207",times:"\xD7",cdot:"\xB7",pm:"\xB1",mp:"\u2213",leq:"\u2264",geq:"\u2265",neq:"\u2260",approx:"\u2248",sim:"\u223C",to:"\u2192",leftarrow:"\u2190",rightarrow:"\u2192",leftrightarrow:"\u2194",mapsto:"\u21A6",in:"\u2208",notin:"\u2209",subset:"\u2282",subseteq:"\u2286",supset:"\u2283",supseteq:"\u2287",cup:"\u222A",cap:"\u2229",forall:"\u2200",exists:"\u2203",neg:"\xAC",lnot:"\xAC",land:"\u2227",lor:"\u2228"},Pf=new Set(["sin","cos","tan","cot","sec","csc","log","ln","exp","max","min","lim"]),iy={0:"\u2070",1:"\xB9",2:"\xB2",3:"\xB3",4:"\u2074",5:"\u2075",6:"\u2076",7:"\u2077",8:"\u2078",9:"\u2079","+":"\u207A","-":"\u207B","=":"\u207C","(":"\u207D",")":"\u207E",n:"\u207F",i:"\u2071",a:"\u1D43",b:"\u1D47",c:"\u1D9C",d:"\u1D48",e:"\u1D49",f:"\u1DA0",g:"\u1D4D",h:"\u02B0",j:"\u02B2",k:"\u1D4F",l:"\u02E1",m:"\u1D50",o:"\u1D52",p:"\u1D56",r:"\u02B3",s:"\u02E2",t:"\u1D57",u:"\u1D58",v:"\u1D5B",w:"\u02B7",x:"\u02E3",y:"\u02B8",z:"\u1DBB"},ay={0:"\u2080",1:"\u2081",2:"\u2082",3:"\u2083",4:"\u2084",5:"\u2085",6:"\u2086",7:"\u2087",8:"\u2088",9:"\u2089","+":"\u208A","-":"\u208B","=":"\u208C","(":"\u208D",")":"\u208E",a:"\u2090",e:"\u2091",h:"\u2095",i:"\u1D62",j:"\u2C7C",k:"\u2096",l:"\u2097",m:"\u2098",n:"\u2099",o:"\u2092",p:"\u209A",r:"\u1D63",s:"\u209B",t:"\u209C",u:"\u1D64",v:"\u1D65",x:"\u2093"};function v_(e,t){if(t==="katex"){let o=e.kind==="display_math",s=e.kind==="inline_math"?e.original.slice(1,-1):e.kind==="display_math"?e.original.slice(2,-2):e.original,i=D_(s,o);if(i)return{text:i,style:!0}}if(e.kind==="inline_math"){let o=e.original.slice(1,-1);return{text:Pt(o),style:!0}}if(e.kind==="display_math"){let o=e.original.slice(2,-2);return{text:F_(o),style:!0}}if(e.kind==="bare_math")return{text:Pt(e.original),style:!0};let r=U_(e.original),n=r!==e.original;return{text:r,style:n}}var Jw=new Map,k_=new Set(["math","semantics","mrow","mstyle"]),M_={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" ",ThinSpace:" ",NegativeThinSpace:"",MediumSpace:" ",ApplyFunction:"",InvisibleTimes:"\xB7",InvisibleComma:","};function D_(e,t){let r=e.trim();if(!r)return"";let n=`${t?"display":"inline"}:${r}`,o=Jw.get(n);if(o!==void 0)return o;try{let s=f_.renderToString(r,{displayMode:t,throwOnError:!1,strict:"ignore",output:"mathml"}),i=L_(s,t);if(i!=null&&i.trim().length>0){let a=i.trimEnd();return Jw.set(n,a),a}}catch{}return null}function L_(e,t){let r=e.match(/<math[\s\S]*<\/math>/i);if(!r)return null;let n=r[0].replace(/<annotation[\s\S]*?<\/annotation>/gi,""),o=N_(n);if(!o)return null;if(t){let s=j_(o);if(s?.name==="mfrac"){let i=dn(s),a=i[0]?jt(i[0],!1).trim():"",c=i[1]?jt(i[1],!1).trim():"";return dy(a,c)}}return jt(o,t)}function N_(e){let t={name:"__root__",attrs:{},children:[]},r=[t],n=/<!--[\s\S]*?-->|<[^>]+>|[^<]+/g,o;for(;(o=n.exec(e))!==null;){let i=o[0];if(!i||i.startsWith("<!--")||i.startsWith("<?"))continue;if(i.startsWith("</")){r.length>1&&r.pop();continue}if(i.startsWith("<")){let d=i.endsWith("/>"),f=i.slice(1,i.length-(d?2:1)).trim();if(!f)continue;let u=f.match(/^([^\s/>]+)/);if(!u)continue;let h=u[1];if(!h)continue;let y=h.replace(/^.*:/,"").toLowerCase(),S=O_(f.slice(h.length)),R={name:y,attrs:S,children:[]},I=r[r.length-1];I&&I.children.push(R),d||r.push(R);continue}let a=cy(i),c=ly(a);if(!c)continue;let l=r[r.length-1];l&&l.children.push(c)}return dn(t).find(i=>i.name==="math")??null}function O_(e){let t={},r=/([A-Za-z_:][A-Za-z0-9:._-]*)\s*=\s*("([^"]*)"|'([^']*)')/g,n;for(;(n=r.exec(e))!==null;){let o=n[1];if(!o)continue;let s=n[3]??n[4]??"",i=o.replace(/^.*:/,"").toLowerCase();t[i]=cy(s)}return t}function cy(e){return e.replace(/&#x([0-9a-fA-F]+);/g,(t,r)=>{let n=Number.parseInt(r,16);return Number.isFinite(n)?String.fromCodePoint(n):""}).replace(/&#([0-9]+);/g,(t,r)=>{let n=Number.parseInt(r,10);return Number.isFinite(n)?String.fromCodePoint(n):""}).replace(/&([A-Za-z][A-Za-z0-9]+);/g,(t,r)=>M_[r]??r)}function ly(e){return e.replace(/[\u200b\u2061\u2062\u2063\u2064]/g,"").replace(/\s+/g," ").trim()}function j_(e){let t=e;for(;k_.has(t.name);){let r=dn(t);if(r.length!==1)break;t=r[0]}return t}function dn(e){return e.children.filter(t=>typeof t!="string")}function Nf(e){let t="";for(let r of e.children)typeof r=="string"?t+=r:t+=Nf(r);return ly(t)}function jt(e,t){switch(e.name){case"math":case"semantics":case"mrow":case"mstyle":case"mpadded":case"mphantom":case"none":return vc(e,t);case"mi":case"mn":case"mtext":return Nf(e);case"mo":{let r=Nf(e);return P_(r)}case"mspace":return" ";case"mfrac":{let r=dn(e),n=r[0]?jt(r[0],!1).trim():"",o=r[1]?jt(r[1],!1).trim():"";return`${n}\u2044${o}`.trim()}case"msup":{let r=dn(e),n=r[0]?jt(r[0],!1):"",o=r[1]?jt(r[1],!1):"";return`${n}${Qw(o)}`}case"msub":{let r=dn(e),n=r[0]?jt(r[0],!1):"",o=r[1]?jt(r[1],!1):"";return`${n}${Zw(o)}`}case"msubsup":{let r=dn(e),n=r[0]?jt(r[0],!1):"",o=r[1]?jt(r[1],!1):"",s=r[2]?jt(r[2],!1):"";return`${n}${Zw(o)}${Qw(s)}`}case"msqrt":{let r=vc(e,!1);return r?`\u221A(${r})`:"\u221A"}case"mroot":{let r=dn(e),n=r[0]?jt(r[0],!1):"",o=r[1]?jt(r[1],!1):"";return o?`${o}\u221A(${n})`:`\u221A(${n})`}case"mfenced":{let r=e.attrs.open??"(",n=e.attrs.close??")",o=vc(e,!1);return`${r}${o}${n}`}case"mtable":{let n=dn(e).filter(o=>o.name==="mtr").map(o=>jt(o,t).trim()).filter(o=>o.length>0);return n.length===0?"":t?n.join(`
|
|
374
|
-
`):`[${n.join("; ")}]`}case"mtr":return dn(e).filter(n=>n.name==="mtd").map(n=>jt(n,t).trim()).filter(n=>n.length>0).join(" ");case"mtd":return vc(e,t);case"annotation":return"";default:return vc(e,t)}}function vc(e,t){let r=e.children.map(n=>typeof n=="string"?n:jt(n,t));return $_(r.join(""))}function P_(e){return e?e==="\u2212"?"-":e:""}function $_(e){return e.replace(/[\u200b\u2061\u2062\u2063\u2064]/g,"").replace(/([∫∑∏])([A-Za-z0-9α-ωΑ-Ω])/g,"$1 $2").replace(/([\u00B2\u00B3\u00B9\u2070-\u209F])([A-Za-zα-ωΑ-Ω])/g,"$1 $2").replace(/([)\]])([A-Za-zα-ωΑ-Ω])/g,"$1 $2").replace(/\s*([+\-−=≈≠≤≥<>×÷·∪∩])\s*/g," $1 ").replace(/\s*,\s*/g,", ").replace(/\s*;\s*/g,"; ").replace(/\s*:\s*/g,": ").replace(/\(\s+/g,"(").replace(/\s+\)/g,")").replace(/\s+/g," ").trim()}function Qw(e){let t=e.replace(/\s+/g,"");return t?Nd(`{${t}}`,iy,"^"):""}function Zw(e){let t=e.replace(/\s+/g,"");return t?Nd(`{${t}}`,ay,"_"):""}function F_(e){let t=e.trim();if(!t)return"";let r=z_(t,"frac");if(r){let n=Pt(r.arg1).trim(),o=Pt(r.arg2).trim();return dy(n,o)}return t.split(`
|
|
375
|
-
`).map(n=>Pt(n)).join(`
|
|
376
|
-
`)}function Pt(e){let t=e.trim();return t=B_(t),t=t.replace(/\\left\s*/g,"").replace(/\\right\s*/g,""),t=kc(t,"text",r=>Pt(r)),t=kc(t,"sqrt",r=>`\u221A(${Pt(r)})`),t=kc(t,"mathrm",r=>Pt(r)),t=kc(t,"mathbf",r=>Pt(r)),t=kc(t,"mathit",r=>Pt(r)),t=Mc(t,"textcolor",(r,n)=>ry(r,Pt(n))),t=Mc(t,"color",(r,n)=>ry(r,Pt(n))),t=Mc(t,"colorbox",(r,n)=>Q_(r,Pt(n))),t=Mc(t,"frac",(r,n)=>`${Pt(r)}\u2044${Pt(n)}`),t=Mc(t,"binom",(r,n)=>`C(${Pt(r)}, ${Pt(n)})`),t=H_(t),t=W_(t),t=q_(t),t=G_(t),t=t.replace(/\s{2,}/g," ").trim(),t}function U_(e){if(!e.startsWith("\\"))return e;let t=e.slice(1);return e==="\\,"||e==="\\;"||e==="\\:"?" ":e==="\\!"?"":e==="\\ "?" ":e==="\\{"?"{":e==="\\}"?"}":e==="\\%"?"%":e==="\\$"?"$":e==="\\#"?"#":e==="\\_"?"_":e==="\\&"?"&":Dc[t]?Dc[t]:Pf.has(t)?t:e}function B_(e){return e.replace(/\\,/g," ").replace(/\\;/g," ").replace(/\\:/g," ").replace(/\\!/g,"").replace(/\\qquad/g," ").replace(/\\quad/g," ").replace(/~+/g," ").replace(/\\ /g," ")}function H_(e){let t=e,r=Object.keys(Dc).sort((n,o)=>o.length-n.length);for(let n of r){let o=Dc[n],s=new RegExp(`\\\\${ty(n)}\\b`,"g");t=t.replace(s,o)}for(let n of Pf){let o=new RegExp(`\\\\${ty(n)}\\b`,"g");t=t.replace(o,n)}return t}function W_(e){return e.replace(/\\([{}%$#&_])/g,"$1")}function q_(e){let t="__ARIA_ESCAPED_LBRACE__",r="__ARIA_ESCAPED_RBRACE__";return e.replace(/\\\{/g,t).replace(/\\\}/g,r).replace(/[{}]/g,"").replaceAll(t,"{").replaceAll(r,"}")}function G_(e){let t=e;return t=t.replace(/([A-Za-z0-9α-ωΑ-Ω)\]])\^(\{[^{}]*\}|.)/g,(r,n,o)=>`${n}${Nd(o,iy,"^")}`),t=t.replace(/([A-Za-z0-9α-ωΑ-Ω)\]])_(\{[^{}]*\}|.)/g,(r,n,o)=>`${n}${Nd(o,ay,"_")}`),t}function Nd(e,t,r){let n=X_(e);if(!n)return"";let o="";for(let s of n){let i=t[s];if(!i)return`${r}(${n})`;o+=i}return o}function X_(e){return e.startsWith("{")&&e.endsWith("}")?e.slice(1,-1):e}function kc(e,t,r){let n="",o=0,s=`\\${t}`;for(;o<e.length;){if($f(e,s,o)){let i=Lc(e,o+s.length);if(i){n+=r(i.value),o=i.end;continue}}n+=e[o],o+=1}return n}function Mc(e,t,r){let n="",o=0,s=`\\${t}`;for(;o<e.length;){if($f(e,s,o)){let i=Lc(e,o+s.length);if(i){let a=Lc(e,i.end);if(a){n+=r(i.value,a.value),o=a.end;continue}}}n+=e[o],o+=1}return n}function z_(e,t){let r=`\\${t}`,n=Of(e,0);if(!$f(e,r,n))return null;let o=Lc(e,n+r.length);if(!o)return null;let s=Lc(e,o.end);return!s||Of(e,s.end)!==e.length?null:{arg1:o.value,arg2:s.value}}function Lc(e,t){let r=Of(e,t);if(r>=e.length)return null;if(e[r]==="{"){let n=K_(e,r);return n===-1?null:{value:e.slice(r+1,n),end:n+1}}if(e[r]==="\\"){let n=Ld(e,r);if(n)return{value:n.segment,end:n.end}}return{value:e[r],end:r+1}}function $f(e,t,r){if(!e.startsWith(t,r))return!1;let n=e[r+t.length];return!n||!/[A-Za-z]/.test(n)}function Of(e,t){let r=t;for(;r<e.length&&/\s/.test(e[r]);)r+=1;return r}function K_(e,t){let r=0;for(let n=t;n<e.length;n+=1){let o=e[n];if(o==="{"&&!ta(e,n)&&(r+=1),o==="}"&&!ta(e,n)&&(r-=1,r===0))return n}return-1}function dy(e,t){let r=Math.max(jf(e),jf(t),1),n="\u2500".repeat(r),o=ey(e,r),s=ey(t,r);return`${o}
|
|
377
|
-
${n}
|
|
378
|
-
${s}`}function jf(e){return Array.from(e).length}function ey(e,t){let r=jf(e);if(r>=t)return e;let n=Math.floor((t-r)/2),o=t-r-n;return`${" ".repeat(n)}${e}${" ".repeat(o)}`}function ty(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function uy(e){let t={},r=sy;for(let[n,o]of Object.entries(r)){let s=n.toLowerCase(),[i,a,c]=o;if(i===0&&a===0&&c===0){t[s]=l=>e.blackBright(l);continue}t[s]=l=>e.rgb(i,a,c)(l)}return t.gray&&!t.grey&&(t.grey=t.gray),t.grey&&!t.gray&&(t.gray=t.grey),t}var my=uy(ln),fy=uy(new oy({level:3})),V_=Object.keys(my).sort((e,t)=>t.length-e.length),Y_=new RegExp(`\\b(${V_.join("|")})\\b`,"gi"),J_=new oy({level:3});function ry(e,t){let r=e.trim().toLowerCase(),n=fy[r];return n?n(t):t}function Q_(e,t){let r=e.trim().toLowerCase(),o=sy[r];if(o){let[s,i,a]=o;return J_.bgRgb(s,i,a)(t)}return t}function py(e,t="auto"){if(t==="never")return e;let r=t==="always"?fy:my;return e.replace(Y_,n=>{let o=r[n.toLowerCase()];return o?o(n):n})}function Z_(e){let t=e.split(`
|
|
379
|
-
`);return t.map((r,n)=>{let o=r.match(/^(\d+)\.\s+(.+)$/);if(!o)return r;let s=n===0||!t[n-1].trim(),i=n===t.length-1||!t[n+1].trim();return!s||!i?r:`${o[1]}\\. ${o[2]}`}).join(`
|
|
380
|
-
`)}function eC(e,t){return t===0||e[t-1]===`
|
|
381
|
-
`}function tC(e){let t=e.split(`
|
|
382
|
-
`),r=[];for(let n=0;n<t.length;n+=1){let o=t[n]??"",s=t[n+1]??"";if(rC(o)&&nC(s)){let i=n;for(;i<t.length&&oC(t[i]??"");)r.push(sC(t[i])),i+=1;n=i-1;continue}r.push(o)}return r.join(`
|
|
383
|
-
`)}function rC(e){let t=e.trim();if(!t.includes("|")||/^[-:|\s]+$/.test(t))return!1;let r=hy(t);return r.length>=2&&r.some(n=>n.length>0)}function nC(e){let t=hy(e.trim());return t.length>=2&&t.every(r=>/^:?-{3,}:?$/.test(r))}function oC(e){let t=e.trim();return t.length>0&&t.includes("|")}function hy(e){let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(r=>r.trim())}function sC(e){return e.replace(/\|/g,"\\|")}var gy=/\x1b\[[0-9;]*m|\x1b\]8;;[^\x07]*\x07/g;function wy(e){return e.replace(gy,"")}function Nc(e){return wy(e).length}function iC(e,t,r){let o=e.reduce((l,d)=>l+d,0);if(o<=t)return;let s=aC(r,t,3),i=t,a=i/o;for(let l=0;l<e.length;l++)e[l]=Math.max(s[l]??3,Math.floor(e[l]*a));let c=e.reduce((l,d)=>l+d,0);for(;c>i;){let l=0;for(let d=1;d<e.length;d++)e[d]>e[l]&&(l=d);if(e[l]<=(s[l]??3))break;e[l]--,c--}for(;c>i;){let l=0;for(let d=1;d<e.length;d++)e[d]>e[l]&&(l=d);if(e[l]<=3)break;e[l]--,c--}}function aC(e,t,r){let n=e.map(s=>Math.max(s,r)),o=n.reduce((s,i)=>s+i,0);for(;o>t;){let s=-1;for(let i=0;i<n.length;i++)n[i]<=r||(s===-1||n[i]>n[s])&&(s=i);if(s===-1)break;n[s]--,o--}return n}function cC(e){let n=3,o=3;for(let s of e){let i=xy(s);n=Math.max(n,Nc(i)),o=Math.max(o,lC(i))}return Math.min(Math.max(3,o),24)}function lC(e){return wy(e).split(/\s+/).reduce((t,r)=>Math.max(t,r.length),0)}function yy(e,t){let r=xy(e);if(t<=0||!r)return[r||""];if(r.includes(`
|
|
384
|
-
`)){let f=[];for(let u of r.split(`
|
|
385
|
-
`))f.push(...yy(u,t));return f}if(Nc(r)<=t)return[r];let n=[],o=0,s=new RegExp(gy.source,"g"),i;for(;(i=s.exec(r))!==null;)i.index>o&&n.push({ansi:!1,value:r.slice(o,i.index)}),n.push({ansi:!0,value:i[0]}),o=s.lastIndex;o<r.length&&n.push({ansi:!1,value:r.slice(o)});let a=[],c="",l=0,d=f=>{for(let u=0;u<f.length;u+=t)c&&l>0&&a.push(c),c=f.slice(u,u+t),l=c.length};for(let f of n){if(f.ansi){c+=f.value;continue}let u=f.value.split(/(\s+)/);for(let h of u){if(!h)continue;let y=h.length,S=!h.trim();S&&l===0||(l+y<=t?(c+=h,l+=y):l===0?d(h):S?(a.push(c),c="",l=0):(a.push(c),c="",l=0,y>t?d(h):(c=h,l=y)))}}return(c||a.length===0)&&a.push(c),a}function xy(e){return e.replace(/\s*\n+\s*/g," ").replace(/\(\s+/g,"(").replace(/\s+\)/g,")").replace(/\[\s+/g,"[").replace(/\s+\]/g,"]").replace(/[ \t]{2,}/g," ").trim()}function dC(e,t,r){let n=Nc(e);if(n>=t)return e;let o=t-n;if(r==="right")return" ".repeat(o)+e;if(r==="center"){let s=Math.floor(o/2);return" ".repeat(s)+e+" ".repeat(o-s)}return e+" ".repeat(o)}function ny(e,t,r){let n=e.map((i,a)=>yy(i,t[a])),o=Math.max(...n.map(i=>i.length),1),s=[];for(let i=0;i<o;i++){let a=n.map((c,l)=>dC(c[i]??"",t[l],r[l]??null));s.push("\u2502 "+a.join(" \u2502 ")+" \u2502")}return s}import{jsx as So,jsxs as Gd,Fragment as NC}from"react/jsx-runtime";import{useCallback as Xd,useEffect as Ly,useRef as zd,useState as bo}from"react";import{Box as jc,Text as Kd}from"ink";import{jsx as hC}from"react/jsx-runtime";import{useEffect as gC,useRef as Wf,useState as wC}from"react";import{Text as yC,useInput as xC}from"ink";import na from"chalk";import{useState as fC}from"react";import{useRef as Sy}from"react";var by=2e3;function Oc(e,t,r){let n=Sy(0),o=Sy(void 0);return()=>{let s=Date.now();s-n.current<=by&&o.current?(o.current&&(clearTimeout(o.current),o.current=void 0),t(),e(!1)):(r?.(),e(!0),o.current=setTimeout(()=>e(!1),by)),n.current=s}}import uC from"string-width";var ra=class e{measuredText;selection;offset;constructor(t,r=0,n=0){this.measuredText=t,this.selection=n,this.offset=Math.max(0,Math.min(this.measuredText.text.length,r))}static fromText(t,r,n=0,o=0){return new e(new Od(t,r-1),n,o)}render(t,r,n){let{line:o,column:s}=this.getPosition();return this.measuredText.getWrappedText().map((i,a,c)=>{let l=i;if(r&&a===c.length-1){let d=Math.max(0,i.length-6);l=r.repeat(d)+i.slice(d)}return o!=a?l.trimEnd():l.slice(0,s)+n(l[s]||t)+l.trimEnd().slice(s+1)}).join(`
|
|
386
|
-
`)}left(){return new e(this.measuredText,this.offset-1)}right(){return new e(this.measuredText,this.offset+1)}up(){let{line:t,column:r}=this.getPosition();if(t==0)return new e(this.measuredText,0,0);let n=this.getOffset({line:t-1,column:r});return new e(this.measuredText,n,0)}down(){let{line:t,column:r}=this.getPosition();if(t>=this.measuredText.lineCount-1)return new e(this.measuredText,this.text.length,0);let n=this.getOffset({line:t+1,column:r});return new e(this.measuredText,n,0)}startOfLine(){let{line:t}=this.getPosition();return new e(this.measuredText,this.getOffset({line:t,column:0}),0)}endOfLine(){let{line:t}=this.getPosition(),r=this.measuredText.getLineLength(t),n=this.getOffset({line:t,column:r});return new e(this.measuredText,n,0)}nextWord(){let t=this;for(;t.isOverWordChar()&&!t.isAtEnd();)t=t.right();for(;!t.isOverWordChar()&&!t.isAtEnd();)t=t.right();return t}prevWord(){let t=this;for(t.left().isOverWordChar()||(t=t.left());!t.isOverWordChar()&&!t.isAtStart();)t=t.left();if(t.isOverWordChar())for(;t.left().isOverWordChar()&&!t.isAtStart();)t=t.left();return t}modifyText(t,r=""){let n=this.offset,o=t.offset,s=this.text.slice(0,n)+r+this.text.slice(o);return e.fromText(s,this.columns,n+r.length)}insert(t){return this.modifyText(this,t)}del(){return this.isAtEnd()?this:this.modifyText(this.right())}backspace(){if(this.isAtStart())return this;let t=this.offset,n=this.left().offset,o=this.text.slice(0,n)+this.text.slice(t);return e.fromText(o,this.columns,n)}deleteToLineStart(){return this.startOfLine().modifyText(this)}deleteToLineEnd(){return this.text[this.offset]===`
|
|
387
|
-
`?this.modifyText(this.right()):this.modifyText(this.endOfLine())}deleteWordBefore(){return this.isAtStart()?this:this.prevWord().modifyText(this)}deleteWordAfter(){return this.isAtEnd()?this:this.modifyText(this.nextWord())}isOverWordChar(){let t=this.text[this.offset]??"";return/\w/.test(t)}equals(t){return this.offset===t.offset&&this.measuredText==t.measuredText}isAtStart(){return this.offset==0}isAtEnd(){return this.offset==this.text.length}get text(){return this.measuredText.text}get columns(){return this.measuredText.columns+1}getPosition(){return this.measuredText.getPositionFromOffset(this.offset)}getOffset(t){return this.measuredText.getOffsetFromPosition(t)}},Rs=class{text;startOffset;isPrecededByNewline;endsWithNewline;constructor(t,r,n,o=!1){this.text=t,this.startOffset=r,this.isPrecededByNewline=n,this.endsWithNewline=o}equals(t){return this.text===t.text&&this.startOffset===t.startOffset}get length(){return this.text.length+(this.endsWithNewline?1:0)}},Od=class{text;columns;wrappedLines;constructor(t,r){this.text=t,this.columns=r,this.wrappedLines=this.measureWrappedText()}measureWrappedText(){if(this.text.length===0)return[new Rs("",0,!0,!1)];let t=[],r=0;for(;r<this.text.length;){let n=r,o=r===0||this.text[r-1]===`
|
|
388
|
-
`,s=0,i=r,a=-1;for(;i<this.text.length;){let c=this.text[i];if(c===`
|
|
389
|
-
`){t.push(new Rs(this.text.slice(n,i),n,o,!0)),r=i+1;break}let l=this.text.codePointAt(i),d=String.fromCodePoint(l),f=uC(d);if(s+f>this.columns){let u;a>=n&&a+1<i?u=a+1:i>n?u=i:u=i+d.length,t.push(new Rs(this.text.slice(n,u),n,o,!1)),r=u;break}(c===" "||c===" ")&&(a=i),s+=f,i+=d.length}i>=this.text.length&&r===n&&(t.push(new Rs(this.text.slice(n),n,o,!1)),r=this.text.length)}return this.text.length>0&&this.text[this.text.length-1]===`
|
|
390
|
-
`&&t.push(new Rs("",this.text.length,!0,!1)),t}getWrappedText(){return this.wrappedLines.map(t=>t.isPrecededByNewline?t.text:t.text.trimStart())}getLine(t){return this.wrappedLines[Math.max(0,Math.min(t,this.wrappedLines.length-1))]}getOffsetFromPosition(t){let r=this.getLine(t.line),n=r.startOffset+t.column;if(r.text.length===0&&r.endsWithNewline)return r.startOffset;let o=r.startOffset+r.text.length,s=r.endsWithNewline?o+1:o;return Math.min(n,s)}getLineLength(t){let r=this.getLine(t),n=this.getLine(t+1);return n.equals(r)?this.text.length-r.startOffset:n.startOffset-r.startOffset-1}getPositionFromOffset(t){let r=this.wrappedLines;for(let o=0;o<r.length;o++){let s=r[o],i=r[o+1];if(t>=s.startOffset&&(!i||t<i.startOffset)){let a=s.isPrecededByNewline?0:s.text.length-s.text.trimStart().length,c=Math.max(0,Math.min(t-s.startOffset-a,s.text.length));return{line:o,column:c}}}let n=r.length-1;return{line:n,column:this.wrappedLines[n].text.length}}get lineCount(){return this.wrappedLines.length}equals(t){return this.text===t.text&&this.columns===t.columns}};import{execSync as Ff}from"child_process";import{readFileSync as mC}from"fs";var Uf="/tmp/claude_cli_latest_screenshot.png",Ty="No image found in clipboard. Use Cmd + Ctrl + Shift + 4 to copy a screenshot to clipboard.";function Bf(){if(process.platform!=="darwin")return null;try{Ff("osascript -e 'the clipboard as \xABclass PNGf\xBB'",{stdio:"ignore"}),Ff(`osascript -e 'set png_data to (the clipboard as \xABclass PNGf\xBB)' -e 'set fp to open for access POSIX file "${Uf}" with write permission' -e 'write png_data to fp' -e 'close access fp'`,{stdio:"ignore"});let t=mC(Uf).toString("base64");return Ff(`rm -f "${Uf}"`,{stdio:"ignore"}),t}catch{return null}}function de(e,t){return t.escape||e==="\x1B"}var pC="[Image pasted]";function Ey(e){return function(t){return(new Map(e).get(t)??(()=>{}))(t)}}function Hf({value:e,onChange:t,onSubmit:r,onExit:n,onExitMessage:o,onMessage:s,onHistoryUp:i,onHistoryDown:a,onHistoryReset:c,onDoubleEscape:l,mask:d="",multiline:f=!1,cursorChar:u,invert:h,columns:y,onImagePaste:S,disableCursorMovementForUpDownKeys:R=!1,externalOffset:I,onOffsetChange:v}){let C=I,T=v,E=ra.fromText(e,y,C),[_,P]=fC(null);function Z(){_&&(clearTimeout(_),P(null),s?.(!1))}let nt=Oc(Y=>{Z(),o?.(Y,"Ctrl-C")},()=>n?.(),()=>{e&&(t(""),c?.())}),ze=Oc(Y=>{Z(),s?.(!!e&&Y,"Press Escape again to clear")},()=>{l?.()||e&&t("")});function le(){return ra.fromText("",y,0)}let N=Oc(Y=>o?.(Y,"Ctrl-D"),()=>n?.());function A(){return Z(),E.text===""?(N(),E):E.del()}function $(){let Y=Bf();return Y===null?(process.platform!=="darwin"||(s?.(!0,Ty),Z(),P(setTimeout(()=>{s?.(!1)},4e3))),E):(S?.(Y),E.insert(pC))}let he=Ey([["a",()=>E.startOfLine()],["b",()=>E.left()],["c",nt],["d",A],["e",()=>E.endOfLine()],["f",()=>E.right()],["h",()=>(Z(),E.backspace())],["k",()=>E.deleteToLineEnd()],["l",()=>le()],["n",()=>We()],["p",()=>_e()],["u",()=>E.deleteToLineStart()],["v",$],["w",()=>E.deleteWordBefore()]]),ae=Ey([["b",()=>E.prevWord()],["f",()=>E.nextWord()],["d",()=>E.deleteWordAfter()]]);function oe(Y){if(f&&E.offset>0&&E.text[E.offset-1]==="\\")return E.backspace().insert(`
|
|
391
|
-
`);if(Y.meta||Y.shift)return E.insert(`
|
|
392
|
-
`);r?.(e)}function _e(){if(R)return i?.(),E;let Y=E.up();return Y.equals(E)&&i?.(),Y}function We(){if(R)return a?.(),E;let Y=E.down();return Y.equals(E)&&a?.(),Y}function dt(Y,se){if(se.shift&&se.delete||Y==="\x1B[3;2~"){let z=E.deleteWordBefore();E.equals(z)||(T(z.offset),E.text!==z.text&&t(z.text));return}if(se.meta&&(se.backspace||se.delete||Y==="\x7F")){let z=E.deleteWordBefore();E.equals(z)||(T(z.offset),E.text!==z.text&&t(z.text));return}if(se.backspace||se.delete||Y==="\b"||Y==="\x7F"||Y==="\b"){let z=E.backspace();E.equals(z)||(T(z.offset),E.text!==z.text&&t(z.text));return}let $e=sr(Y,se)(Y);$e&&(E.equals($e)||(T($e.offset),E.text!==$e.text&&t($e.text)))}function sr(Y,se){if(de(Y,se))return ze;if(se.backspace||se.delete)return Z(),()=>E.backspace();switch(!0){case(se.leftArrow&&(se.ctrl||se.meta||se.fn)):return()=>E.prevWord();case(se.rightArrow&&(se.ctrl||se.meta||se.fn)):return()=>E.nextWord();case se.ctrl:return he;case se.home:return()=>E.startOfLine();case se.end:return()=>E.endOfLine();case se.pageDown:return()=>E.endOfLine();case se.pageUp:return()=>E.startOfLine();case se.return:return()=>oe(se);case se.meta:return ae;case se.tab:return()=>{};case se.upArrow:return _e;case se.downArrow:return We;case se.leftArrow:return()=>E.left();case se.rightArrow:return()=>E.right()}return function($e){switch(!0){case($e=="\x1B[H"||$e=="\x1B[1~"):return E.startOfLine();case($e=="\x1B[F"||$e=="\x1B[4~"):return E.endOfLine();case($e==="\b"||$e==="\x7F"||$e==="\b"):return Z(),E.backspace();default:return E.insert($e.replace(/\r/g,`
|
|
393
|
-
`))}}}return{onInput:dt,renderedValue:E.render(u,d,h),offset:C,setOffset:T}}D();var _y="[200~",jd="\x1B[201~",Pd="[201~";function SC(e){let t=e,r=!1,n=!1;if(t.startsWith(_y)&&(t=t.slice(_y.length),r=!0),t.endsWith(jd))t=t.slice(0,-jd.length),n=!0;else if(t.endsWith(Pd))t=t.slice(0,-Pd.length),n=!0;else{let o=t.indexOf(jd);if(o!==-1)t=t.slice(0,o)+t.slice(o+jd.length),n=!0;else{let s=t.indexOf(Pd);s!==-1&&(t=t.slice(0,s)+t.slice(s+Pd.length),n=!0)}}return{text:t,hasBracketStart:r,hasBracketEnd:n}}function oa({value:e,placeholder:t="",focus:r=!0,mask:n,multiline:o=!1,highlightPastedText:s=!1,showCursor:i=!0,onChange:a,onSubmit:c,onExit:l,onHistoryUp:d,onHistoryDown:f,onExitMessage:u,onMessage:h,onHistoryReset:y,onDoubleEscape:S,columns:R,onImagePaste:I,onPaste:v,isDimmed:C=!1,disableCursorMovementForUpDownKeys:T=!1,cursorOffset:E,onChangeCursorOffset:_}){let[nt,ze]=wC(0),le=R??process.stdout.columns??80,N=E??nt,A=_??ze,{onInput:$,renderedValue:he}=Hf({value:e,onChange:a,onSubmit:c,onExit:l,onExitMessage:u,onMessage:h,onHistoryReset:y,onHistoryUp:d,onHistoryDown:f,onDoubleEscape:S,focus:r,mask:n,multiline:o,cursorChar:i?" ":"",highlightPastedText:s,invert:na.inverse,themeText:fe=>na.hex(x().colors.text)(fe),columns:le,onImagePaste:I,disableCursorMovementForUpDownKeys:T,externalOffset:N,onOffsetChange:A}),ae=Wf([]),oe=Wf(null),_e=Wf(!1),We=()=>{oe.current&&(clearTimeout(oe.current),oe.current=null)},dt=()=>{let fe=ae.current.join("");ae.current=[],We(),_e.current=!1,!(!fe||!v)&&Promise.resolve().then(()=>v(fe))},sr=()=>{We(),oe.current=setTimeout(()=>{dt()},100)},Y=fe=>{ae.current.push(fe),sr()},se=()=>oe.current!==null||_e.current;gC(()=>()=>{We(),ae.current=[],_e.current=!1},[]);let $e=fe=>!!(fe.return||fe.escape||fe.tab||fe.ctrl||fe.meta||fe.upArrow||fe.downArrow||fe.leftArrow||fe.rightArrow||fe.pageUp||fe.pageDown||fe.backspace||fe.delete);xC((fe,Be)=>{let{text:Ye,hasBracketStart:Xt,hasBracketEnd:Ke}=SC(fe);if(Xt&&v&&(_e.current=!0),_e.current&&v){if($e(Be)){dt();return}Ye&&Y(Ye),Ke&&dt();return}if(Ke&&se()){Ye&&Y(Ye),dt();return}if(Be.backspace||Be.delete||Ye==="\b"||Ye==="\x7F"||Ye==="\b"){$(Ye,{...Be,backspace:!0});return}if(!(!Ye&&!$e(Be))){if(v&&se()&&$e(Be)){dt();return}if(v&&(Ye.length>800||se())){Y(Ye);return}$(Ye,Be)}},{isActive:r});let je=t?na.hex(x().colors.textMuted)(t):void 0;i&&r&&(je=t.length>0?na.inverse(t[0])+na.hex(x().colors.textMuted)(t.slice(1)):na.inverse(" "));let Qe=e.length==0&&t;return hC(yC,{wrap:"truncate-end",dimColor:C,children:Qe?je:he})}import{useSyncExternalStore as bC}from"react";function Ry(){return{columns:process.stdout.columns||80,rows:process.stdout.rows||24}}var $d=Ry(),Fd=!1,Ud=new Set;function qf(){let e=Ry();return e.columns===$d.columns&&e.rows===$d.rows?!1:($d=e,!0)}function TC(){for(let e of Ud)e()}function Ay(){qf()&&TC()}function EC(){Fd||(process.stdout.on("resize",Ay),Fd=!0)}function _C(){!Fd||Ud.size!==0||(process.stdout.off("resize",Ay),Fd=!1)}function CC(e){return Ud.add(e),qf(),EC(),()=>{Ud.delete(e),_C()}}function Cy(){return qf(),$d}function ft(){return bC(CC,Cy,Cy)}qd();var OC="image/png",Ny="[Image pasted]";function jC(e){return`data:${OC};base64,${e}`}function zf({userName:e,value:t,onChange:r,onSubmit:n,onTrigger:o,onExit:s,isStreaming:i=!1,isDisabled:a=!1,focus:c,history:l=[],onSaveInput:d,onDoubleEscape:f}){let{columns:u}=ft(),h=u-6,y=As()&&Dy(),[S,R]=bo(-1),[I,v]=bo(""),[C,T]=bo(l),[E,_]=bo(t.length),[P,Z]=bo(null),[nt,ze]=bo(null),[le,N]=bo({show:!1}),[A,$]=bo({show:!1}),he=zd(t),ae=zd(E),oe=zd(P),_e=zd(nt);he.current=t,ae.current=E,oe.current=P,_e.current=nt,Ly(()=>{l.length>0&&T(z=>{let je=[...z];for(let Qe of l)je.includes(Qe)||je.push(Qe);return je.slice(0,100)})},[l]),Ly(()=>{C.length===0&&S>=0&&R(-1)},[C.length]);let We=Xd(()=>{if(C.length===0)return;S===-1&&v(t);let z=Math.min(S+1,C.length-1);if(R(z),z>=0&&z<C.length){let je=C[z];r(je),_(je.length)}},[C,S,t,r]),dt=Xd(()=>{if(S<0)return;let z=S-1;if(R(z),z===-1)r(I),_(I.length);else if(z>=0&&z<C.length){let je=C[z];r(je),_(je.length)}else z>=C.length&&(R(-1),r(I),_(I.length))},[S,I,C,r]),sr=Xd(z=>{R(-1);let je=z==="/"||z.startsWith("/")&&!t.startsWith("/"),Qe=z.match(/@([\p{L}\p{N}_-]*)$/u),fe=t.match(/@[\p{L}\p{N}_-]*$/u),Be=Qe&&!fe;r(z),je?o("command",z.slice(1)):Be&&o("mention",Qe[1])},[t,r,o]),Y=Xd(z=>{let je=he.current,Qe=oe.current,fe=_e.current,Be=z!==je&&(Qe!==null||fe!==null)?je:z;if(Qe){let Zr=`[Pasted text +${(Qe.match(/\r\n|\r|\n/g)||[]).length} lines] `;Be.includes(Zr)&&(Be=Be.replaceAll(Zr,Qe))}fe&&Be.includes(Ny)&&(Be=Be.replaceAll(Ny,""));let Ye=fe!==null,Xt=Be.trim();if(!(!Xt&&!Ye)){if(Ye){let Ke=jC(fe);Be=Xt?`${Be}
|
|
394
|
-
|
|
395
|
-
${Ke}`:Ke}Xt&&(d?.(Xt),T(Ke=>[Xt,...Ke.filter(Zr=>Zr!==Xt)].slice(0,100))),he.current="",ae.current=0,oe.current=null,_e.current=null,r(""),Z(null),ze(null),$({show:!1}),n(Be)}},[n,d,r]);function se(z){_e.current=z,ze(z),$({show:!0,text:"Image attached. Press Enter to send."})}function $e(z){let je=he.current,Qe=ae.current,fe=z.replace(/\r/g,`
|
|
396
|
-
`),Ye=`[Pasted text +${(fe.match(/\r\n|\r|\n/g)||[]).length} lines] `,Xt=je.slice(0,Qe)+Ye+je.slice(Qe);he.current=Xt,r(Xt);let Ke=Qe+Ye.length;ae.current=Ke,_(Qe+Ye.length),oe.current=fe,Z(fe)}return Gd(jc,{flexDirection:"column",children:[So(jc,{borderStyle:"single",borderLeft:!1,borderRight:!1,borderDimColor:!0,width:"100%",children:Gd(jc,{children:[So(kf,{userName:e}),So(oa,{multiline:!0,value:t,onChange:sr,onSubmit:Y,onHistoryUp:We,onHistoryDown:dt,onHistoryReset:()=>R(-1),onDoubleEscape:f,onExit:s,onExitMessage:(z,je)=>N({show:z,key:je}),onMessage:(z,je)=>$({show:z,text:je}),onImagePaste:se,onPaste:$e,columns:h,isDimmed:a,focus:c!==!1,showCursor:!0,cursorOffset:E,onChangeCursorOffset:_})]})}),So(jc,{flexDirection:"row",justifyContent:"space-between",paddingX:2,children:So(jc,{justifyContent:"flex-start",gap:1,children:le.show?Gd(Kd,{dimColor:!0,children:["Press ",le.key," again to exit"]}):A.show?So(Kd,{dimColor:!0,children:A.text}):Gd(NC,{children:[So(Kd,{dimColor:!0,children:"/ for commands \xB7 @ to mention \xB7 esc to undo"}),So(Kd,{dimColor:!0,children:y?"shift + \u23CE for newline":"\\\u23CE for newline"})]})})})]})}import{jsx as JG}from"react/jsx-runtime";import{Static as ZG,Box as eX}from"ink";import{jsx as Hr,jsxs as Wr}from"react/jsx-runtime";import*as JS from"react";import{Box as zo,Text as wn}from"ink";import nI from"wrap-ansi";D();import{jsxs as Kf,jsx as Pc}from"react/jsx-runtime";import{Box as $c,Text as Vf}from"ink";var PC=process.platform==="darwin"?"\u23FA":"\u25CF";function Vd({param:{text:e},userName:t,columns:r,addMargin:n=!1,showPrefix:o=!0}){let s=x(),i=t||"User",a=Math.max(r-4,20);return Kf($c,{flexDirection:"column",marginTop:n?1:0,width:"100%",children:[o&&Pc($c,{flexDirection:"row",children:Kf(Vf,{bold:!0,color:s.colors.primary,children:["\u{1F984} ",i]})}),Kf($c,{flexDirection:"row",width:"100%",marginTop:o?1:0,children:[Pc($c,{minWidth:2,children:Pc(Vf,{color:s.colors.primary,children:PC})}),Pc($c,{flexShrink:1,width:a,children:Pc(Vf,{wrap:"wrap",children:e?St(e,{width:a}):""})})]})]})}D();import{jsx as Jf,jsxs as HC}from"react/jsx-runtime";import{Box as WC,Text as Qf}from"ink";var $C=/data:image\/[a-zA-Z0-9.+-]+;base64,[a-zA-Z0-9+/=\n\r]+/g;function FC(){return(process.env.TERM_PROGRAM??"").toLowerCase()==="iterm.app"}function UC(){return FC()&&!!process.stdout?.isTTY}function Yd(e){let r=e.trim().match(/^data:(image\/[a-zA-Z0-9.+-]+);base64,([a-zA-Z0-9+/=\n\r]+)$/);if(!r)return null;let[,n,o]=r;if(!n||!o)return null;try{let s=o.replace(/\s+/g,""),i=Buffer.from(s,"base64");return i.length===0?null:{buffer:i,mimeType:n}}catch{return null}}function Oy(e){let t=Yd(e);return t?BC(t.buffer,t.mimeType):null}function BC(e,t="image/png"){if(!UC())return null;let r=e.toString("base64");return`\x1B]1337;File=inline=1;preserveAspectRatio=1;size=${e.length};type=${t}:${r}\x07`}function Yf(e){let t=[],r=0;for(let n of e.matchAll($C)){let o=n.index??0,s=n[0]??"";s&&(o>r&&t.push({type:"text",text:e.slice(r,o)}),t.push({type:"image",dataUri:s}),r=o+s.length)}return r<e.length&&t.push({type:"text",text:e.slice(r)}),t.length>0?t:[{type:"text",text:e}]}function jy({dataUri:e,userName:t,showPrefix:r=!0}){let n=x(),s=`\u{1F984} ${t||"User"}`,i=Oy(e);return HC(WC,{flexDirection:"column",width:"100%",children:[r&&Jf(Qf,{bold:!0,color:n.colors.primary,children:s}),i?Jf(Qf,{children:i}):Jf(Qf,{dimColor:!0,children:"[Image attachment]"})]})}D();import{jsxs as ia,jsx as Bc}from"react/jsx-runtime";import{useRef as VC}from"react";import{Box as Jd,Text as Hc}from"ink";var Fc=[{present:"Accomplishing",past:"Accomplished"},{present:"Actioning",past:"Actioned"},{present:"Actualizing",past:"Actualized"},{present:"Absquatulating",past:"Absquatulated"},{present:"Bamboozling",past:"Bamboozled"},{present:"Brewing",past:"Brewed"},{present:"Calculating",past:"Calculated"},{present:"Cerebrating",past:"Cerebrated"},{present:"Churning",past:"Churned"},{present:"Coalescing",past:"Coalesced"},{present:"Cogitating",past:"Cogitated"},{present:"Confabulating",past:"Confabulated"},{present:"Conjuring",past:"Conjured"},{present:"Considering",past:"Considered"},{present:"Contemplating",past:"Contemplated"},{present:"Cooking",past:"Cooked"},{present:"Crafting",past:"Crafted"},{present:"Crunching",past:"Crunched"},{present:"Deliberating",past:"Deliberated"},{present:"Determining",past:"Determined"},{present:"Dillydallying",past:"Dillydallied"},{present:"Discombobulating",past:"Discombobulated"},{present:"Doing",past:"Done"},{present:"Effecting",past:"Effected"},{present:"Finagling",past:"Finagled"},{present:"Fizzwizzling",past:"Fizzwizzled"},{present:"Flummoxing",past:"Flummoxed"},{present:"Forging",past:"Forged"},{present:"Frobnicating",past:"Frobnicated"},{present:"Gallivanting",past:"Gallivanted"},{present:"Generating",past:"Generated"},{present:"Hatching",past:"Hatched"},{present:"Herding",past:"Herded"},{present:"Honking",past:"Honked"},{present:"Hornswoggling",past:"Hornswoggled"},{present:"Hustling",past:"Hustled"},{present:"Ideating",past:"Ideated"},{present:"Inferring",past:"Inferred"},{present:"Lollygagging",past:"Lollygagged"},{present:"Manifesting",past:"Manifested"},{present:"Marinating",past:"Marinated"},{present:"Moseying",past:"Moseyed"},{present:"Mulling",past:"Mulled"},{present:"Mustering",past:"Mustered"},{present:"Musing",past:"Mused"},{present:"Noodling",past:"Noodled"},{present:"Perambulating",past:"Perambulated"},{present:"Percolating",past:"Percolated"},{present:"Pondering",past:"Pondered"},{present:"Prestidigitating",past:"Prestidigitated"},{present:"Processing",past:"Processed"},{present:"Puttering",past:"Puttered"},{present:"Reflecting",past:"Reflected"},{present:"Reticulating",past:"Reticulated"},{present:"Ruminating",past:"Ruminated"},{present:"Schlepping",past:"Schlepped"},{present:"Shenaniganing",past:"Shenaniganed"},{present:"Shucking",past:"Shucked"},{present:"Skedaddling",past:"Skedaddled"},{present:"Snozzwangling",past:"Snozzwangled"},{present:"Simmering",past:"Simmered"},{present:"Smooshing",past:"Smooshed"},{present:"Spinning",past:"Spun"},{present:"Stewing",past:"Stewed"},{present:"Synthesizing",past:"Synthesized"},{present:"Thaumaturging",past:"Thaumaturged"},{present:"Thinking",past:"Thought"},{present:"Transmogrifying",past:"Transmogrified"},{present:"Transmuting",past:"Transmuted"},{present:"Vibing",past:"Vibed"},{present:"Weaving",past:"Woven"},{present:"Working",past:"Worked"},{present:"Chrysalizing",past:"Chrysalized"},{present:"Fluttering",past:"Fluttered"},{present:"Harmonizing",past:"Harmonized"},{present:"Metamorphosing",past:"Metamorphosed"},{present:"Orchestrating",past:"Orchestrated"},{present:"Catching",past:"Caught"},{present:"Evolving",past:"Evolved"},{present:"Mega Evolving",past:"Mega Evolved"},{present:"Summoning",past:"Summoned"},{present:"Charging",past:"Charged"},{present:"Fusing",past:"Fused"},{present:"Kamehameha-ing",past:"Kamehameha'd"},{present:"Powering Up",past:"Powered Up"},{present:"Spirit Bombing",past:"Spirit Bombed"},{present:"Transcending",past:"Transcended"},{present:"Gear Shifting",past:"Gear Shifted"},{present:"Gum-Gum-ing",past:"Gum-Gum'd"},{present:"Navigating",past:"Navigated"},{present:"Plundering",past:"Plundered"},{present:"Sailing",past:"Sailed"},{present:"Setting Sail",past:"Set Sail"},{present:"Catapulting",past:"Catapulted"},{present:"Mobilizing",past:"Mobilized"},{present:"Newtypeing",past:"Newtyped"},{present:"Trans-Am-ing",past:"Trans-Am'd"},{present:"Assembling",past:"Assembled"},{present:"Hulking",past:"Hulked"},{present:"Snapping",past:"Snapped"},{present:"Vibranium-ing",past:"Vibranium'd"},{present:"Alchemizing",past:"Alchemized"},{present:"Assimilating",past:"Assimilated"},{present:"Astral Projecting",past:"Astral Projected"},{present:"Beaming",past:"Beamed"},{present:"Cloaking",past:"Cloaked"},{present:"Dematerializing",past:"Dematerialized"},{present:"Enchanting",past:"Enchanted"},{present:"Engaging",past:"Engaged"},{present:"Ensorcelling",past:"Ensorcelled"},{present:"Holographing",past:"Holographed"},{present:"Hyperjumping",past:"Hyperjumped"},{present:"Morphing",past:"Morphed"},{present:"Nebulizing",past:"Nebulized"},{present:"Phasing",past:"Phased"},{present:"Quantum Leaping",past:"Quantum Leapt"},{present:"Shapeshifting",past:"Shapeshifted"},{present:"Spellcasting",past:"Spellcast"},{present:"Teleporting",past:"Teleported"},{present:"Terraforming",past:"Terraformed"},{present:"Time Traveling",past:"Time Traveled"},{present:"Time Warping",past:"Time Warped"},{present:"Transforming",past:"Transformed"},{present:"Warping",past:"Warped"},{present:"Wormholing",past:"Wormholed"},{present:"Bepuzzling",past:"Bepuzzled"},{present:"Blorbulating",past:"Blorbulated"},{present:"Cattywampusing",past:"Cattywampused"},{present:"Cromulating",past:"Cromulated"},{present:"Discorbuflating",past:"Discorbuflated"},{present:"Embiggenating",past:"Embiggenated"},{present:"Flibbertigibbeting",past:"Flibbertigibbeted"},{present:"Flonkifying",past:"Flonkified"},{present:"Frobscottling",past:"Frobscottled"},{present:"Glorpifying",past:"Glorpified"},{present:"Gobsmacking",past:"Gobsmacked"},{present:"Higgledy-piggling",past:"Higgledy-piggled"},{present:"Jiggery-pokerying",past:"Jiggery-pokeried"},{present:"Kerfuffling",past:"Kerfuffled"},{present:"Malarkeying",past:"Malarkeyed"},{present:"Mumblewumbling",past:"Mumblewumbled"},{present:"Phantasmagoring",past:"Phantasmagored"},{present:"Quibberflasting",past:"Quibberflasted"},{present:"Quorfluxing",past:"Quorfluxed"},{present:"Rigmaroling",past:"Rigmaroled"},{present:"Skullduggering",past:"Skullduggered"},{present:"Snizzleworfing",past:"Snizzleworfed"},{present:"Snorfulating",past:"Snorfulated"},{present:"Spatchcocking",past:"Spatchcocked"},{present:"Tomfoolering",past:"Tomfoolered"},{present:"Wibbling",past:"Wibbled"},{present:"Wumboozling",past:"Wumboozled"},{present:"Yoinking",past:"Yoinked"},{present:"Zippledorping",past:"Zippledorped"},{present:"Zorbinating",past:"Zorbinated"},{present:"Awakening",past:"Awakened"},{present:"Bankai-ing",past:"Bankai'd"},{present:"Rasengan-ing",past:"Rasengan'd"},{present:"Unleashing",past:"Unleashed"}];function Nr(){return Fc[Math.floor(Math.random()*Fc.length)]??Fc[0]}var qC=new Set(["file","web"]),GC={ls:"list",rm:"remove",cp:"copy",mv:"move",cd:"change_dir",mkdir:"make_dir"},XC=new Set(["arion","delegation","knowledge","patch","processes","process","quest","skill","stdin","tool","user","worker"]);function $y(e,t=!1){let r=GC[e]??e,n=r.split("_").filter(s=>!qC.has(s.toLowerCase()));if(n.length===0)return t?Py(r.toLowerCase()):Uc(r);let o=t?zC(n):-1;return n.map((s,i)=>i===o?Py(s.toLowerCase()):Uc(s.toLowerCase())).join(" ")}function zC(e){let t=e.findIndex(r=>!XC.has(r.toLowerCase()));return t>=0?t:0}var KC=new Set(["glob","grep","run","get","set","put","stop","spin","forget"]);function Py(e){return e.endsWith("e")&&e.length>2?Uc(e.slice(0,-1))+"ing":KC.has(e)?Uc(e)+e[e.length-1]+"ing":Uc(e)+"ing"}function Uc(e){return e.charAt(0).toUpperCase()+e.slice(1)}var YC=1/0;function JC(e){if(e==null)return"";if(e<=0)return"< 1s";if(e<60)return`${e}s`;let t=Math.floor(e/60),r=e%60;return`${t}m ${r}s`}function Zf({content:e,expanded:t=!1,durationSeconds:r,verb:n,arionName:o,arionEmoji:s,arionColor:i,isLive:a=!1,maxLines:c=YC}){let l=x(),d=VC(Nr()),f=n||d.current.present,u=n||d.current.past,h=JC(r);return ia(Jd,{flexDirection:"column",children:[!!(s&&o)&&Bc(Jd,{marginBottom:1,children:ia(Hc,{color:i||l.colors.textMuted,bold:!0,children:[s," ",o]})}),ia(Hc,{color:l.colors.textMuted,children:["\u273B"," ",a?f:u,a?"\u2026":h?` for ${h}`:""]}),a&&e&&Bc(Fy,{content:e,maxLines:c,isLive:!0}),!a&&t&&e&&Bc(Fy,{content:e,maxLines:c,isLive:!1})]})}function Fy({content:e,maxLines:t,isLive:r}){let n=x(),{columns:o}=ft(),s=Math.max(o-4,20),a=St(e,{width:s,mode:r?"streaming":"final"}).split(`
|
|
397
|
-
`),c=a.slice(0,t),l=a.length-c.length;return ia(Jd,{children:[Bc(Hc,{color:n.colors.textMuted,children:" \u23BF "}),ia(Jd,{flexDirection:"column",width:s,children:[c.map((d,f)=>Bc(Hc,{color:n.colors.textMuted,wrap:"wrap",children:d},f)),l>0&&ia(Hc,{color:n.colors.textMuted,children:["\u2026"," (+",l," line",l!==1?"s":"",")"]})]})]})}import{jsx as Br,jsxs as tI}from"react/jsx-runtime";import{Box as KS,Text as Fp}from"ink";D();import{jsx as tp,jsxs as Qd}from"react/jsx-runtime";import{Box as Wy,Text as Zd}from"ink";import{jsx as Hy}from"react/jsx-runtime";import{Box as ZC,Text as eR}from"ink";import tR from"react";import{useEffect as Uy,useRef as QC}from"react";function By(e,t){let r=QC(e);Uy(()=>{r.current=e},[e]),Uy(()=>{function n(){r.current()}let o=setInterval(n,t);return()=>clearInterval(o)},[t])}D();var rR=process.platform==="darwin"?"\u23FA":"\u25CF";function ep({isError:e=!1,isUnresolved:t=!1,shouldAnimate:r=!0,...n}){let o=t||n.isQueued||!1,[s,i]=tR.useState(!0);By(()=>{r&&i(c=>!c)},600);let a=o?x().colors.textMuted:e?x().colors.error:x().colors.success;return Hy(ZC,{minWidth:2,children:Hy(eR,{color:a,children:s?rR:" "})})}function nR(e){return e.split(/,\s*(?=\w+:\s)/).map(r=>r.replace(/^\w+:\s*/,"")).join(" ")}function oR(e,t){let r=e.replace(/\s+/g," ").trim();return r.length<=t?r:r.slice(0,t-1)+"\u2026"}function qy({displayName:e,args:t,status:r,durationMs:n,verbose:o}){let s=x(),i=r==="pending"||r==="running",a=r==="error",c;if(t)if(typeof t=="string")if(o)c=t;else{let l=nR(t),d=process.stdout.columns||80,f=2+e.length+1,u=Math.max(20,d-f);c=oR(l,u)}else c=t;return Qd(Wy,{flexDirection:"row",children:[tp(ep,{shouldAnimate:i,isError:a,isUnresolved:i}),tp(Zd,{bold:!0,children:e}),c!=null&&(typeof c=="string"?Qd(Zd,{children:[" ",c]}):Qd(Wy,{children:[tp(Zd,{children:" "}),c]})),o&&n!=null?Qd(Zd,{color:s.colors.textMuted,children:[" \xB7 ",(n/1e3).toFixed(1),"s"]}):null]})}import{jsxs as Gy,jsx as Xy}from"react/jsx-runtime";import{Box as rp,Text as sR}from"ink";function np({children:e}){return Xy(rp,{flexDirection:"column",children:Gy(rp,{flexDirection:"row",children:[Gy(sR,{children:[" ","\u23BF"," "]}),Xy(rp,{flexDirection:"column",flexGrow:1,children:e})]})})}import{Fragment as iR,jsx as op}from"react/jsx-runtime";import{Box as aR,Text as cR}from"ink";function zy({durationMs:e,usage:t}){let r=[];return t&&t.totalTokens>0&&(r.push(`+${kd(t.totalTokens)} tokens`),r.push(Rf(t.estimatedCost))),e&&r.push(`${(e/1e3).toFixed(1)}s`),r.length===0?op(iR,{}):op(aR,{children:op(cR,{dimColor:!0,children:r.join(" \xB7 ")})})}import{jsx as lR}from"react/jsx-runtime";import Vy from"react";var Ky=process.stdout.columns||80,Yy=Vy.createContext({terminalWidth:Ky,contentWidth:Math.max(Ky-5,1)});function eu({value:e,children:t}){return lR(Yy.Provider,{value:e,children:t})}function To(){return Vy.useContext(Yy)}import{jsx as Wc,jsxs as cp}from"react/jsx-runtime";import{Text as ca}from"ink";D();import{jsx as dR,jsxs as uR}from"react/jsx-runtime";import{Text as Jy}from"ink";function k(){return uR(Jy,{children:["\xA0\xA0","\u23BF"," \xA0",dR(Jy,{color:x().colors.error,children:"No (tell ARIA what to do differently)"})]})}import{jsx as ap,jsxs as hR}from"react/jsx-runtime";import{Box as gR,Text as wR}from"ink";D();import{jsx as tu}from"react/jsx-runtime";import{Box as sp,Text as mR}from"ink";import fR from"chalk";function Ut(e){return e.length>80?e.slice(0,80)+"\u2026":e}function $n(e){return e.split(`
|
|
398
|
-
`).map(Ut).join(`
|
|
399
|
-
`)}var ip=3;function pR(e,t){let r=e.split(`
|
|
400
|
-
`);return r.length<=ip?r.map(Ut).join(`
|
|
401
|
-
`):[...r.slice(0,ip).map(Ut),fR.grey(`\u2026 +${t-ip} lines`)].join(`
|
|
402
|
-
`)}function aa({content:e,lines:t,verbose:r,isError:n}){return tu(sp,{justifyContent:"space-between",width:"100%",children:tu(sp,{flexDirection:"row",children:tu(sp,{flexDirection:"column",children:tu(mR,{color:n?x().colors.error:void 0,children:r?e.trim():pR(e.trim(),t)})})})})}D();function yR({content:e,verbose:t}){let{stdout:r,stdoutLines:n,stderr:o,stderrLines:s}=e;return hR(gR,{flexDirection:"column",children:[r!==""?ap(aa,{content:r,lines:n,verbose:t}):null,o!==""?ap(aa,{content:o,lines:s,verbose:t,isError:!0}):null,r===""&&o===""?ap(wR,{color:x().colors.textMuted,children:"(No content)"}):null]})}var Qy=yR;var Eo={displayName(){return"Bash"},renderInput(e){if(typeof e.command=="string"){let t=e.command;if(t.includes(`"$(cat <<'EOF'`)){let r=t.match(/^(.*?)"?\$\(cat <<'EOF'\n([\s\S]*?)\n\s*EOF\n\s*\)"(.*)$/);if(r&&r[1]&&r[2])return`${r[1].trim()} "${r[2].trim()}"${(r[3]||"").trim()}`}return t}if(typeof e.program=="string"){let t=Array.isArray(e.args)?" "+e.args.join(" "):"";return`${e.program}${t}`}if(typeof e.input=="string"){let t=e.input.length>40?e.input.slice(0,40)+"\u2026":e.input;return`stdin \u2192 ${e.pid??""} "${t}"`}return e.signal!=null?`kill ${e.signal} ${e.pid}`:typeof e.timeoutMs=="number"||typeof e.timeout=="number"?`wait ${e.pid}`:e.pid!=null&&Object.keys(e).length<=2?`pid ${e.pid}`:""},renderRejection(){return Wc(k,{})},renderOutput(e,{verbose:t}){if(e==null)return Wc(ca,{children:"(No content)"});if(typeof e=="string")return Wc(ca,{children:e||"(No content)"});let r=e;if(typeof r.stdout=="string"||typeof r.stderr=="string"){let n={stdout:r.stdout??"",stdoutLines:typeof r.stdoutLines=="number"?r.stdoutLines:(r.stdout??"").split(`
|
|
403
|
-
`).length,stderr:r.stderr??"",stderrLines:typeof r.stderrLines=="number"?r.stderrLines:(r.stderr??"").split(`
|
|
404
|
-
`).length};return Wc(Qy,{content:n,verbose:t})}return r.pid!=null?cp(ca,{children:["pid: ",String(r.pid)]}):r.signal!=null||r.killed!=null?cp(ca,{children:[r.killed?"Killed":"Signal sent",r.signal?` (${String(r.signal)})`:""]}):r.exitCode!=null?cp(ca,{children:["Exit code: ",String(r.exitCode)]}):Wc(ca,{children:JSON.stringify(e)})}};import{jsx as _o,jsxs as AR}from"react/jsx-runtime";import{Box as tx,Text as zc}from"ink";import{relative as up}from"path";import{jsx as la,Fragment as ex,jsxs as Gc}from"react/jsx-runtime";import{Box as dp,Text as Xc}from"ink";D();import{jsx as Cr,jsxs as Or}from"react/jsx-runtime";import{Box as qc,Text as pr}from"ink";import*as Zy from"react";import{useMemo as xR}from"react";function SR(e,t){let r=[],n="";for(let o of e)[...n].length<t?n+=o:(r.push(n),n=o);return n&&r.push(n),r}function bR({patch:e,dim:t,width:r,overrideTheme:n}){return xR(()=>TR(e.lines,e.oldStart,r,t,n),[e.lines,e.oldStart,r,t,n]).map((s,i)=>Cr(qc,{children:s},i))}function TR(e,t,r,n,o){let s=x(),i=ER(e.map(l=>l.startsWith("+")?{code:"+"+l.slice(1),i:0,type:"add"}:l.startsWith("-")?{code:"-"+l.slice(1),i:0,type:"remove"}:{code:l,i:0,type:"nochange"}),t),c=Math.max(...i.map(({i:l})=>l)).toString().length;return i.flatMap(({type:l,code:d,i:f})=>SR(d,r-c).map((h,y)=>{let S=`${l}-${f}-${y}`;switch(l){case"add":return Or(pr,{children:[Cr(lp,{i:y===0?f:void 0,width:c}),Cr(pr,{color:o?s.colors.text:void 0,backgroundColor:n?s.colors.diffAddedDimmed:s.colors.diffAdded,dimColor:n,children:h})]},S);case"remove":return Or(pr,{children:[Cr(lp,{i:y===0?f:void 0,width:c}),Cr(pr,{color:o?s.colors.text:void 0,backgroundColor:n?s.colors.diffRemovedDimmed:s.colors.diffRemoved,dimColor:n,children:h})]},S);case"nochange":return Or(pr,{children:[Cr(lp,{i:y===0?f:void 0,width:c}),Cr(pr,{color:o?s.colors.text:void 0,dimColor:n,children:h})]},S)}}))}function lp({i:e,width:t}){return Or(pr,{color:x().colors.textMuted,children:[e!==void 0?e.toString().padStart(t):" ".repeat(t)," "]})}function ER(e,t){let r=t,n=[],o=[...e];for(;o.length>0;){let{code:s,type:i}=o.shift(),a={code:s,type:i,i:r};switch(i){case"nochange":r++,n.push(a);break;case"add":r++,n.push(a);break;case"remove":{n.push(a);let c=0;for(;o[0]?.type==="remove";){r++;let{code:l,type:d}=o.shift(),f={code:l,type:d,i:r};n.push(f),c++}r-=c;break}}}return n}function _R(e){let t=[];for(let r of e.lines)switch(r.type){case"added":t.push("+"+r.content);break;case"removed":t.push("-"+r.content);break;default:t.push(" "+r.content);break}return{lines:t,oldStart:e.oldStart}}function Is({diff:e,width:t=60,showHeader:r=!0,maxLines:n=50,dim:o=!1}){let s=x(),i=e.hunks.reduce((d,f)=>d+f.lines.length,0),a=i>n,c=a?Math.floor(n/e.hunks.length):void 0,l=a?e.hunks.reduce((d,f)=>d+Math.min(f.lines.length,c),0):i;return Or(qc,{flexDirection:"column",width:t,children:[r&&Or(qc,{marginBottom:1,children:[Cr(pr,{bold:!0,children:e.filePath}),Or(pr,{color:s.colors.textMuted,children:[" ","(",Or(pr,{color:s.colors.success,children:["+",e.additions]})," / ",Or(pr,{color:s.colors.error,children:["-",e.deletions]}),")"]})]}),e.hunks.map((d,f)=>{let u=c&&d.lines.length>c?{...d,lines:d.lines.slice(0,c)}:d,h=_R(u);return Or(Zy.Fragment,{children:[f>0&&Cr(qc,{paddingY:0,children:Cr(pr,{color:s.colors.textMuted,children:"..."})}),Cr(bR,{patch:h,dim:o,width:t})]},f)}),a&&Cr(qc,{marginTop:1,children:Or(pr,{color:s.colors.textMuted,children:["... ",i-l," more lines"]})})]})}D();function CR(e,t){return e.flatMap((r,n)=>n?[t(n),r]:[r])}function RR(e,t){let r=[],n=e.oldStart,o=e.newStart,s=0,i=0;for(let a of e.lines){let c=a.slice(1);a.startsWith("+")?(r.push({type:"added",content:c,newLineNo:o++}),s++):a.startsWith("-")?(r.push({type:"removed",content:c,oldLineNo:n++}),i++):r.push({type:"unchanged",content:c,oldLineNo:n++,newLineNo:o++})}return{filePath:t,hunks:[{oldStart:e.oldStart,oldLines:e.oldLines,newStart:e.newStart,newLines:e.newLines,lines:r}],additions:s,deletions:i}}function ru({filePath:e,structuredPatch:t,verbose:r}){let{columns:n}=ft(),o=t.reduce((l,d)=>l+d.lines.filter(f=>f.startsWith("+")).length,0),s=t.reduce((l,d)=>l+d.lines.filter(f=>f.startsWith("-")).length,0),i=t.flatMap(l=>l.lines.filter(d=>d.startsWith("+")||d.startsWith("-"))),c=r||i.length<=2;return Gc(dp,{flexDirection:"column",children:[Gc(Xc,{children:[o>0?Gc(ex,{children:["Added ",la(Xc,{bold:!0,children:o})," ",o>1?"lines":"line"]}):null,o>0&&s>0?", ":null,s>0?Gc(ex,{children:["removed ",la(Xc,{bold:!0,children:s})," ",s>1?"lines":"line"]}):null,c?null:Gc(Xc,{color:x().colors.textMuted,children:[" (",i.length," diff lines)"]})]}),c&&CR(t.map(l=>la(dp,{flexDirection:"column",paddingLeft:5,children:la(Is,{diff:RR(l,e),showHeader:!1,dim:!1,width:n-12})},l.newStart)),l=>la(dp,{paddingLeft:5,children:la(Xc,{color:x().colors.textMuted,children:"..."})},`ellipsis-${l}`))]})}var nu={displayName(e){let t=e?.old_string??e?.oldText??"",r=e?.new_string??e?.newText??"";return t===""?"Create":r===""?"Delete":"Edit"},renderInput(e,{verbose:t}){let r=String(e?.file_path??e?.path??"");if(r)return t?r:up(process.cwd(),r);if(typeof e?.patch=="string"){let o=[...e.patch.matchAll(/^\*\*\*\s+(?:Update|Add|Delete|Rename)\s+(.+)$/gm)].map(s=>s[1]??"").filter(Boolean).slice(0,3);return o.length>0?o.map(s=>t?s:up(process.cwd(),s)).join(", "):"patch"}return""},renderOutput(e,{verbose:t}){if(e==null)return _o(zc,{children:"(No content)"});if(typeof e=="string")return _o(zc,{children:e});let r=e;if(r.structuredPatch)return _o(ru,{filePath:r.filePath??r.path,structuredPatch:r.structuredPatch,verbose:t});if(r.path!=null){let n=t?String(r.path):up(process.cwd(),String(r.path)),o=r.replacements!=null?Number(r.replacements):void 0,s=o!=null?` (${o} replacement${o!==1?"s":""})`:"";return _o(tx,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:_o(tx,{flexDirection:"row",children:AR(zc,{children:["Edited ",_o(zc,{bold:!0,children:n}),s]})})})}return _o(zc,{children:JSON.stringify(e)})},renderRejection(){return _o(k,{})}};import{jsx as Bt,jsxs as ou}from"react/jsx-runtime";import{Box as Rr,Text as Kc}from"ink";import{extname as nx,relative as DR}from"path";import{jsx as IR}from"react/jsx-runtime";import{highlight as rx,supportsLanguage as vR}from"cli-highlight";import{Text as kR}from"ink";import{useMemo as MR}from"react";function jr({code:e,language:t}){let r=MR(()=>{try{return t&&vR(t)?rx(e,{language:t}):rx(e,{language:"markdown"})}catch{return e}},[e,t]);return IR(kR,{children:r})}D();var da=3,mp={displayName(){return"Read"},renderInput(e,{verbose:t}){let r=String(e?.file_path??e?.path??""),{file_path:n,path:o,...s}=e;return[["path",t?r:DR(process.cwd(),r)],...Object.entries(s).filter(([a])=>a!=="file_path"&&a!=="path")].map(([a,c])=>`${a}: ${JSON.stringify(c)}`).join(", ")},renderOutput(e,{verbose:t},r){let n=r??{},o=String(n.file_path??n.path??""),s=o?nx(o).slice(1):"";if(e==null)return Bt(Rr,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Bt(Rr,{flexDirection:"row",children:Bt(Kc,{children:"(No content)"})})});if(typeof e=="string"){let a=e||"(No content)",c=a.split(`
|
|
405
|
-
`);return Bt(Rr,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Bt(Rr,{flexDirection:"row",children:ou(Rr,{flexDirection:"column",children:[Bt(jr,{code:t?a:$n(c.slice(0,da).filter(l=>l.trim()!=="").join(`
|
|
406
|
-
`)),language:s}),!t&&c.length>da&&ou(Kc,{color:x().colors.textMuted,children:["... (+",c.length-da," lines)"]})]})})})}let i=e;if(i.type==="media"||i.type==="image")return Bt(Rr,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Bt(Rr,{flexDirection:"row",children:Bt(Kc,{children:"Read image"})})});if(i.type==="text"&&i.file){let a=i.file,c=a.content||"(No content)";return Bt(Rr,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Bt(Rr,{flexDirection:"row",children:ou(Rr,{flexDirection:"column",children:[Bt(jr,{code:t?c:$n(c.split(`
|
|
407
|
-
`).slice(0,da).filter(l=>l.trim()!=="").join(`
|
|
408
|
-
`)),language:nx(a.filePath).slice(1)}),!t&&a.numLines>da&&ou(Kc,{color:x().colors.textMuted,children:["... (+",a.numLines-da," lines)"]})]})})})}return Bt(Rr,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Bt(Rr,{flexDirection:"row",children:Bt(Kc,{children:JSON.stringify(e)})})})},renderRejection(){return Bt(k,{})}};import{jsx as un,jsxs as Vc}from"react/jsx-runtime";import{Box as su,Text as Co}from"ink";import{EOL as LR}from"os";import{extname as NR,relative as fp}from"path";D();var pp=3,hp={displayName:()=>"Write",renderInput(e,{verbose:t}){let r=String(e?.file_path??e?.path??"");if(!r)return"";let n=t?r:fp(process.cwd(),r),o=typeof e?.content=="string"?` (${e.content.length} bytes)`:"";return n+o},renderRejection(){return un(k,{})},renderOutput(e,{verbose:t}){if(e==null)return un(Co,{children:"(No content)"});if(typeof e=="string")return un(Co,{children:e});let r=e;if(r.structuredPatch)return un(ru,{filePath:r.filePath??r.path,structuredPatch:r.structuredPatch,verbose:t});if(r.path!=null&&r.action!=null){let n=t?String(r.path):fp(process.cwd(),String(r.path)),o=r.bytesWritten!=null?Number(r.bytesWritten):void 0,s=String(r.action),i=o!=null?`${o} bytes to `:"";return un(su,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:un(su,{flexDirection:"row",children:Vc(Co,{children:["Wrote ",i,un(Co,{bold:!0,children:n})," (",s,")"]})})})}if(r.type==="create"&&r.filePath!=null){let n=r.content||"",o=n||"(No content)",s=n.split(LR).length;return Vc(su,{flexDirection:"column",children:[Vc(Co,{children:["Wrote ",s," lines to"," ",un(Co,{bold:!0,children:t?r.filePath:fp(process.cwd(),r.filePath)})]}),Vc(su,{flexDirection:"column",paddingLeft:5,children:[un(jr,{code:t?o:$n(o.split(`
|
|
409
|
-
`).slice(0,pp).filter(i=>i.trim()!=="").join(`
|
|
410
|
-
`)),language:NR(r.filePath).slice(1)}),!t&&s>pp&&Vc(Co,{color:x().colors.textMuted,children:["... (+",s-pp," lines)"]})]})]})}return un(Co,{children:JSON.stringify(e)})}};import{jsx as vs,jsxs as ua}from"react/jsx-runtime";import{Box as au,Text as ks}from"ink";import{isAbsolute as FR,relative as gp,resolve as UR}from"path";import{jsxs as OR,jsx as jR}from"react/jsx-runtime";import{Box as PR,Text as $R}from"ink";function iu({costUSD:e,durationMs:t,debug:r}){if(!r)return null;let n=(t/1e3).toFixed(1);return jR(PR,{flexDirection:"column",minWidth:23,width:23,children:OR($R,{dimColor:!0,children:["Cost: $",e.toFixed(4)," (",n,"s)"]})})}var ox={displayName(){return"Grep"},renderInput({pattern:e,path:t,include:r},{verbose:n}){let o=t?FR(t)?t:UR(process.cwd(),t):void 0,s=o?gp(process.cwd(),o):void 0;return`pattern: "${e}"${s||n?`, path: "${n?o:s}"`:""}${r?`, include: "${r}"`:""}`},renderRejection(){return vs(k,{})},renderOutput(e){let t=0,r=0,n=0,o=!1,s=[];if(e!=null&&typeof e=="object"&&!Array.isArray(e)){let a=e;if(Array.isArray(a.matches)){let c=new Set;for(let l of a.matches){let d=l,f=typeof d.filePath=="string"?d.filePath:typeof d.file=="string"?d.file:typeof d.path=="string"?d.path:void 0;f&&c.add(f)}t=a.matches.length,r=c.size,o=!!a.truncated;for(let l of c)s.push(gp(process.cwd(),l))}else typeof a.numFiles=="number"&&(r=a.numFiles,n=typeof a.durationMs=="number"?a.durationMs:0)}else if(Array.isArray(e)){let a=new Set;for(let c of e)if(c!=null&&typeof c=="object"){let l=c,d=typeof l.filePath=="string"?l.filePath:typeof l.file=="string"?l.file:typeof l.path=="string"?l.path:void 0;d&&a.add(d)}t=e.length,r=a.size||e.length;for(let c of a)s.push(gp(process.cwd(),c))}let i=4;return ua(au,{flexDirection:"column",children:[ua(au,{flexDirection:"row",children:[ua(ks,{bold:!0,children:[t," "]}),ua(ks,{children:[t===1?"match":"matches"," in "]}),ua(ks,{bold:!0,children:[r," "]}),vs(ks,{children:r===1?"file":"files"}),o&&vs(ks,{color:"yellow",children:" (truncated)"}),n>0&&vs(iu,{costUSD:0,durationMs:n,debug:!1})]}),s.slice(0,i).map((a,c)=>vs(au,{paddingLeft:2,children:vs(ks,{dimColor:!0,children:a})},c)),s.length>i&&vs(au,{paddingLeft:2,children:ua(ks,{dimColor:!0,children:["+",s.length-i," more files"]})})]})}};import{jsx as cu,jsxs as wp}from"react/jsx-runtime";import{Box as sx,Text as yp}from"ink";import{isAbsolute as BR,relative as HR,resolve as WR}from"path";var ix={displayName(){return"Search"},renderInput({pattern:e,path:t},{verbose:r}){let n=t?BR(t)?t:WR(process.cwd(),t):void 0,o=n?HR(process.cwd(),n):void 0;return`pattern: "${e}"${o||r?`, path: "${r?n:o}"`:""}`},renderRejection(){return cu(k,{})},renderOutput(e){let t=0,r=0;if(Array.isArray(e))t=e.length;else if(typeof e=="string")try{let n=JSON.parse(e);t=n.numFiles??0,r=n.durationMs??0}catch{t=0}else if(e!=null&&typeof e=="object"){let n=e;t=typeof n.numFiles=="number"?n.numFiles:0,r=typeof n.durationMs=="number"?n.durationMs:0}return wp(sx,{justifyContent:"space-between",width:"100%",children:[wp(sx,{flexDirection:"row",children:[cu(yp,{children:"Found "}),wp(yp,{bold:!0,children:[t," "]}),cu(yp,{children:t===0||t>1?"files":"file"})]}),r>0&&cu(iu,{costUSD:0,durationMs:r,debug:!1})]})}};import{jsx as Pr,jsxs as ma}from"react/jsx-runtime";import{Box as Fn,Text as Ms}from"ink";import{isAbsolute as qR,relative as GR,resolve as XR}from"path";D();var Un=3,ax=1e3,zR=`There are more than ${ax} files in the repository. Use the LS tool (passing a specific path), Bash tool, and other tools to explore nested directories. The first ${ax} files and directories are included below:
|
|
411
|
-
|
|
412
|
-
`,lu={displayName(){return"List"},renderInput({path:e},{verbose:t}){let r=e?qR(e)?e:XR(process.cwd(),e):void 0,n=r?GR(process.cwd(),r):".";return`path: "${t?e:n}"`},renderRejection(){return Pr(k,{})},renderOutput(e,{verbose:t}){if(typeof e=="string"){let r=e.replace(zR,"");if(!r)return null;let n=r.split(`
|
|
413
|
-
`).filter(o=>o.trim()!=="");return Pr(Fn,{justifyContent:"space-between",width:"100%",children:Pr(Fn,{children:ma(Fn,{flexDirection:"column",paddingLeft:0,children:[n.slice(0,t?void 0:Un).map((o,s)=>Pr(Ms,{children:t?o:Ut(o)},s)),!t&&n.length>Un&&ma(Ms,{color:x().colors.textMuted,children:["... (+",n.length-Un," items)"]})]})})})}if(e!=null&&typeof e=="object"&&!Array.isArray(e)){let r=e,n=Array.isArray(r.entries)?r.entries:[],o=typeof r.total=="number"?r.total:n.length;if(n.length===0)return Pr(Ms,{children:"(empty directory)"});let s=n.map(i=>{let a=i.type==="dir"||i.type==="directory"?"/":"";return`${i.name}${a}`});return Pr(Fn,{justifyContent:"space-between",width:"100%",children:Pr(Fn,{children:ma(Fn,{flexDirection:"column",paddingLeft:0,children:[s.slice(0,t?void 0:Un).map((i,a)=>Pr(Ms,{children:t?i:Ut(i)},a)),!t&&o>Un&&ma(Ms,{color:x().colors.textMuted,children:["... (+",o-Un," items)"]})]})})})}if(Array.isArray(e)){let r=e.map(String);return Pr(Fn,{justifyContent:"space-between",width:"100%",children:Pr(Fn,{children:ma(Fn,{flexDirection:"column",paddingLeft:0,children:[r.slice(0,t?void 0:Un).map((n,o)=>Pr(Ms,{children:t?n:Ut(n)},o)),!t&&r.length>Un&&ma(Ms,{color:x().colors.textMuted,children:["... (+",r.length-Un," items)"]})]})})})}return null}};import{jsx as fa}from"react/jsx-runtime";import{Box as KR,Text as cx}from"ink";D();var lx={displayName:()=>"mcp",renderInput(e){return Object.entries(e).map(([t,r])=>`${t}: ${JSON.stringify(r)}`).join(", ")},renderRejection(){return fa(k,{})},renderOutput(e,{verbose:t}){if(Array.isArray(e))return fa(KR,{flexDirection:"column",children:e.map((n,o)=>{if(n.type==="image")return fa(cx,{children:"[Image]"},o);let s=(n.text||"").split(`
|
|
414
|
-
`).length;return fa(aa,{content:n.text||"",lines:s,verbose:t},o)})});if(!e)return fa(cx,{color:x().colors.textMuted,children:"(No content)"});let r=e.split(`
|
|
415
|
-
`).length;return fa(aa,{content:e,lines:r,verbose:t})}};D();import{jsxs as dx,jsx as VR}from"react/jsx-runtime";import{Box as YR,Text as ux}from"ink";var mx={displayName:()=>"Think",renderInput(e){return e.thought},renderRejection(){return dx(YR,{flexDirection:"row",height:1,overflow:"hidden",children:[dx(ux,{children:[" ","\u23BF \xA0"]}),VR(ux,{color:x().colors.error,children:"Thought cancelled"})]})},renderOutput(){return null}};import{jsx as du}from"react/jsx-runtime";import{Box as JR,Text as QR}from"ink";D();function ZR(e){if(e==null)return"(No content)";if(typeof e=="string")return e||"(No content)";if(typeof e=="object"){let t=e;if(typeof t.formattedContext=="string"&&t.formattedContext)return t.formattedContext;if(typeof t.content=="string")return t.content||"(No content)";if(Array.isArray(t.memories)){let r=t.memories;if(r.length===0)return"(No memories found)";let n=typeof t.count=="number"?t.count:r.length,o=r.map(s=>{let i=typeof s.content=="string"?s.content:JSON.stringify(s.content),a=typeof s.network=="string"?` [${s.network}]`:"";return`\u2022 ${i}${a}`});return`${n} memories:
|
|
416
|
-
${o.join(`
|
|
417
|
-
`)}`}return JSON.stringify(e)}return String(e)}function eA({content:e,isEmpty:t}){let{contentWidth:r}=To();return du(JR,{flexDirection:"column",width:"100%",children:du(QR,{color:t?x().colors.textMuted:void 0,children:t?e:St(e,{width:r})})})}var uu={displayName(){return"Read Memory"},renderInput(e){return Object.entries(e).map(([t,r])=>`${t}: ${JSON.stringify(r)}`).join(", ")},renderRejection(){return du(k,{})},renderOutput(e,{verbose:t}={verbose:!1}){let r=ZR(e),n=3,o=r.split(`
|
|
418
|
-
`),s=!t&&o.length>n,i=$n(s?[...o.slice(0,n),`\u2026 +${o.length-n} lines`].join(`
|
|
419
|
-
`):r);return du(eA,{content:i,isEmpty:r==="(No content)"})}};import{jsx as mu}from"react/jsx-runtime";import{Box as fx,Text as tA}from"ink";var Yc={displayName(){return"Write Memory"},renderInput(e){return Object.entries(e).map(([t,r])=>`${t}: ${JSON.stringify(r)}`).join(", ")},renderRejection(){return mu(k,{})},renderOutput(){return mu(fx,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:mu(fx,{flexDirection:"row",children:mu(tA,{children:"Updated memory"})})})}};import{jsx as rA}from"react/jsx-runtime";import{EOL as nA}from"os";var xp={displayName(){return"Task"},renderInput(e,{verbose:t}){let r=typeof e.prompt=="string"?e.prompt:typeof e.task=="string"?e.task:"";if(!r)return"";let n=typeof e.arion=="string"?`@${e.arion} `:"",o=r.split(nA);return n+St(!t&&o.length>1?o[0]+"\u2026":r)},renderRejection(){return rA(k,{})},renderOutput(){return null}};import{jsx as Sp,jsxs as oA}from"react/jsx-runtime";import{Text as bp}from"ink";import{relative as sA}from"path";var px={displayName(){return"Read Notebook"},renderInput(e,{verbose:t}){return`notebook_path: ${t?e.notebook_path:sA(process.cwd(),e.notebook_path)}`},renderRejection(){return Sp(k,{})},renderOutput(e){return e?e.length<1||!e[0]?Sp(bp,{children:"No cells found in notebook"}):oA(bp,{children:["Read ",e.length," cells"]}):Sp(bp,{children:"No cells found in notebook"})}};import{jsx as pa,jsxs as Tp}from"react/jsx-runtime";import{Box as Ep,Text as fu}from"ink";import{relative as iA}from"path";var hx={displayName(){return"Edit Notebook"},renderInput(e,{verbose:t}){let r=t?e.notebook_path:iA(process.cwd(),e.notebook_path??""),n=e.new_source?e.new_source.slice(0,30)+"\u2026":"";return`${r} cell:${e.cell_number??"?"}${n?` "${n}"`:""}`},renderRejection(){return pa(k,{})},renderOutput(e){if(!e||typeof e!="object")return pa(fu,{children:"(No content)"});let{cell_number:t,new_source:r,language:n,error:o}=e;if(o)return pa(Ep,{flexDirection:"column",children:pa(fu,{color:"red",children:o})});let s=2,i=r.split(`
|
|
420
|
-
`),a=i.length>s,c=a?i.slice(0,s).join(`
|
|
421
|
-
`):r;return Tp(Ep,{flexDirection:"column",children:[Tp(fu,{children:["Updated cell ",t,":"]}),pa(Ep,{marginLeft:2,children:pa(jr,{code:c,language:n})}),a&&Tp(fu,{color:"gray",children:["... (+",i.length-s," lines)"]})]})}};import{jsx as _p,jsxs as gx}from"react/jsx-runtime";import{Box as aA,Text as wx}from"ink";D();var Cp=3,yx={displayName(){return"Architect"},renderInput(e){return Object.entries(e).map(([t,r])=>`${t}: ${JSON.stringify(r)}`).join(", ")},renderOutput(e,{verbose:t}={verbose:!1}){if(!e||!Array.isArray(e))return _p(wx,{children:"(No content)"});let r=e.map(i=>i.text).join(`
|
|
422
|
-
`),n=r.split(`
|
|
423
|
-
`),o=!t&&n.length>Cp,s=$n(o?n.slice(0,Cp).join(`
|
|
424
|
-
`):r);return gx(aA,{flexDirection:"column",gap:1,children:[_p(jr,{code:s,language:"markdown"}),o&&gx(wx,{color:x().colors.textMuted,children:["... (+",n.length-Cp," lines)"]})]})},renderRejection(){return _p(k,{})}};D();import{jsx as cA,jsxs as lA}from"react/jsx-runtime";import{Text as xx}from"ink";var Sx={displayName:()=>"Stickers",renderInput(e){return typeof e.prompt=="string"?e.prompt.length>50?e.prompt.slice(0,50)+"\u2026":e.prompt:""},renderRejection(){return lA(xx,{children:["\xA0\xA0\u23BF \xA0",cA(xx,{color:x().colors.error,children:"No (Sticker request cancelled)"})]})},renderOutput(){return null}};import{jsx as Bn,jsxs as pu}from"react/jsx-runtime";import{Box as Jc,Text as ha}from"ink";D();function bx(e,t=80){return e.length>t?e.slice(0,t-1)+"\u2026":e}function dA(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/(1024*1024)).toFixed(1)}MB`}function uA({preview:e}){let{contentWidth:t}=To(),r=Math.max(t-4,1);return Bn(ha,{color:x().colors.textMuted,dimColor:!0,children:St(e,{width:r})})}var Tx={displayName(){return"Fetch"},renderInput(e){return e.url?bx(String(e.url)):Object.entries(e).map(([t,r])=>`${t}: ${JSON.stringify(r)}`).join(", ")},renderRejection(){return Bn(k,{})},renderOutput(e){if(!e||typeof e=="string"){let c=typeof e=="string"?e:"(No content)";return Bn(Jc,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Bn(Jc,{flexDirection:"row",children:Bn(ha,{color:x().colors.textMuted,children:c})})})}let t=x(),r=e.finalUrl||"",n=e.status,o=n&&n>=200&&n<300?t.colors.success:n&&n>=400?t.colors.error:t.colors.warning,s=e.content?e.content.slice(0,200).split(`
|
|
425
|
-
`)[0]:"",i=e.contentBytes?dA(e.contentBytes):"",a=e.fromCache?" (cached)":"";return pu(Jc,{flexDirection:"column",children:[pu(Jc,{flexDirection:"row",children:[n!=null&&pu(ha,{color:o,bold:!0,children:[n," "]}),r&&Bn(ha,{color:t.colors.textMuted,children:bx(r,60)}),i&&pu(ha,{color:t.colors.textMuted,children:[" ","(",i,a,")"]}),e.truncated&&Bn(ha,{color:t.colors.warning,children:" [truncated]"})]}),s&&Bn(Jc,{flexDirection:"row",paddingLeft:4,children:Bn(uA,{preview:s})})]})}};import{jsx as hr,jsxs as Ex}from"react/jsx-runtime";import{Box as ga,Text as Ds}from"ink";D();function Rp(e,t=80){return e.length>t?e.slice(0,t-1)+"\u2026":e}function mA({preview:e}){let{contentWidth:t}=To(),r=Math.max(t-4,1);return hr(Ds,{color:x().colors.textMuted,dimColor:!0,children:St(e,{width:r})})}var _x={displayName(){return"Browse"},renderInput(e){return e.url?Rp(String(e.url)):Object.entries(e).map(([t,r])=>`${t}: ${JSON.stringify(r)}`).join(", ")},renderRejection(){return hr(k,{})},renderOutput(e){if(!e||typeof e=="string"){let i=typeof e=="string"?e:"(No content)";return hr(ga,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:hr(ga,{flexDirection:"row",children:hr(Ds,{color:x().colors.textMuted,children:i})})})}let t=x(),r=e.finalUrl||e.url||"",n=e.title||"",o=e.content?e.content.slice(0,200).split(`
|
|
426
|
-
`)[0]:"",s=e.fromCache?" (cached)":"";return Ex(ga,{flexDirection:"column",children:[Ex(ga,{flexDirection:"row",children:[n?hr(Ds,{bold:!0,children:n}):hr(Ds,{color:t.colors.textMuted,children:Rp(r,60)}),s&&hr(Ds,{color:t.colors.textMuted,children:s}),e.truncated&&hr(Ds,{color:t.colors.warning,children:" [truncated]"})]}),n&&r&&hr(ga,{flexDirection:"row",paddingLeft:4,children:hr(Ds,{color:t.colors.textMuted,children:Rp(r,60)})}),o&&hr(ga,{flexDirection:"row",paddingLeft:4,children:hr(mA,{preview:o})})]})}};import{jsx as Ro,jsxs as Ls}from"react/jsx-runtime";import{Box as wa,Text as Ao}from"ink";D();function fA(e){try{return new URL(e).hostname.replace(/^www\./,"")}catch{return e.length>50?e.slice(0,47)+"\u2026":e}}var Cx={displayName(){return"Search"},renderInput(e){return e.query?`"${e.query}"`:Object.entries(e).map(([t,r])=>`${t}: ${JSON.stringify(r)}`).join(", ")},renderRejection(){return Ro(k,{})},renderOutput(e){if(!e||typeof e=="string"){let i=typeof e=="string"?e:"(No results)";return Ro(wa,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Ro(wa,{flexDirection:"row",children:Ro(Ao,{color:x().colors.textMuted,children:i})})})}let t=x(),r=e.results||[],n=e.query||"",o=2,s=r.slice(0,o);return Ls(wa,{flexDirection:"column",children:[Ls(wa,{flexDirection:"row",children:[Ro(Ao,{children:"Found "}),Ls(Ao,{bold:!0,children:[r.length," "]}),Ro(Ao,{children:r.length===1?"result":"results"}),n&&Ls(Ao,{color:t.colors.textMuted,children:[" for '",n,"'"]})]}),s.map((i,a)=>Ls(wa,{flexDirection:"row",paddingLeft:4,children:[Ro(Ao,{bold:!0,children:i.title.length>60?i.title.slice(0,57)+"\u2026":i.title}),Ls(Ao,{color:t.colors.textMuted,children:[" (",fA(i.url),")"]})]},a)),r.length>o&&Ro(wa,{flexDirection:"row",paddingLeft:4,children:Ls(Ao,{color:t.colors.textMuted,children:["+",r.length-o," more"]})})]})}};import{jsx as Hn,jsxs as pA}from"react/jsx-runtime";import{Box as ya,Text as Ap}from"ink";var Rx={displayName(){return"Learn"},renderInput(e,t){let r;typeof e.source=="string"?r=e.source:e.source&&typeof e.source=="object"?r=e.source.type||e.source.command||e.source.path||"unknown":r="unknown";let n=e.name??"";return n?`${r}: ${n}`:r},renderRejection(){return Hn(k,{})},renderOutput(e){if(e==null)return Hn(ya,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Hn(ya,{flexDirection:"row",children:Hn(Ap,{children:"Learned"})})});if(typeof e=="string")return Hn(ya,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Hn(ya,{flexDirection:"row",children:Hn(Ap,{children:e})})});let t=e,r=t.name??"unknown",n=t.type??"",o=n?` ${n}`:"";return Hn(ya,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Hn(ya,{flexDirection:"row",children:pA(Ap,{children:["Learned",o," ",r]})})})}};import{jsx as xa,jsxs as hA}from"react/jsx-runtime";import{Box as hu,Text as Ax}from"ink";var Ix={displayName(){return"Learn Tool"},renderInput(e,t){return e.name??"tool"},renderRejection(){return xa(k,{})},renderOutput(e){if(!e||typeof e!="object")return xa(hu,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:xa(hu,{flexDirection:"row",children:xa(Ax,{children:"(No content)"})})});let t=e.name??"unknown";return xa(hu,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:xa(hu,{flexDirection:"row",children:hA(Ax,{children:["Learned tool ",t]})})})}};import{jsx as Sa,jsxs as gA}from"react/jsx-runtime";import{Box as gu,Text as vx}from"ink";var kx={displayName(){return"Learn Skill"},renderInput(e,t){return e.name??"skill"},renderRejection(){return Sa(k,{})},renderOutput(e){if(!e||typeof e!="object")return Sa(gu,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Sa(gu,{flexDirection:"row",children:Sa(vx,{children:"(No content)"})})});let t=e.name??"unknown";return Sa(gu,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Sa(gu,{flexDirection:"row",children:gA(vx,{children:["Learned skill ",t]})})})}};import{jsx as Wn,jsxs as wA}from"react/jsx-runtime";import{Box as ba,Text as Ip}from"ink";import{basename as yA}from"path";var Mx={displayName(){return"Create Tool"},renderInput(e,t){return e.name??"tool"},renderRejection(){return Wn(k,{})},renderOutput(e){if(e==null)return Wn(ba,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Wn(ba,{flexDirection:"row",children:Wn(Ip,{children:"Created tool"})})});if(typeof e=="string")return Wn(ba,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Wn(ba,{flexDirection:"row",children:Wn(Ip,{children:e})})});let t=e,r=t.name??(typeof t.scriptPath=="string"?yA(t.scriptPath):"unknown");return Wn(ba,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Wn(ba,{flexDirection:"row",children:wA(Ip,{children:["Created tool ",r]})})})}};import{jsx as Ta,jsxs as xA}from"react/jsx-runtime";import{Box as wu,Text as Dx}from"ink";var Lx={displayName(){return"Create Skill"},renderInput(e,t){return e.name??"skill"},renderRejection(){return Ta(k,{})},renderOutput(e){if(!e||typeof e!="object")return Ta(wu,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Ta(wu,{flexDirection:"row",children:Ta(Dx,{children:"(No content)"})})});let t=e.name??"unknown";return Ta(wu,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Ta(wu,{flexDirection:"row",children:xA(Dx,{children:["Created skill ",t]})})})}};import{jsx as Ea,jsxs as SA}from"react/jsx-runtime";import{Box as yu,Text as Nx}from"ink";var Ox={displayName(){return"Use Skill"},renderInput(e,t){return e.name??"skill"},renderRejection(){return Ea(k,{})},renderOutput(e){if(!e||typeof e!="object")return Ea(yu,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Ea(yu,{flexDirection:"row",children:Ea(Nx,{children:"(No content)"})})});let t=e.skill?.name??"unknown";return Ea(yu,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Ea(yu,{flexDirection:"row",children:SA(Nx,{children:["Loaded skill ",t]})})})}};import{jsx as Io,jsxs as xu}from"react/jsx-runtime";import{Box as Ns,Text as Su}from"ink";D();function bA(e){let t=x();switch(e){case"active":case"in_progress":return t.colors.success;case"blocked":return t.colors.warning;case"done":case"closed":return t.colors.textMuted;default:return t.colors.text}}var jx={displayName(){return"Quest List"},renderInput(e){return e.status?`status: ${e.status}`:"all quests"},renderRejection(){return Io(k,{})},renderOutput(e,{verbose:t}){let r=e?.quests??[],n=e?.count??r.length;return t?r.length===0?Io(Ns,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Io(Ns,{flexDirection:"row",children:Io(Su,{children:"0 quests"})})}):xu(Ns,{flexDirection:"column",children:[Io(Ns,{children:xu(Su,{children:[n," quest",n!==1?"s":""]})}),r.map(o=>Io(Ns,{flexDirection:"row",paddingLeft:4,children:xu(Su,{color:bA(o.status),children:["P",o.priority," [",o.status,"] ",o.id," ",o.title]})},o.id))]}):Io(Ns,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Io(Ns,{flexDirection:"row",children:xu(Su,{children:[n," quest",n!==1?"s":""]})})})}};import{jsx as Os,jsxs as bu}from"react/jsx-runtime";import{Box as Qc,Text as Zc}from"ink";D();function TA(e){let t=x();switch(e){case"created":return t.colors.success;case"updated":return t.colors.info;case"failed":return t.colors.error;default:return t.colors.text}}var Px={displayName(){return"Quest Update"},renderInput(e){if(e.quests&&Array.isArray(e.quests)){let r=e.quests.length;return`${r} quest${r!==1?"s":""}`}let t=[];return e.action&&t.push(e.action),e.title&&t.push(e.title),e.id&&t.push(e.id),t.join(" ")||"quest update"},renderRejection(){return Os(k,{})},renderOutput(e,{verbose:t}){let r=[];if(e!=null&&typeof e=="object"){let c=e;Array.isArray(c.quests)&&(r=c.quests)}let n=r.filter(c=>c.action==="created").length,o=r.filter(c=>c.action==="updated").length,s=r.filter(c=>c.action==="failed").length,i=x(),a=[];return n>0&&a.push(`${n} created`),o>0&&a.push(`${o} updated`),s>0&&a.push(`${s} failed`),a.length===0&&a.push("0 changes"),t?bu(Qc,{flexDirection:"column",children:[Os(Qc,{children:a.map((c,l)=>{let d=c.includes("created")?i.colors.success:c.includes("updated")?i.colors.info:c.includes("failed")?i.colors.error:i.colors.text;return bu(Zc,{children:[l>0?", ":"",Os(Zc,{color:d,children:c})]},l)})}),r.map(c=>Os(Qc,{flexDirection:"row",paddingLeft:4,children:bu(Zc,{color:TA(c.action),children:["[",c.action,"] ",c.id," ",c.title,c.error?` -- ${c.error}`:""]})},c.id))]}):Os(Qc,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Os(Qc,{flexDirection:"row",children:a.map((c,l)=>{let d=c.includes("created")?i.colors.success:c.includes("updated")?i.colors.info:c.includes("failed")?i.colors.error:i.colors.text;return bu(Zc,{children:[l>0?", ":"",Os(Zc,{color:d,children:c})]},l)})})})}};import{jsx as qn,jsxs as vp}from"react/jsx-runtime";import{Box as js,Text as Tu}from"ink";var $x=120,Fx={displayName(){return"Ask User"},renderInput(e){let t;if(typeof e.question=="string")t=e.question;else{let r=e.questions?.[0];t=typeof r=="string"?r:typeof r?.question=="string"?r.question:"asking user..."}return t.length>$x?t.slice(0,$x)+"\u2026":t},renderRejection(){return qn(k,{})},renderOutput(e,{verbose:t}){if(typeof e=="string")return qn(js,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:qn(js,{flexDirection:"row",children:qn(Tu,{children:"Received answer"})})});let r=e?.answers??[],n=r.length;return t?vp(js,{flexDirection:"column",children:[qn(js,{children:vp(Tu,{children:["Received ",n," answer",n!==1?"s":""]})}),r.map((o,s)=>qn(js,{flexDirection:"row",paddingLeft:4,children:qn(Tu,{children:typeof o=="string"?o:o?.answer??JSON.stringify(o)})},s))]}):qn(js,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:qn(js,{flexDirection:"row",children:vp(Tu,{children:["Received ",n," answer",n!==1?"s":""]})})})}};import{jsx as Gn,jsxs as EA}from"react/jsx-runtime";import{Box as _a,Text as kp}from"ink";D();var Ux={displayName(){return"Hatch Arion"},renderInput(e,t){return e.name?`${e.name}`:Object.entries(e).map(([r,n])=>`${r}: ${JSON.stringify(n)}`).join(", ")},renderRejection(){return Gn(k,{})},renderOutput(e,t){let r=x();if(!e)return Gn(_a,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Gn(_a,{flexDirection:"row",children:Gn(kp,{color:r.colors.textMuted,children:"(No content)"})})});if(typeof e=="string")return Gn(_a,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Gn(_a,{flexDirection:"row",children:Gn(kp,{color:r.colors.success,children:e.includes("hatched")?e:`${e} has hatched!`})})});let n=e.emoji||"",o=e.name||"Arion";return Gn(_a,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Gn(_a,{flexDirection:"row",children:EA(kp,{color:r.colors.success,children:[n,n?" ":"",o," has hatched!"]})})})}};import{jsx as Ps}from"react/jsx-runtime";import{Box as Eu,Text as Bx}from"ink";D();var Hx={displayName(){return"Rest Arion"},renderInput(e,t){return e.name?`${e.name}`:Object.entries(e).map(([r,n])=>`${r}: ${JSON.stringify(n)}`).join(", ")},renderRejection(){return Ps(k,{})},renderOutput(e,t){let r=x();if(e==null)return Ps(Eu,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Ps(Eu,{flexDirection:"row",children:Ps(Bx,{color:r.colors.textMuted,children:"Arion is now resting"})})});let n=typeof e=="string"?e:e.message||`${e.name||"Arion"} is now resting`;return Ps(Eu,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Ps(Eu,{flexDirection:"row",children:Ps(Bx,{color:r.colors.textMuted,children:n})})})}};import{jsx as $s}from"react/jsx-runtime";import{Box as _u,Text as Wx}from"ink";D();var qx={displayName(){return"Wake Arion"},renderInput(e,t){return e.name?`${e.name}`:Object.entries(e).map(([r,n])=>`${r}: ${JSON.stringify(n)}`).join(", ")},renderRejection(){return $s(k,{})},renderOutput(e,t){let r=x();if(e==null)return $s(_u,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:$s(_u,{flexDirection:"row",children:$s(Wx,{color:r.colors.success,children:"Arion is now awake"})})});let n=typeof e=="string"?e:e.message||`${e.name||"Arion"} is now awake`;return $s(_u,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:$s(_u,{flexDirection:"row",children:$s(Wx,{color:r.colors.success,children:n})})})}};import{jsx as Fs}from"react/jsx-runtime";import{Box as Cu,Text as Gx}from"ink";D();var Xx={displayName(){return"Retire Arion"},renderInput(e,t){return e.name?`${e.name}`:Object.entries(e).map(([r,n])=>`${r}: ${JSON.stringify(n)}`).join(", ")},renderRejection(){return Fs(k,{})},renderOutput(e,t){let r=x();if(e==null)return Fs(Cu,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Fs(Cu,{flexDirection:"row",children:Fs(Gx,{color:r.colors.warning,children:"Arion has been retired"})})});let n=typeof e=="string"?e:e.message||`${e.name||"Arion"} has been retired`;return Fs(Cu,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Fs(Cu,{flexDirection:"row",children:Fs(Gx,{color:r.colors.warning,children:n})})})}};import{jsx as mn,jsxs as _A}from"react/jsx-runtime";import{Box as Ca,Text as Ru}from"ink";D();var zx={displayName(){return"Spawn Worker"},renderInput(e,t){return e.task?`${e.task}`:Object.entries(e).map(([r,n])=>`${r}: ${JSON.stringify(n)}`).join(", ")},renderRejection(){return mn(k,{})},renderOutput(e,t){let r=x();if(!e)return mn(Ca,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:mn(Ca,{flexDirection:"row",children:mn(Ru,{color:r.colors.textMuted,children:"(No content)"})})});if(typeof e=="string")return mn(Ca,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:mn(Ca,{flexDirection:"row",children:mn(Ru,{children:e})})});let n=e.id||"unknown";return mn(Ca,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:_A(Ca,{flexDirection:"row",children:[mn(Ru,{children:"Spawned worker "}),mn(Ru,{bold:!0,children:n})]})})}};import{jsx as Ar,jsxs as Mp}from"react/jsx-runtime";import{Box as vo,Text as Ra}from"ink";D();function CA(e,t){switch(e){case"completed":return t.colors.success;case"running":return t.colors.info;case"failed":return t.colors.error;default:return t.colors.textMuted}}var Kx={displayName(){return"Check Delegation"},renderInput(e,t){return e.id?`${e.id}`:Object.entries(e).map(([r,n])=>`${r}: ${JSON.stringify(n)}`).join(", ")},renderRejection(){return Ar(k,{})},renderOutput(e,t){let r=x();if(!e)return Ar(vo,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Ar(vo,{flexDirection:"row",children:Ar(Ra,{color:r.colors.textMuted,children:"(No content)"})})});if(typeof e=="string")return Ar(vo,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Ar(vo,{flexDirection:"row",children:Ar(Ra,{children:e})})});let{id:n,status:o,result:s,error:i}=e,a=CA(o,r);return Mp(vo,{flexDirection:"column",children:[Mp(vo,{flexDirection:"row",children:[n&&Mp(Ra,{bold:!0,children:[n," "]}),Ar(Ra,{color:a,children:o||"unknown"})]}),o==="completed"&&s&&Ar(vo,{flexDirection:"row",paddingLeft:4,children:Ar(Ra,{color:r.colors.textMuted,children:Ut(s)})}),o==="failed"&&i&&Ar(vo,{flexDirection:"row",paddingLeft:4,children:Ar(Ra,{color:r.colors.error,children:Ut(i)})})]})}};import{jsx as Yt,jsxs as RA}from"react/jsx-runtime";import{Box as ko,Text as Us}from"ink";D();function Au(e,t=60){return e.length>t?e.slice(0,t-1)+"\u2026":e}function AA(e){let t=e.action||"unknown";switch(t){case"launch":return e.url?`launch and navigate to ${Au(String(e.url))}`:"launch";case"navigate":return e.url?`navigate to ${Au(String(e.url))}`:"navigate";case"click":return e.selector?`click ${e.selector}`:"click";case"type":return e.selector?`type into ${e.selector}`:"type";default:return t}}var Vx={displayName(){return"Browser"},renderInput(e,t){return AA(e)},renderRejection(){return Yt(k,{})},renderOutput(e,t){let r=x();if(!e)return Yt(ko,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Yt(ko,{flexDirection:"row",children:Yt(Us,{color:r.colors.textMuted,children:"(No content)"})})});if(typeof e=="string")return Yt(ko,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Yt(ko,{flexDirection:"row",children:Yt(Us,{children:e})})});let n=e.title||"",o=e.url||"";return RA(ko,{flexDirection:"column",children:[Yt(ko,{flexDirection:"row",children:n?Yt(Us,{bold:!0,children:n}):o?Yt(Us,{color:r.colors.textMuted,children:Au(o)}):Yt(Us,{color:r.colors.success,children:"Done"})}),n&&o&&Yt(ko,{flexDirection:"row",paddingLeft:4,children:Yt(Us,{color:r.colors.textMuted,children:Au(o)})}),e.error&&Yt(ko,{flexDirection:"row",paddingLeft:4,children:Yt(Us,{color:r.colors.error,children:e.error})})]})}};import{jsx as it,jsxs as Mo}from"react/jsx-runtime";import{Box as Jt,Text as gr}from"ink";D();function IA(e){let t=e.action||"unknown";switch(t){case"spawn":return e.command?`spawn: ${e.command}`:"spawn";case"read":return e.pid!=null?`read pid ${e.pid}`:"read";case"write":return e.pid!=null?`write to pid ${e.pid}`:"write";case"kill":return e.pid!=null?`kill pid ${e.pid}`:"kill";case"list":return"list processes";default:return t}}var Yx={displayName(){return"Process"},renderInput(e,t){return IA(e)},renderRejection(){return it(k,{})},renderOutput(e,t){let r=x();if(!e)return it(Jt,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:it(Jt,{flexDirection:"row",children:it(gr,{color:r.colors.textMuted,children:"(No content)"})})});if(typeof e=="string")return it(Jt,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:it(Jt,{flexDirection:"row",children:it(gr,{children:e})})});if(e.action==="spawn"||e.pid!=null&&!e.output&&!e.sessions)return it(Jt,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Mo(Jt,{flexDirection:"row",children:[it(gr,{children:"Spawned process "}),it(gr,{bold:!0,children:e.pid})]})});if(e.action==="read"||e.output!=null){let n=(e.output||"").split(`
|
|
427
|
-
`),o=n.length>3?n.slice(0,3).map(Ut).join(`
|
|
428
|
-
`)+`
|
|
429
|
-
... +${n.length-3} more lines`:(e.output||"").split(`
|
|
430
|
-
`).map(Ut).join(`
|
|
431
|
-
`);return it(Jt,{flexDirection:"column",children:it(Jt,{flexDirection:"row",children:it(gr,{children:o})})})}if(e.action==="list"||e.sessions){let n=e.sessions||[];if(n.length===0)return it(Jt,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:it(Jt,{flexDirection:"row",children:it(gr,{color:r.colors.textMuted,children:"No active processes"})})});let o=2;return Mo(Jt,{flexDirection:"column",children:[Mo(Jt,{flexDirection:"row",children:[Mo(gr,{bold:!0,children:[n.length," "]}),it(gr,{children:n.length===1?"process":"processes"})]}),n.slice(0,o).map((s,i)=>Mo(Jt,{flexDirection:"row",paddingLeft:4,children:[Mo(gr,{bold:!0,children:[s.pid," "]}),Mo(gr,{children:[s.command||""," "]}),it(gr,{color:s.status==="running"?r.colors.success:r.colors.textMuted,children:s.status||""})]},i)),n.length>o&&Mo(gr,{color:r.colors.textMuted,children:["... (+",n.length-o," more)"]})]})}return it(Jt,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:it(Jt,{flexDirection:"row",children:it(gr,{children:JSON.stringify(e)})})})}};import{jsx as Aa,jsxs as Iu}from"react/jsx-runtime";import{Box as Dp,Text as Ia}from"ink";D();var Jx={displayName(){return"Search"},renderInput(e,{verbose:t}){let r=e.query;if(!r)return Object.entries(e).filter(([,o])=>o!==void 0).map(([o,s])=>`${o}: ${JSON.stringify(s)}`).join(", ");let n=[`"${r}"`];return t&&e.sources?.length&&n.push(`sources: [${e.sources.join(", ")}]`),n.join(" ")},renderRejection(){return Aa(k,{})},renderOutput(e){let t=x();if(!e||typeof e=="string"){let a=typeof e=="string"?e:"(No results)";return Aa(Dp,{flexDirection:"row",width:"100%",children:Aa(Ia,{color:t.colors.textMuted,children:a})})}let r=e.results??[],n=e.platform,o=(r.length===0,null),s=new Map;for(let a of r)s.set(a.source,(s.get(a.source)??0)+1);let i=[...s.entries()].map(([a,c])=>`${c} ${a}`).join(", ");return Aa(Dp,{flexDirection:"column",children:Iu(Dp,{flexDirection:"row",children:[Aa(Ia,{children:"Found "}),Iu(Ia,{bold:!0,children:[r.length," "]}),Aa(Ia,{children:r.length===1?"result":"results"}),n&&Iu(Ia,{color:t.colors.textMuted,children:[" ","on ",n.os,"/",n.arch]}),i&&r.length>0&&Iu(Ia,{color:t.colors.textMuted,children:[" (",i,")"]})]})})}};import{jsx as bt,jsxs as pt}from"react/jsx-runtime";import{Box as Ht,Text as Ze}from"ink";D();function vA(e){return e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m`:e<86400?`${Math.floor(e/3600)}h ${Math.floor(e%3600/60)}m`:`${Math.floor(e/86400)}d`}var Qx={displayName(){return"Self Diagnose"},renderInput(e){let t=[];return e.focus&&t.push(`focus: ${e.focus}`),e.sections?.length?t.push(`${e.sections.length} sections`):t.push("all sections"),t.join(", ")},renderRejection(){return bt(k,{})},renderOutput(e,{verbose:t}){if(!e||typeof e!="object")return null;let r=e,n=r._meta,o=x();if(!t){let s=[];n&&s.push(`${n.sections_returned.length}/6 sections \xB7 ${n.elapsed_ms}ms`),n?.errors.length&&s.push(`${n.errors.length} errors`);let i=r.errors&&r.errors.length>0||r.crashes&&r.crashes.length>0||r.runtime&&(r.runtime.socket_dirs>100||r.runtime.relaunch_pending);return bt(Ze,{color:i?o.colors.warning:o.colors.success,children:s.join(" \xB7 ")||"done"})}return pt(Ht,{flexDirection:"column",children:[r.runtime&&pt(Ht,{paddingLeft:2,flexDirection:"column",children:[bt(Ze,{bold:!0,children:"runtime"}),bt(Ht,{paddingLeft:2,children:pt(Ze,{children:["PID ",r.runtime.pid," \xB7 up ",vA(r.runtime.uptime_s)," \xB7 heap"," ",r.runtime.heap_mb,"MB \xB7 RSS ",r.runtime.rss_mb,"MB"]})}),(r.runtime.socket_dirs>100||r.runtime.relaunch_pending)&&pt(Ht,{paddingLeft:2,children:[r.runtime.socket_dirs>100&&pt(Ze,{color:o.colors.error,children:["\u26A0 socket leak: ",r.runtime.socket_dirs," dirs in sock/"]}),r.runtime.relaunch_pending&&bt(Ze,{color:o.colors.error,children:"\u26A0 stuck restart pending"})]})]}),r.errors!==void 0&&pt(Ht,{paddingLeft:2,flexDirection:"column",children:[bt(Ze,{bold:!0,color:r.errors&&r.errors.length>0?o.colors.error:o.colors.success,children:"errors"}),bt(Ht,{paddingLeft:2,flexDirection:"column",children:r.errors&&r.errors.length>0?r.errors.map((s,i)=>pt(Ze,{color:o.colors.error,children:["[",s.source,"] ",s.timestamp?s.timestamp.slice(11,19):"?"," ",s.severity," ",s.category,": ",s.message.slice(0,80)]},i)):bt(Ze,{color:o.colors.success,children:"none"})})]}),r.crashes!==void 0&&pt(Ht,{paddingLeft:2,flexDirection:"column",children:[bt(Ze,{bold:!0,color:r.crashes&&r.crashes.length>0?o.colors.error:o.colors.success,children:"crashes"}),bt(Ht,{paddingLeft:2,flexDirection:"column",children:r.crashes&&r.crashes.length>0?r.crashes.map((s,i)=>pt(Ze,{color:o.colors.error,children:[s.file," ",s.timestamp?s.timestamp.slice(0,19):""," ",s.error_message??""]},i)):bt(Ze,{color:o.colors.success,children:"none"})})]}),r.databases&&pt(Ht,{paddingLeft:2,flexDirection:"column",children:[bt(Ze,{bold:!0,children:"databases"}),bt(Ht,{paddingLeft:2,flexDirection:"column",children:r.databases.map((s,i)=>{let a=s.wal_mb&&parseFloat(s.wal_mb)>1;return pt(Ze,{color:a?o.colors.warning:void 0,children:[s.name,": ",s.size_mb,"MB",s.wal_mb?` (WAL ${s.wal_mb}MB${a?" \u26A0":""})`:"",s.schema_version!==void 0?` schema:v${s.schema_version}`:""]},i)})})]}),r.daemon&&r.daemon.length>0&&pt(Ht,{paddingLeft:2,flexDirection:"column",children:[bt(Ze,{bold:!0,children:"daemon"}),bt(Ht,{paddingLeft:2,flexDirection:"column",children:r.daemon.map((s,i)=>pt(Ze,{children:[s.source,": ",s.entries.length," entries"]},i))})]}),r.network&&pt(Ht,{paddingLeft:2,flexDirection:"column",children:[bt(Ze,{bold:!0,children:"network"}),pt(Ht,{paddingLeft:2,flexDirection:"column",children:[pt(Ze,{children:["node: ",r.network.display_name??"unknown"," \xB7 port"," ",r.network.listen_port??"?"," \xB7 endpoint"," ",r.network.external_endpoint??"none"]}),pt(Ze,{children:["peers: ",r.network.peer_count," \xB7 TLS:"," ",r.network.tls_certs_present?"\u2713":"\u2717"," \xB7 trusted CAs:"," ",r.network.trusted_cas]}),r.network.peers.length>0&&r.network.peers.map((s,i)=>pt(Ze,{color:s.status==="connected"?o.colors.success:o.colors.warning,children:[s.name||s.node_id.slice(0,8),": ",s.status]},i)),r.network.recent_diagnostics.length>0&&pt(Ze,{dimColor:!0,children:[r.network.recent_diagnostics.length," recent diagnostic events"]})]})]}),n?.errors&&n.errors.length>0&&pt(Ht,{paddingLeft:2,flexDirection:"column",children:[bt(Ze,{bold:!0,color:o.colors.error,children:"collection errors"}),n.errors.map((s,i)=>bt(Ht,{paddingLeft:2,children:bt(Ze,{color:o.colors.error,children:s})},i))]})]})}};import{jsx as $t,jsxs as Do}from"react/jsx-runtime";import{Box as Xn,Text as Qt}from"ink";import{relative as Zx}from"path";D();function kA(e){return"counts"in e&&Array.isArray(e.counts)}function MA(e){let t=[];return t.push(`"${e.pattern}"`),e.file_type&&t.push(`-t ${e.file_type}`),e.path&&t.push(e.path),t.join(" ")}var eS={displayName(){return"Ripgrep"},renderInput(e,{verbose:t}={}){let r=MA(e),n=t&&e.extra_args&&e.extra_args.length>0?` [${e.extra_args.join(" ")}]`:"";return`${r}${n}`},renderRejection(){return $t(k,{})},renderOutput(e){let t=x();if(!e||typeof e!="object")return $t(Qt,{color:t.colors.textMuted,children:String(e??"No result")});if(!("counts"in e)&&!("matches"in e)){let a=e.message;return $t(Qt,{color:t.colors.textMuted,children:typeof a=="string"?a:"Search complete"})}if(kA(e)){let{counts:a,total:c}=e,l=Math.min(5,a.length),d=a.length-l;return Do(Xn,{flexDirection:"column",children:[Do(Xn,{flexDirection:"row",children:[$t(Qt,{bold:!0,children:c}),$t(Qt,{children:" matches across "}),$t(Qt,{bold:!0,children:a.length}),$t(Qt,{children:" files"})]}),a.slice(0,l).map((f,u)=>$t(Xn,{paddingLeft:2,children:Do(Qt,{color:t.colors.textMuted,children:[Zx(process.cwd(),f.file),": ",f.count]})},u)),d>0&&$t(Xn,{paddingLeft:2,children:Do(Qt,{color:t.colors.textMuted,children:["+",d," more files"]})})]})}let{matches:r}=e;if(r.length===0)return $t(Xn,{children:$t(Qt,{color:t.colors.textMuted,children:"No matches found"})});let n=new Map;for(let a of r)n.has(a.file)||n.set(a.file,[]),n.get(a.file).push(a);let o=Array.from(n.entries()),s=Math.min(3,o.length),i=o.length-s;return Do(Xn,{flexDirection:"column",children:[Do(Xn,{flexDirection:"row",children:[$t(Qt,{bold:!0,children:r.length}),$t(Qt,{children:" matches in "}),$t(Qt,{bold:!0,children:o.length}),$t(Qt,{children:" files"})]}),o.slice(0,s).map(([a,c],l)=>$t(Xn,{paddingLeft:2,children:Do(Qt,{color:t.colors.textMuted,children:[Zx(process.cwd(),a),": ",c.length]})},l)),i>0&&$t(Xn,{paddingLeft:2,children:Do(Qt,{color:t.colors.textMuted,children:["+",i," more files"]})})]})}};import{jsx as Ft,jsxs as Lo}from"react/jsx-runtime";import{Box as zn,Text as Zt}from"ink";import{relative as tS}from"path";D();function DA(e){return"counts"in e&&Array.isArray(e.counts)}function LA(e){let t=[];return t.push(`"${e.pattern}"`),e.fuzzy!==void 0&&e.fuzzy!==!1&&(typeof e.fuzzy=="number"?t.push(`fuzzy:${e.fuzzy}`):t.push("fuzzy")),e.bool&&t.push("bool"),e.file_type&&t.push(`-t ${e.file_type}`),e.path&&e.path!=="."&&t.push(e.path),t.join(" ")}var rS={displayName(){return"Ugrep"},renderInput(e,{verbose:t}={}){let r=LA(e),n=[];return t&&(e.ignore_case&&n.push("-i"),e.smart_case&&n.push("-j"),e.fixed_strings&&n.push("-F"),e.word_regexp&&n.push("-w"),e.files_only&&n.push("-l"),e.count&&n.push("-c"),e.context!==void 0&&n.push(`-C ${e.context}`),e.neg_pattern&&n.push(`-N "${e.neg_pattern}"`),e.decompress&&n.push("-z"),e.glob&&n.push(`-g "${e.glob}"`),e.extra_args&&e.extra_args.length>0&&n.push(`[${e.extra_args.join(" ")}]`)),n.length>0?`${r} ${n.join(" ")}`:r},renderRejection(){return Ft(k,{})},renderOutput(e){let t=x();if(!e||typeof e!="object")return Ft(Zt,{color:t.colors.textMuted,children:String(e??"No result")});if(!("counts"in e)&&!("matches"in e)){let a=e.message;return Ft(Zt,{color:t.colors.textMuted,children:typeof a=="string"?a:"Search complete"})}if(DA(e)){let{counts:a,total:c}=e,l=Math.min(5,a.length),d=a.length-l;return Lo(zn,{flexDirection:"column",children:[Lo(zn,{flexDirection:"row",children:[Ft(Zt,{bold:!0,children:c}),Ft(Zt,{children:" matches across "}),Ft(Zt,{bold:!0,children:a.length}),Ft(Zt,{children:" files"})]}),a.slice(0,l).map((f,u)=>Ft(zn,{paddingLeft:2,children:Lo(Zt,{color:t.colors.textMuted,children:[tS(process.cwd(),f.file),": ",f.count]})},u)),d>0&&Ft(zn,{paddingLeft:2,children:Lo(Zt,{color:t.colors.textMuted,children:["+",d," more files"]})})]})}let{matches:r}=e;if(r.length===0)return Ft(zn,{children:Ft(Zt,{color:t.colors.textMuted,children:"No matches found"})});let n=new Map;for(let a of r)n.has(a.file)||n.set(a.file,[]),n.get(a.file).push(a);let o=Array.from(n.entries()),s=Math.min(3,o.length),i=o.length-s;return Lo(zn,{flexDirection:"column",children:[Lo(zn,{flexDirection:"row",children:[Ft(Zt,{bold:!0,children:r.length}),Ft(Zt,{children:" matches in "}),Ft(Zt,{bold:!0,children:o.length}),Ft(Zt,{children:" files"})]}),o.slice(0,s).map(([a,c],l)=>Ft(zn,{paddingLeft:2,children:Lo(Zt,{color:t.colors.textMuted,children:[tS(process.cwd(),a),": ",c.length]})},l)),i>0&&Ft(zn,{paddingLeft:2,children:Lo(Zt,{color:t.colors.textMuted,children:["+",i," more files"]})})]})}};import{jsx as be,jsxs as Ne}from"react/jsx-runtime";import{Box as Oe,Text as Ce}from"ink";import{relative as nS}from"path";D();function oS(e){if(!e)return"\u2022";let t=e.toLowerCase();return t.includes("function")||t==="fn"?"\u{1D453}":t.includes("class")?"\u{1D436}":t.includes("method")?"\u{1D45A}":t.includes("type")||t==="interface"||t==="enum"?"\u{1D447}":t.includes("const")||t==="variable"||t==="var"?"\u{1D450}":"\u2022"}function NA(e){let{command:t,query:r,files:n,language:o,max_results:s,exact:i,reranker:a,path:c,...l}=e,d=[];if(t&&d.push(`${t}`),r&&d.push(`"${r}"`),n){let f=Array.isArray(n)?n.join(", "):n;d.push(f)}return o&&d.push(`lang: ${o}`),s&&d.push(`max: ${s}`),i&&d.push("exact"),d.join(" ")}var sS={displayName(){return"Probe"},renderInput(e,{verbose:t}){return NA(e)},renderRejection(){return be(k,{})},renderOutput(e,{verbose:t}={},r){let n=x();if(!e)return be(Oe,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:be(Oe,{flexDirection:"row",children:be(Ce,{color:n.colors.textMuted,children:"No results"})})});if(typeof e=="string"){let s=e.split(`
|
|
432
|
-
`).slice(0,3);return be(Oe,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Ne(Oe,{flexDirection:"column",children:[s.map((i,a)=>be(Ce,{color:n.colors.textMuted,children:i.length>80?i.slice(0,77)+"\u2026":i},a)),e.split(`
|
|
433
|
-
`).length>3&&Ne(Ce,{color:n.colors.textMuted,children:["... (+",e.split(`
|
|
434
|
-
`).length-3," lines)"]})]})})}if(typeof e!="object"||e===null)return be(Oe,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:be(Oe,{flexDirection:"row",children:be(Ce,{color:n.colors.textMuted,children:"No results"})})});let o=e;if(typeof o.raw=="string"){let s=o.raw.split(`
|
|
435
|
-
`).slice(0,3);return be(Oe,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Ne(Oe,{flexDirection:"column",children:[s.map((i,a)=>be(Ce,{color:n.colors.textMuted,children:i.length>80?i.slice(0,77)+"\u2026":i},a)),o.raw.split(`
|
|
436
|
-
`).length>3&&Ne(Ce,{color:n.colors.textMuted,children:["... (+",o.raw.split(`
|
|
437
|
-
`).length-3," lines)"]})]})})}if(Array.isArray(o.symbols)&&o.symbols.length>0){let s=o.symbols.filter(c=>c!=null&&typeof c=="object"),i=5,a=s.slice(0,i);return Ne(Oe,{flexDirection:"column",children:[Ne(Oe,{flexDirection:"row",children:[be(Ce,{children:"Found "}),Ne(Ce,{bold:!0,children:[s.length," "]}),be(Ce,{children:s.length===1?"symbol":"symbols"})]}),a.map((c,l)=>Ne(Oe,{flexDirection:"row",paddingLeft:2,children:[Ne(Ce,{children:[oS(c.kind)," "]}),be(Ce,{bold:!0,children:c.name||"(unnamed)"}),c.line!==void 0&&Ne(Ce,{color:n.colors.textMuted,children:[" :",c.line]})]},l)),s.length>i&&be(Oe,{flexDirection:"row",paddingLeft:2,children:Ne(Ce,{color:n.colors.textMuted,children:["+",s.length-i," more"]})})]})}if(Array.isArray(o.results)&&o.results.length>0){let s=o.results.filter(c=>c!=null&&typeof c=="object"),i=3,a=s.slice(0,i);return Ne(Oe,{flexDirection:"column",children:[Ne(Oe,{flexDirection:"row",children:[be(Ce,{children:"Found "}),Ne(Ce,{bold:!0,children:[s.length," "]}),be(Ce,{children:s.length===1?"result":"results"})]}),a.map((c,l)=>Ne(Oe,{flexDirection:"column",paddingLeft:2,children:[be(Oe,{flexDirection:"row",children:Ne(Ce,{bold:!0,children:[nS(process.cwd(),c.file||""),c.line!==void 0?`:${c.line}`:""]})}),c.code&&be(Ce,{color:n.colors.textMuted,children:c.code.length>60?c.code.slice(0,60)+"\u2026":c.code})]},l)),s.length>i&&be(Oe,{flexDirection:"row",paddingLeft:2,children:Ne(Ce,{color:n.colors.textMuted,children:["+",s.length-i," more"]})})]})}if(Array.isArray(e)){let s=e.filter(l=>l!=null&&typeof l=="object");if(s.length===0)return be(Oe,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:be(Oe,{flexDirection:"row",children:be(Ce,{color:n.colors.textMuted,children:"No results"})})});let i=s[0];if(i.kind!==void 0||i.name&&!i.file){let d=s.slice(0,5);return Ne(Oe,{flexDirection:"column",children:[Ne(Oe,{flexDirection:"row",children:[be(Ce,{children:"Found "}),Ne(Ce,{bold:!0,children:[s.length," "]}),be(Ce,{children:s.length===1?"symbol":"symbols"})]}),d.map((f,u)=>Ne(Oe,{flexDirection:"row",paddingLeft:2,children:[Ne(Ce,{children:[oS(f.kind)," "]}),be(Ce,{bold:!0,children:f.name||"(unnamed)"}),f.line!==void 0&&Ne(Ce,{color:n.colors.textMuted,children:[":",f.line]})]},u)),s.length>5&&be(Oe,{flexDirection:"row",paddingLeft:2,children:Ne(Ce,{color:n.colors.textMuted,children:["+",s.length-5," more"]})})]})}let a=3,c=s.slice(0,a);return Ne(Oe,{flexDirection:"column",children:[Ne(Oe,{flexDirection:"row",children:[be(Ce,{children:"Found "}),Ne(Ce,{bold:!0,children:[s.length," "]}),be(Ce,{children:s.length===1?"result":"results"})]}),c.map((l,d)=>Ne(Oe,{flexDirection:"column",paddingLeft:2,children:[be(Oe,{flexDirection:"row",children:Ne(Ce,{bold:!0,children:[nS(process.cwd(),l.file||l.path||""),l.line!==void 0?`:${l.line}`:""]})}),typeof l.code=="string"&&be(Ce,{color:n.colors.textMuted,children:l.code.length>60?l.code.slice(0,60)+"\u2026":l.code})]},d)),s.length>a&&be(Oe,{flexDirection:"row",paddingLeft:2,children:Ne(Ce,{color:n.colors.textMuted,children:["+",s.length-a," more"]})})]})}return be(Oe,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:be(Oe,{flexDirection:"row",children:be(Ce,{color:n.colors.textMuted,children:"No results"})})})}};import{jsx as No,jsxs as va}from"react/jsx-runtime";import{Box as Lp,Text as fn}from"ink";D();var iS=3,aS={displayName(){return"AST Grep"},renderInput(e,{verbose:t}={verbose:!1}){let r=e.pattern,n=e.language,o=e.rewrite,s=e.path;if(!r)return"(No pattern)";let i="";return o?i=`"${r}" \u2192 "${o}"`:i=`"${r}"`,n&&(i+=` ${n}`),t&&s&&(i+=` @ ${s}`),i},renderRejection(){return No(k,{})},renderOutput(e){let t=x();if(e==null)return No(fn,{color:t.colors.textMuted,children:"(No output)"});let r=e;if(typeof r.raw=="string"){let n=r.raw.split(`
|
|
438
|
-
`),o=n.slice(0,2).join(`
|
|
439
|
-
`),s=n.length-2;return va(Lp,{flexDirection:"column",gap:0,children:[No(fn,{color:t.colors.success,children:"Rewrites applied"}),No(fn,{color:t.colors.textMuted,children:o}),s>0&&va(fn,{color:t.colors.textMuted,children:["... (+",s," lines)"]})]})}if(Array.isArray(r.matches)){let n=r.matches;if(n.length===0)return No(fn,{color:t.colors.textMuted,children:"No matches found"});let o=n.slice(0,iS),s=n.length-iS;return va(Lp,{flexDirection:"column",gap:0,children:[va(fn,{color:t.colors.success,children:[n.length," AST ",n.length===1?"match":"matches"]}),o.map((i,a)=>{let c=i.file,l=i.line,d=i.text,f=c||"unknown";l!=null&&(f+=`:${l}`);let u=d?String(d):"(no text)";return u.length>60&&(u=u.slice(0,57)+"..."),va(Lp,{flexDirection:"row",gap:1,children:[No(fn,{bold:!0,children:f}),No(fn,{color:t.colors.textMuted,children:u})]},a)}),s>0&&va(fn,{color:t.colors.textMuted,children:["+",s," more"]})]})}return No(fn,{children:JSON.stringify(e)})}};import{jsx as K,jsxs as Te,Fragment as vu}from"react/jsx-runtime";import{Box as Re,Text as ne}from"ink";D();function OA(e){if(!e||typeof e!="object")return!1;let t=e;return"definition"in t||"callers"in t||"callees"in t}function jA(e){switch(e?.toLowerCase()){case"function":return"\u{1D453} ";case"class":return"\u{1D436} ";case"method":return"\u{1D45A} ";case"interface":return"\u{1D43C} ";case"enum":return"\u{1D438} ";case"type":return"\u{1D447} ";case"module":return"\u{1F4E6} ";case"file":return"\u{1F4C4} ";default:return"\u2022 "}}function PA(e,t,r){let n=jA(e.label),o=e.file_path?e.file_path.length>40?"\u2026"+e.file_path.slice(-37):e.file_path:"";return Te(Re,{flexDirection:"row",paddingLeft:4,children:[K(ne,{children:n}),K(ne,{bold:!0,children:e.name}),o&&Te(ne,{color:r.colors.textMuted,children:[" (",o,")"]})]},t)}function cS(e,t,r,n){return Te(Re,{flexDirection:"row",paddingLeft:4,children:[Te(ne,{color:n.colors.textMuted,children:[t," "]}),K(ne,{children:e.name}),e.file&&Te(ne,{color:n.colors.textMuted,children:[" (",e.file,")"]})]},r)}function $A(e){return!e||typeof e!="object"?!1:Array.isArray(e.results)}function FA(e){if(!e||typeof e!="object")return!1;let t=e;return Array.isArray(t.inbound)||Array.isArray(t.outbound)||!!t.node}function UA(e){return!e||typeof e!="object"?!1:Array.isArray(e.affected)}function BA(e){return!e||typeof e!="object"?!1:Array.isArray(e.components)}function HA(e){return!e||typeof e!="object"?!1:typeof e.status=="string"}var lS={displayName(){return"Code Graph"},renderInput(e){let t=e.action||"unknown",r=[];e.name&&r.push(`"${e.name}"`),e.file&&r.push(`file: ${e.file}`),e.path&&r.push(`path: ${e.path}`),e.project&&r.push(`project: ${e.project}`),e.query&&r.push(`query: "${e.query}"`),e.depth&&r.push(`depth: ${e.depth}`),e.direction&&r.push(`dir: ${e.direction}`);let n=r.length>0?` ${r.join(" ")}`:"";return`${t}${n}`},renderRejection(){return K(k,{})},renderOutput(e,t,r){let n=x(),o=r?.action||"query";if(!e)return K(Re,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:K(Re,{flexDirection:"row",children:K(ne,{color:n.colors.textMuted,children:"(No results)"})})});if(typeof e=="string"){let a=e.length>100?e.slice(0,97)+"\u2026":e;return K(Re,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:K(Re,{flexDirection:"row",children:Te(ne,{color:n.colors.textMuted,children:[o,": ",a]})})})}if("raw"in e&&typeof e.raw=="string"){let a=e.raw.length>100?e.raw.slice(0,97)+"\u2026":e.raw;return K(Re,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:K(Re,{flexDirection:"row",children:Te(ne,{color:n.colors.textMuted,children:[o,": ",a]})})})}if($A(e)){let a=e.results||[],c=e.total??a.length,l=3,d=a.slice(0,l);return Te(Re,{flexDirection:"column",children:[Te(Re,{flexDirection:"row",children:[K(ne,{bold:!0,children:c}),Te(ne,{children:[" ",c===1?"symbol":"symbols"," found"]})]}),d.map((f,u)=>PA(f,u,n)),a.length>l&&K(Re,{flexDirection:"row",paddingLeft:4,children:Te(ne,{color:n.colors.textMuted,children:["+",a.length-l," more"]})})]})}if(FA(e)){let a=e.inbound||[],c=e.outbound||[],l=3,d=a.slice(0,l),f=c.slice(0,l);return Te(Re,{flexDirection:"column",children:[Te(Re,{flexDirection:"row",children:[K(ne,{children:"Call chain: "}),K(ne,{bold:!0,children:a.length}),K(ne,{children:" inbound, "}),K(ne,{bold:!0,children:c.length}),K(ne,{children:" outbound"})]}),d.length>0&&Te(vu,{children:[K(Re,{flexDirection:"row",paddingLeft:2,children:K(ne,{color:n.colors.textMuted,children:"Callers:"})}),d.map((u,h)=>cS(u,"\u2190",h,n)),a.length>l&&K(Re,{flexDirection:"row",paddingLeft:4,children:Te(ne,{color:n.colors.textMuted,children:["+",a.length-l," more"]})})]}),f.length>0&&Te(vu,{children:[K(Re,{flexDirection:"row",paddingLeft:2,children:K(ne,{color:n.colors.textMuted,children:"Callees:"})}),f.map((u,h)=>cS(u,"\u2192",h,n)),c.length>l&&K(Re,{flexDirection:"row",paddingLeft:4,children:Te(ne,{color:n.colors.textMuted,children:["+",c.length-l," more"]})})]})]})}if(UA(e)){let a=e.affected||[],c=3,l=a.slice(0,c);return Te(Re,{flexDirection:"column",children:[Te(Re,{flexDirection:"row",children:[K(ne,{bold:!0,children:a.length}),Te(ne,{children:[" ",a.length===1?"symbol":"symbols"," affected"]}),e.depth&&Te(vu,{children:[K(ne,{color:n.colors.textMuted,children:" (depth: "}),K(ne,{color:n.colors.textMuted,children:e.depth}),K(ne,{color:n.colors.textMuted,children:")"})]})]}),l.map((d,f)=>Te(Re,{flexDirection:"row",paddingLeft:4,children:[Te(ne,{children:["\u2022 ",d.name]}),d.file&&Te(ne,{color:n.colors.textMuted,children:[" (",d.file,")"]})]},f)),a.length>c&&K(Re,{flexDirection:"row",paddingLeft:4,children:Te(ne,{color:n.colors.textMuted,children:["+",a.length-c," more"]})})]})}if(BA(e)){let a=e.components||[];return K(Re,{flexDirection:"column",children:Te(Re,{flexDirection:"row",children:[K(ne,{children:"Architecture overview"}),a.length>0&&Te(vu,{children:[K(ne,{color:n.colors.textMuted,children:" ("}),K(ne,{color:n.colors.textMuted,children:a.length}),K(ne,{color:n.colors.textMuted,children:" components)"})]})]})})}if(HA(e))return e.status?.toLowerCase().includes("index")&&typeof e.node_count=="number"&&typeof e.edge_count=="number"?K(Re,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Te(Re,{flexDirection:"row",children:[K(ne,{color:n.colors.success,children:"Indexed: "}),K(ne,{bold:!0,children:e.node_count}),K(ne,{children:" nodes, "}),K(ne,{bold:!0,children:e.edge_count}),K(ne,{children:" edges"})]})}):K(Re,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:K(Re,{flexDirection:"row",children:K(ne,{color:n.colors.warning,children:"Not indexed"})})});if(OA(e)){let a=!!e.definition,c=Array.isArray(e.callers)&&e.callers.length>0,l=Array.isArray(e.callees)&&e.callees.length>0;return Te(Re,{flexDirection:"column",children:[K(Re,{flexDirection:"row",children:K(ne,{children:"Context 360\xB0"})}),a&&e.definition&&Te(Re,{flexDirection:"row",paddingLeft:4,children:[K(ne,{color:n.colors.info,children:"\u{1F4CD} "}),K(ne,{children:e.definition.name||"definition"})]}),c&&e.callers&&Te(Re,{flexDirection:"row",paddingLeft:4,children:[K(ne,{color:n.colors.textMuted,children:"\u2190 "}),Te(ne,{children:[e.callers.length," callers"]})]}),l&&e.callees&&Te(Re,{flexDirection:"row",paddingLeft:4,children:[K(ne,{color:n.colors.textMuted,children:"\u2192 "}),Te(ne,{children:[e.callees.length," callees"]})]})]})}let s=JSON.stringify(e),i=s.length>100?s.slice(0,97)+"\u2026":s;return K(Re,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:K(Re,{flexDirection:"row",children:Te(ne,{color:n.colors.textMuted,children:[o,": ",i]})})})}};import{jsx as ve,jsxs as Kn}from"react/jsx-runtime";import{Box as vt,Text as et}from"ink";import{relative as uS}from"path";D();var Fe={File:"\u{1F4C4}",Module:"\u{1F4E6}",Namespace:"\u{1F4E6}",Package:"\u{1F4E6}",Class:"\u{1D436}",Method:"\u{1D45A}",Property:"\u{1F539}",Field:"\u{1F539}",Constructor:"\u2699",Enum:"\u{1F4CB}",Interface:"\u{1D43C}",Function:"\u{1D453}",Variable:"\u{1D463}",Constant:"\u{1F512}",String:'"',Number:"#",Boolean:"\u2713",Array:"[]",Object:"{}",Key:"\u{1F511}",Null:"\u2205",EnumMember:"\u{1F4CB}",Struct:"\u{1F4E6}",Event:"\u26A1",Operator:"\u2295",TypeParameter:"T"};function WA(e){return e.startsWith("file://")?e.slice(7):e}function dS(e,t,r){let n=uS(process.cwd(),WA(e));return t!==void 0&&r!==void 0?`${n}:${t+1}:${r+1}`:t!==void 0?`${n}:${t+1}`:n}function qA(e){let t="";if(typeof e=="string")t=e;else if(e&&typeof e=="object"){let n=e;typeof n.value=="string"&&(t=n.value)}let r=t.split(`
|
|
440
|
-
`);return r.length>0?r[0].trim():""}function GA(e,t=80){return e.length>t?e.slice(0,t-1)+"\u2026":e}var mS={displayName(){return"LSP"},renderInput(e,{verbose:t}){let r=String(e?.action??""),n=String(e?.file??""),o=typeof e?.line=="number"?e.line:void 0,s=typeof e?.character=="number"?e.character:void 0,i=e?.new_name?String(e.new_name):"",a=n?t?n:uS(process.cwd(),n):"";return r==="rename"&&o!==void 0&&s!==void 0&&i?`${r} ${a}:${o+1}:${s+1} \u2192 ${i}`:o!==void 0&&s!==void 0&&a?`${r} ${a}:${o+1}:${s+1}`:a?`${r} ${a}`:r},renderOutput(e,{verbose:t}={},r){let o=String((r??{})?.action??"");if(e==null)return ve(vt,{children:ve(et,{color:x().colors.textMuted,children:"(No result)"})});if(o==="definition"||o==="references"){let s=[];if(e!=null&&typeof e=="object"&&!Array.isArray(e)){let d=e;typeof d.uri=="string"&&(s=[d])}else Array.isArray(e)&&(s=e.map(d=>d!=null&&typeof d=="object"?d:{}));if(s.length===0)return ve(vt,{children:ve(et,{color:x().colors.textMuted,children:"(No result)"})});if(o==="definition"){let d=s[0];if(!d)return ve(vt,{children:ve(et,{color:x().colors.textMuted,children:"(No result)"})});let f=typeof d.uri=="string"?d.uri:"",u=typeof d.range?.start?.line=="number"?d.range.start.line:void 0,h=typeof d.range?.start?.character=="number"?d.range.start.character:void 0;return ve(vt,{children:Kn(et,{children:["\u2192 ",ve(et,{bold:!0,children:dS(f,u,h)})]})})}let i=s.length,a=t?s.length:Math.min(5,s.length),c=s.slice(0,a),l=i>a;return Kn(vt,{flexDirection:"column",children:[ve(vt,{children:Kn(et,{children:[ve(et,{bold:!0,children:i})," reference",i!==1?"s":""]})}),c.length>0&&ve(vt,{flexDirection:"column",marginLeft:2,children:c.map((d,f)=>{if(!d)return null;let u=typeof d.uri=="string"?d.uri:"",h=typeof d.range?.start?.line=="number"?d.range.start.line:void 0,y=typeof d.range?.start?.character=="number"?d.range.start.character:void 0;return ve(et,{color:x().colors.textMuted,children:dS(u,h,y)},f)})}),l&&ve(vt,{marginLeft:2,children:Kn(et,{color:x().colors.textMuted,children:["+",i-a," more"]})})]})}if(o==="hover"){if(e!=null&&typeof e=="object"){let i=e.contents;if(i){let a=qA(i),c=GA(a);return ve(vt,{children:ve(et,{children:ve(et,{bold:!0,children:c})})})}}return ve(vt,{children:ve(et,{color:x().colors.textMuted,children:"(No hover info)"})})}if(o==="symbols"){let s=[];if(Array.isArray(e)&&(s=e.map(f=>f!=null&&typeof f=="object"?f:{})),s.length===0)return ve(vt,{children:ve(et,{color:x().colors.textMuted,children:"(No symbols)"})});let i=s.length,a=t?s.length:Math.min(5,s.length),c=s.slice(0,a),l=i>a,d=f=>typeof f=="string"?Fe[f]||"\u2022":typeof f=="number"&&{1:Fe.File||"\u2022",2:Fe.Module||"\u2022",3:Fe.Namespace||"\u2022",4:Fe.Package||"\u2022",5:Fe.Class||"\u2022",6:Fe.Method||"\u2022",7:Fe.Property||"\u2022",8:Fe.Field||"\u2022",9:Fe.Constructor||"\u2022",10:Fe.Enum||"\u2022",11:Fe.Interface||"\u2022",12:Fe.Function||"\u2022",13:Fe.Variable||"\u2022",14:Fe.Constant||"\u2022",15:Fe.String||"\u2022",16:Fe.Number||"\u2022",17:Fe.Boolean||"\u2022",18:Fe.Array||"\u2022",19:Fe.Object||"\u2022",20:Fe.Key||"\u2022",21:Fe.Null||"\u2022",22:Fe.EnumMember||"\u2022",23:Fe.Struct||"\u2022",24:Fe.Event||"\u2022",25:Fe.Operator||"\u2022",26:Fe.TypeParameter||"\u2022"}[String(f)]||"\u2022";return Kn(vt,{flexDirection:"column",children:[ve(vt,{children:Kn(et,{children:[ve(et,{bold:!0,children:i})," symbol",i!==1?"s":""]})}),c.length>0&&ve(vt,{flexDirection:"column",marginLeft:2,children:c.map((f,u)=>{let h=d(f.kind),y=String(f.name??"");return Kn(et,{children:[h," ",y]},u)})}),l&&ve(vt,{marginLeft:2,children:Kn(et,{color:x().colors.textMuted,children:["+",i-a," more"]})})]})}if(o==="rename"){if(e!=null&&typeof e=="object"){let i=e.changes;if(i!=null&&typeof i=="object"){let a=Object.keys(i).length,c=0;for(let l of Object.values(i))Array.isArray(l)&&(c+=l.length);return ve(vt,{children:Kn(et,{children:["Renamed in ",ve(et,{bold:!0,children:a})," file",a!==1?"s":""," (",ve(et,{bold:!0,children:c})," edit",c!==1?"s":"",")"]})})}}return ve(vt,{children:ve(et,{color:x().colors.textMuted,children:"(Rename failed)"})})}return ve(vt,{children:ve(et,{children:JSON.stringify(e)})})},renderRejection(){return ve(k,{})}};import{jsx as kt,jsxs as Bs}from"react/jsx-runtime";import{Box as Np,Text as at}from"ink";import{relative as ku}from"path";D();var fS={displayName(){return"FastRipgrep"},renderInput(e,{verbose:t}){let{command:r,pattern:n,path:o}=e;if(r==="search"&&n){let s=o?ku(process.cwd(),o):void 0;return`search "${n}"${s||t?` in ${t&&o?o:s||"."}`:""}`}if(r==="status"){let s=o?ku(process.cwd(),o):void 0;return`status${s||t?` for ${t&&o?o:s||"."}`:""}`}if(r==="index"||r==="init"){let s=o?ku(process.cwd(),o):void 0;return`${r}${s||t?` at ${t&&o?o:s||"."}`:""}`}return r==="update"?`update index${o?` at ${t?o:ku(process.cwd(),o)}`:""}`:r},renderRejection(){return kt(k,{})},renderOutput(e){let t=x();if(e==null)return kt(at,{color:t.colors.textMuted,children:"No output"});if(typeof e=="string"){let r=e.trim().split(`
|
|
441
|
-
`);return kt(at,{color:t.colors.textMuted,children:r[0]})}if(typeof e=="object"&&!Array.isArray(e)){let r=e;if(Array.isArray(r.matches)){let n=r.matches,o=new Set,s=0;for(let a of n)typeof a.file=="string"?o.add(a.file):typeof a.path=="string"&&o.add(a.path),s++;let i=o.size;return i===0?kt(at,{color:t.colors.textMuted,children:"No matches"}):Bs(Np,{flexDirection:"row",children:[kt(at,{children:"Found "}),kt(at,{bold:!0,children:s}),Bs(at,{children:[" ",s===1?"match":"matches"," in "]}),kt(at,{bold:!0,children:i}),Bs(at,{children:[" ",i===1?"file":"files"]})]})}if(Array.isArray(r.counts)&&typeof r.total=="number"){let n=r.counts,o=r.total,s=n.length;return s===0?kt(at,{color:t.colors.textMuted,children:"No matches"}):Bs(Np,{flexDirection:"row",children:[kt(at,{children:"Found "}),kt(at,{bold:!0,children:o}),Bs(at,{children:[" ",o===1?"match":"matches"," in "]}),kt(at,{bold:!0,children:s}),Bs(at,{children:[" ",s===1?"file":"files"]})]})}if(typeof r.indexed=="boolean"||typeof r.files=="number"){let n=r.indexed===!0,o=typeof r.files=="number"?r.files:0;return n?Bs(Np,{flexDirection:"row",children:[kt(at,{children:"Index: "}),kt(at,{bold:!0,children:o}),kt(at,{children:" files indexed"})]}):kt(at,{color:t.colors.textMuted,children:"Not indexed"})}return typeof r.message=="string"?kt(at,{color:t.colors.textMuted,children:r.message}):kt(at,{color:t.colors.textMuted,children:"Command completed"})}return kt(at,{color:t.colors.textMuted,children:"Done"})}};import{jsx as Tt,jsxs as ht}from"react/jsx-runtime";import{Box as $r,Text as Ue}from"ink";import{relative as Op}from"path";D();var pS={displayName(){return"Fuzzy Find"},renderInput(e,{verbose:t}){let{action:r,query:n,patterns:o,constraints:s,path:i}=e;if(r==="grep"&&n){let a=`grep "${n}"`;return s&&(a+=` [${s}]`),i&&t&&(a+=` in ${i}`),a}if(r==="find_files"){let a=`find_files${n?` "${n}"`:""}`;return s&&(a+=` [${s}]`),i&&t&&(a+=` in ${i}`),a}if(r==="multi_grep"&&o){let c=`multi_grep ${o.map(l=>`"${l}"`).join(" ")}`;return s&&(c+=` [${s}]`),i&&t&&(c+=` in ${i}`),c}return r},renderRejection(){return Tt(k,{})},renderOutput(e){let t=x();if(e==null)return Tt(Ue,{color:t.colors.textMuted,children:"No results"});if(typeof e=="string"){let r=e.trim().split(`
|
|
442
|
-
`);return Tt(Ue,{color:t.colors.textMuted,children:r[0]})}if(typeof e=="object"&&!Array.isArray(e)){let r=e;if(Array.isArray(r.results)){let n=r.results;if(n.length===0)return Tt(Ue,{color:t.colors.textMuted,children:"No matches"});let o=new Map;for(let l of n){let d=typeof l.file=="string"?l.file:"unknown";o.set(d,(o.get(d)||0)+1)}let s=o.size,i=n.length,a=Array.from(o.entries()).slice(0,3),c=a.map(([l])=>Op(process.cwd(),l));return ht($r,{flexDirection:"column",children:[ht($r,{flexDirection:"row",children:[Tt(Ue,{children:"Found "}),Tt(Ue,{bold:!0,children:i}),ht(Ue,{children:[" ",i===1?"match":"matches"," in "]}),Tt(Ue,{bold:!0,children:s}),ht(Ue,{children:[" ",s===1?"file":"files"]})]}),a.length>0&&ht($r,{flexDirection:"column",marginLeft:2,children:[a.map(([l,d],f)=>ht($r,{flexDirection:"row",children:[ht(Ue,{color:t.colors.textMuted,children:[c[f],": "]}),Tt(Ue,{color:t.colors.textMuted,bold:!0,children:d})]},f)),s>3&&ht(Ue,{color:t.colors.textMuted,children:["... and ",s-3," more"]})]})]})}if(Array.isArray(r.files)){let n=r.files;if(n.length===0)return Tt(Ue,{color:t.colors.textMuted,children:"No files found"});let o=n.slice(0,5).map(s=>Op(process.cwd(),s));return ht($r,{flexDirection:"column",children:[ht($r,{flexDirection:"row",children:[Tt(Ue,{children:"Found "}),Tt(Ue,{bold:!0,children:n.length}),ht(Ue,{children:[" ",n.length===1?"file":"files"]})]}),ht($r,{flexDirection:"column",marginLeft:2,children:[o.map((s,i)=>Tt(Ue,{color:t.colors.textMuted,children:s},i)),n.length>5&&ht(Ue,{color:t.colors.textMuted,children:["... and ",n.length-5," more"]})]})]})}}if(Array.isArray(e)){if(e.length===0)return Tt(Ue,{color:t.colors.textMuted,children:"No results"});if(typeof e[0]=="string"){let r=e,n=r.slice(0,5).map(o=>Op(process.cwd(),o));return ht($r,{flexDirection:"column",children:[ht($r,{flexDirection:"row",children:[Tt(Ue,{children:"Found "}),Tt(Ue,{bold:!0,children:r.length}),ht(Ue,{children:[" ",r.length===1?"file":"files"]})]}),ht($r,{flexDirection:"column",marginLeft:2,children:[n.map((o,s)=>Tt(Ue,{color:t.colors.textMuted,children:o},s)),r.length>5&&ht(Ue,{color:t.colors.textMuted,children:["... and ",r.length-5," more"]})]})]})}return ht($r,{flexDirection:"row",children:[Tt(Ue,{children:"Found "}),Tt(Ue,{bold:!0,children:e.length}),ht(Ue,{children:[" ",e.length===1?"result":"results"]})]})}return Tt(Ue,{color:t.colors.textMuted,children:"Done"})}};import{jsx as Wt,jsxs as Ir}from"react/jsx-runtime";import{Box as el,Text as tt}from"ink";D();var hS={displayName(){return"Serena"},renderInput(e,{verbose:t}){let{action:r,name_path:n,pattern:o,new_name:s,relative_path:i}=e;if(r==="find_symbol"&&n){let a=`find_symbol "${n}"`;return i&&t&&(a+=` in ${i}`),a}if(r==="find_references"&&n)return`find_references "${n}"`;if(r==="search"&&o){let a=`search "${o}"`;return i&&t&&(a+=` in ${i}`),a}return r==="rename"&&n&&s?`rename "${n}" \u2192 "${s}"`:r==="overview"?`overview${i?` of ${i}`:""}`:r==="replace_body"&&n?`replace_body "${n}"`:r==="insert_after"&&n?`insert_after "${n}"`:r==="insert_before"&&n?`insert_before "${n}"`:r},renderRejection(){return Wt(k,{})},renderOutput(e){let t=x();if(e==null)return Wt(tt,{color:t.colors.textMuted,children:"No output"});if(typeof e=="string"){let n=e.trim().split(`
|
|
443
|
-
`).slice(0,2).join(`
|
|
444
|
-
`);return Wt(tt,{color:t.colors.textMuted,children:n})}if(typeof e=="object"&&!Array.isArray(e)){let r=e;if(Array.isArray(r.results)){let n=r.results;if(n.length===0)return Wt(tt,{color:t.colors.textMuted,children:"No results"});let o=n.slice(0,3);return Ir(el,{flexDirection:"column",children:[Ir(el,{flexDirection:"row",children:[Wt(tt,{children:"Found "}),Wt(tt,{bold:!0,children:n.length}),Ir(tt,{children:[" ",n.length===1?"result":"results"]})]}),Ir(el,{flexDirection:"column",marginLeft:2,children:[o.map((s,i)=>{if(s!=null&&typeof s=="object"){let a=s,c=a.name||a.symbol_name||a.qualified_name,l=a.file||a.path;if(c&&l)return Ir(tt,{color:t.colors.textMuted,children:[typeof c=="string"?c:"",typeof l=="string"?` (${l})`:""]},i);if(c)return Wt(tt,{color:t.colors.textMuted,children:typeof c=="string"?c:""},i)}return Ir(tt,{color:t.colors.textMuted,children:["Result ",i+1]},i)}),n.length>3&&Ir(tt,{color:t.colors.textMuted,children:["... and ",n.length-3," more"]})]})]})}if(typeof r.raw=="string"){let o=r.raw.trim().split(`
|
|
445
|
-
`).slice(0,2).join(`
|
|
446
|
-
`);return Wt(tt,{color:t.colors.textMuted,children:o})}if(typeof r.success=="boolean")if(r.success){let n=typeof r.message=="string"?r.message:"Success";return Wt(tt,{color:t.colors.success,children:n})}else{let n=typeof r.error=="string"?r.error:"Failed";return Wt(tt,{color:t.colors.error,children:n})}return typeof r.message=="string"?Wt(tt,{color:t.colors.textMuted,children:r.message}):r.name&&r.kind?Ir(el,{flexDirection:"row",children:[Ir(tt,{color:t.colors.textMuted,children:[typeof r.kind=="string"?r.kind:"Symbol",":"]}),Ir(tt,{children:[" ",typeof r.name=="string"?r.name:""]})]}):Wt(tt,{color:t.colors.textMuted,children:"Completed"})}return Array.isArray(e)?e.length===0?Wt(tt,{color:t.colors.textMuted,children:"No results"}):Ir(el,{flexDirection:"row",children:[Wt(tt,{children:"Found "}),Wt(tt,{bold:!0,children:e.length}),Ir(tt,{children:[" ",e.length===1?"result":"results"]})]}):Wt(tt,{color:t.colors.textMuted,children:"Done"})}};import{jsx as gt,jsxs as gS}from"react/jsx-runtime";import{Box as Fr,Text as pn}from"ink";D();function jp(e,t=60){return e.length>t?e.slice(0,t-1)+"\u2026":e}var wS={displayName(){return"Quip"},renderInput(e,{verbose:t}={}){let r=String(e.action??"read"),n=e.query?jp(String(e.query)):"",o=e.threadId?jp(String(e.threadId)):"",s=[r];return n?s.push(`query: ${n}`):o&&s.push(`threadId: ${o}`),gt(Fr,{flexDirection:"row",children:gt(pn,{children:s.join(", ")})})},renderRejection(){return gt(k,{})},renderOutput(e,{verbose:t}={}){let r=x();if(e==null)return gt(Fr,{flexDirection:"column",children:gt(pn,{color:r.colors.textMuted,children:"(No content)"})});if(typeof e=="string")return gt(Fr,{flexDirection:"column",children:gt(pn,{children:e})});let n=e;if(n.success===!1)return gt(Fr,{flexDirection:"column",children:gt(pn,{color:r.colors.error,children:String(n.message??"Error reading Quip document")})});if(n.success===!0){let o=n.data;if(o?.output&&typeof o.output=="string"){let s=o.output.split(`
|
|
447
|
-
`),a=s.slice(0,2).join(`
|
|
448
|
-
`);return gS(Fr,{flexDirection:"column",children:[gt(Fr,{flexDirection:"row",children:gt(pn,{color:r.colors.textMuted,dimColor:!0,children:jp(a,80)})}),s.length>2&>(Fr,{flexDirection:"row",paddingLeft:0,children:gS(pn,{color:r.colors.textMuted,children:["... (",s.length-2," more lines)"]})})]})}if(n.message)return gt(Fr,{flexDirection:"column",children:gt(pn,{children:String(n.message)})})}return typeof n.message=="string"&&n.message.toLowerCase().includes("created")?gt(Fr,{flexDirection:"column",children:gt(pn,{color:r.colors.success,children:n.message})}):n.message?gt(Fr,{flexDirection:"column",children:gt(pn,{children:String(n.message)})}):gt(Fr,{flexDirection:"column",children:gt(pn,{color:r.colors.textMuted,children:"(No response)"})})}};import{jsx as ct}from"react/jsx-runtime";import{Box as hn,Text as gn}from"ink";D();function yS(e,t=40){return e.length>t?e.slice(0,t-1)+"\u2026":e}var xS={displayName(){return"Quip Comment"},renderInput(e,{verbose:t}={}){let r=e.threadId?yS(String(e.threadId),30):"",n=e.content?yS(String(e.content),40):"",o=[];return r&&o.push(`thread: ${r}`),n&&o.push(`"${n}"`),ct(hn,{flexDirection:"row",children:ct(gn,{children:o.length>0?o.join(" "):"Posting comment..."})})},renderRejection(){return ct(k,{})},renderOutput(e,{verbose:t}={}){let r=x();if(e==null)return ct(hn,{flexDirection:"column",children:ct(gn,{color:r.colors.textMuted,children:"(No response)"})});if(typeof e=="string")return e.toLowerCase().includes("posted")||e.toLowerCase().includes("success")?ct(hn,{flexDirection:"column",children:ct(gn,{color:r.colors.success,children:e})}):ct(hn,{flexDirection:"column",children:ct(gn,{children:e})});let n=e;if(n.success===!1)return ct(hn,{flexDirection:"column",children:ct(gn,{color:r.colors.error,children:String(n.message??"Error posting comment")})});if(n.success===!0){let o=n.message??"Comment posted";return ct(hn,{flexDirection:"column",children:ct(gn,{color:r.colors.success,children:o})})}return n.message?String(n.message).toLowerCase().includes("posted")?ct(hn,{flexDirection:"column",children:ct(gn,{color:r.colors.success,children:String(n.message)})}):String(n.message).toLowerCase().includes("error")||String(n.message).toLowerCase().includes("failed")?ct(hn,{flexDirection:"column",children:ct(gn,{color:r.colors.error,children:String(n.message)})}):ct(hn,{flexDirection:"column",children:ct(gn,{children:String(n.message)})}):ct(hn,{flexDirection:"column",children:ct(gn,{color:r.colors.textMuted,children:"(Comment posted)"})})}};import{jsx as tl,jsxs as Mu}from"react/jsx-runtime";import{Box as SS,Text as ka}from"ink";D();var bS={displayName(){return"Quip Create"},renderInput(e,{verbose:t}={}){let r=typeof e.title=="string"?e.title:"";return Mu(SS,{flexDirection:"row",children:[tl(ka,{children:r?`"${r.slice(0,50)}"`:"new document"}),t&&typeof e.folderId=="string"&&Mu(ka,{color:x().colors.textMuted,children:[" in ",e.folderId]})]})},renderRejection(){return tl(k,{})},renderOutput(e,{verbose:t}={}){let r=x();if(!e||typeof e!="object")return tl(ka,{color:r.colors.textMuted,children:typeof e=="string"?e:"No result"});let n=e,o=n.success!==!1,s=typeof n.message=="string"?n.message:"";return o?Mu(SS,{flexDirection:"row",children:[tl(ka,{color:r.colors.success,children:"\u2713 Document created"}),s&&Mu(ka,{color:r.colors.textMuted,children:[" \u2014 ",s.slice(0,60)]})]}):tl(ka,{color:r.colors.error,children:s||"Failed to create document"})}};import{jsx as Oo,jsxs as Hs}from"react/jsx-runtime";import{Box as Ws,Text as qs}from"ink";D();var TS={displayName(){return"Slack Read"},renderInput(e,{verbose:t}={}){let r=e?.channel??"",n=e?.limit??e?.max_messages??"",o=[];return r&&o.push(`#${String(r).replace(/^#/,"")}`),n&&o.push(`limit:${n}`),o.join(", ")||"Slack messages"},renderRejection(){return Oo(k,{})},renderOutput(e,{verbose:t}={}){let r=x();if(e==null)return Oo(Ws,{flexDirection:"column",children:Oo(qs,{color:r.colors.textMuted,children:"No messages"})});let n=e??{},o=n.data??n,s=Array.isArray(o.messages)?o.messages:[],i=String(o.channelId??o.channel_id??o.channel??"");if(!s.length)return Oo(Ws,{flexDirection:"column",children:Oo(qs,{color:r.colors.textMuted,children:"No messages"})});let a=i?`#${i.replace(/^#/,"")}`:"channel",c=s.length;return Hs(Ws,{flexDirection:"column",children:[Hs(Ws,{marginBottom:1,children:[Hs(qs,{bold:!0,children:[c," "]}),Hs(qs,{children:["message",c===1?"":"s"," from ",a]})]}),s.slice(0,3).map((l,d)=>{let f=l??{},u=String(f.user??f.username??"unknown"),h=String(f.text??f.message??""),y=h.length>60?h.substring(0,60)+"\u2026":h;return Oo(Ws,{flexDirection:"column",paddingLeft:2,marginBottom:d<2?1:0,children:Hs(Ws,{children:[Hs(qs,{bold:!0,children:[u,": "]}),Oo(qs,{dimColor:!0,children:y})]})},d)}),s.length>3&&Oo(Ws,{paddingLeft:2,marginTop:1,children:Hs(qs,{color:r.colors.textMuted,children:["+",s.length-3," more message",s.length-3===1?"":"s"]})})]})}};import{jsx as Gs,jsxs as Du}from"react/jsx-runtime";import{Box as rl,Text as nl}from"ink";D();var ES={displayName(){return"Slack Send"},renderInput(e,{verbose:t}={}){let r=e?.channel??"",n=String(e?.text??""),o=n.length>40?n.substring(0,40)+"\u2026":n,s=[];return r&&s.push(`#${String(r).replace(/^#/,"")}`),o&&s.push(`"${o}"`),s.join(" \u2192 ")||"Send message"},renderRejection(){return Gs(k,{})},renderOutput(e,{verbose:t}={}){let r=x();if(e==null)return Gs(rl,{flexDirection:"column",children:Gs(nl,{color:r.colors.error,children:"Failed to send message"})});let n=e??{},o=n.success!==!1&&n.success!==null,s=String(n.message??n.error??""),i=n.data??n,a=String(i.channelId??i.channel_id??i.channel??""),c=String(i.ts??i.timestamp??"");if(!o)return Gs(rl,{flexDirection:"column",children:Du(nl,{color:r.colors.error,children:["Failed to send message",s?`: ${s}`:""]})});let l=a?`#${a.replace(/^#/,"")}`:"channel";return Du(rl,{flexDirection:"column",children:[Du(rl,{children:[Gs(nl,{color:r.colors.success,children:"\u2713 Sent to "}),Gs(nl,{bold:!0,color:r.colors.success,children:l})]}),c&&t&&Gs(rl,{marginTop:1,paddingLeft:2,children:Du(nl,{color:r.colors.textMuted,children:["timestamp: ",c]})})]})}};import{jsx as ol,jsxs as _S}from"react/jsx-runtime";import{Box as Pp,Text as $p}from"ink";D();var CS={displayName(){return"Slack React"},renderInput(e,{verbose:t}={}){let r=String(e?.name??e?.emoji??""),n=String(e?.channel??""),s=[r.startsWith(":")?r:`:${r}:`];return n&&s.push(`#${n.replace(/^#/,"")}`),s.join(" in ")||"Add reaction"},renderRejection(){return ol(k,{})},renderOutput(e,{verbose:t}={}){let r=x();if(e==null)return ol(Pp,{flexDirection:"column",children:ol($p,{color:r.colors.error,children:"Failed to add reaction"})});let n=e??{},o=n.success!==!1&&n.success!==null,s=String(n.message??n.error??""),i=n.data??n,a=String(i.emoji??i.name??i.reaction??"");if(!o)return ol(Pp,{flexDirection:"column",children:_S($p,{color:r.colors.error,children:["Failed to add reaction",s?`: ${s}`:""]})});let c=a.startsWith(":")?a:`:${a}:`;return ol(Pp,{flexDirection:"column",children:_S($p,{color:r.colors.success,children:["\u2713 Added ",c]})})}};import{jsx as Mt,jsxs as Xs}from"react/jsx-runtime";import{Box as vr,Text as kr}from"ink";D();var RS={displayName(){return"Outlook Read"},renderInput(e,{verbose:t}={}){let r=x(),n=String(e?.folder??""),o=e?.search??e?.search_query,s=e?.filter,i=[];return n&&i.push(`folder: ${n}`),o&&i.push(`search: ${String(o)}`),s&&i.push(`filter: ${String(s)}`),Mt(vr,{flexDirection:"row",children:Mt(kr,{children:i.length>0?i.join(", "):"Reading emails..."})})},renderRejection(){return Mt(k,{})},renderOutput(e,{verbose:t}={}){let r=x();if(e==null)return Mt(vr,{flexDirection:"column",children:Mt(kr,{children:"(No emails found)"})});let n=e;if(n.success===!1)return Mt(vr,{flexDirection:"column",children:Mt(kr,{color:r.colors.error,children:String(n.message??"Error reading emails")})});if(n.success===!0){let o=n.data??{};if(Array.isArray(o?.messages)){let i=o.messages;if(i.length===0)return Mt(vr,{flexDirection:"column",children:Mt(kr,{children:"(No emails)"})});let a=i.length,c=i.slice(0,3);return Xs(vr,{flexDirection:"column",children:[Xs(kr,{children:[a," email",a!==1?"s":""]}),c.map((l,d)=>Mt(vr,{flexDirection:"row",marginTop:0,children:Xs(vr,{children:[Mt(kr,{bold:!0,children:l.subject||"(No subject)"}),l.from&&Xs(kr,{color:r.colors.textMuted,children:[" from ",l.from]})]})},d)),a>3&&Xs(kr,{color:r.colors.textMuted,children:["... and ",a-3," more"]})]})}if(o?.subject){let i=o.subject,a=o?.from;return Xs(vr,{flexDirection:"column",children:[Mt(vr,{flexDirection:"row",children:Mt(kr,{bold:!0,children:String(i)})}),a&&Mt(vr,{flexDirection:"row",children:Xs(kr,{color:r.colors.textMuted,children:["from ",String(a)]})})]})}let s=typeof n.data=="string"?n.data:JSON.stringify(n.data,null,2);return Mt(vr,{flexDirection:"column",children:Mt(kr,{children:s})})}return Mt(vr,{flexDirection:"column",children:Mt(kr,{children:JSON.stringify(e)})})}};import{jsxs as XA,jsx as dr}from"react/jsx-runtime";import{Box as zs,Text as Ks}from"ink";D();var AS={displayName(){return"Outlook Send"},renderInput(e,{verbose:t}={}){let r=x(),n=String(e?.to??""),o=String(e?.subject??"");return o.length>40&&(o=o.substring(0,40)+"..."),dr(zs,{flexDirection:"row",children:XA(Ks,{children:["to: ",n,o&&` \u2014 "${o}"`]})})},renderRejection(){return dr(k,{})},renderOutput(e,{verbose:t}={}){let r=x();if(e==null)return dr(zs,{flexDirection:"column",children:dr(Ks,{color:r.colors.error,children:"Failed to send email"})});let n=e;if(n.success===!1)return dr(zs,{flexDirection:"column",children:dr(Ks,{color:r.colors.error,children:String(n.message??"Failed to send email")})});if(n.success===!0){let o=String(n.message??"Email sent");return dr(zs,{flexDirection:"column",children:dr(Ks,{color:r.colors.success,children:o})})}return typeof e=="string"?e.toLowerCase().includes("sent")||e.toLowerCase().includes("success")?dr(zs,{flexDirection:"column",children:dr(Ks,{color:r.colors.success,children:e})}):dr(zs,{flexDirection:"column",children:dr(Ks,{color:r.colors.error,children:e})}):dr(zs,{flexDirection:"column",children:dr(Ks,{children:JSON.stringify(e)})})}};import{jsx as er,jsxs as zA}from"react/jsx-runtime";import{Box as Vs,Text as jo}from"ink";D();var IS={displayName(){return"Outlook Reply"},renderInput(e,{verbose:t}={}){let r=x(),n=String(e?.messageId??e?.message_id??""),o=!!(e?.replyAll??e?.reply_all??!1),s=n.length>20?n.substring(0,20)+"...":n;return er(Vs,{flexDirection:"row",children:zA(jo,{children:[s,o&&er(jo,{color:r.colors.textMuted,children:" [reply-all]"})]})})},renderRejection(){return er(k,{})},renderOutput(e,{verbose:t}={}){let r=x();if(e==null)return er(Vs,{flexDirection:"column",children:er(jo,{color:r.colors.error,children:"Failed to send reply"})});let n=e;if(n.success===!1)return er(Vs,{flexDirection:"column",children:er(jo,{color:r.colors.error,children:String(n.message??"Failed to send reply")})});if(n.success===!0){let o=String(n.message??"Reply sent");return er(Vs,{flexDirection:"column",children:er(jo,{color:r.colors.success,children:o})})}return typeof e=="string"?e.toLowerCase().includes("sent")||e.toLowerCase().includes("success")||e.toLowerCase().includes("reply")?er(Vs,{flexDirection:"column",children:er(jo,{color:r.colors.success,children:e})}):er(Vs,{flexDirection:"column",children:er(jo,{color:r.colors.error,children:e})}):er(Vs,{flexDirection:"column",children:er(jo,{children:JSON.stringify(e)})})}};import{jsx as Po,jsxs as Ma,Fragment as KA}from"react/jsx-runtime";import{Box as Lu,Text as $o}from"ink";D();function VA(e){return e.startsWith("client-")?e.slice(0,15)+"\u2026":e.replace(/^@/,"")}var vS={displayName(){return"Message"},renderInput(e){let t=String(e?.to??""),r=e?.type??"quest",n=[];return t&&n.push(`@${VA(t)}`),r&&r!=="quest"&&n.push(String(r)),n.join(" ")||"Send message"},renderRejection(){return Po(k,{})},renderOutput(e,{verbose:t}={},r){let n=x(),o=String(r?.content??"");if(e==null)return Ma(Lu,{flexDirection:"column",children:[Po($o,{color:n.colors.error,children:"Failed to send message"}),o&&Po($o,{dimColor:!0,children:o})]});let s=e??{},i=s.success!==!1&&s.success!==null,a=String(s.message??s.error??""),c=s.data??s,l=String(c.messageId??c.message_id??c.id??"");return i?Ma(Lu,{flexDirection:"column",children:[Ma(Lu,{children:[Po($o,{color:n.colors.success,children:"\u2713 Sent"}),l&&Ma(KA,{children:[Po($o,{children:" "}),Po($o,{color:n.colors.textMuted,dimColor:!0,children:l})]})]}),o&&Po($o,{children:o})]}):Ma(Lu,{flexDirection:"column",children:[Ma($o,{color:n.colors.error,children:["\u2717 ",a||"Failed to deliver"]}),o&&Po($o,{dimColor:!0,children:o})]})}};import{jsx as tr,jsxs as Ys}from"react/jsx-runtime";import{Box as Fo,Text as Ur}from"ink";D();function YA({msg:e}){let{contentWidth:t}=To(),r=String(e.from??e.sender??"Unknown"),n=String(e.content??e.text??""),o=St(n,{width:t,mode:"final"}),s=process.platform==="darwin"?"\u23FA":"\u25CF";return Ys(Fo,{flexDirection:"column",children:[Ys(Fo,{flexDirection:"row",marginBottom:1,children:[tr(Ur,{children:"\u{1F4EC} "}),tr(Ur,{bold:!0,color:"cyan",children:r})]}),Ys(Fo,{flexDirection:"row",children:[tr(Fo,{minWidth:2,children:tr(Ur,{color:"cyan",children:s})}),tr(Fo,{flexShrink:1,width:t,children:tr(Ur,{children:o})})]})]})}function JA({msg:e,verbose:t}){let r=x(),n=String(e.from??e.sender??"Unknown"),o=String(e.type??"quest"),s=String(e.content??e.text??""),i=t||s.length<=80?s:s.substring(0,80)+"\u2026";return Ys(Fo,{flexDirection:"row",children:[tr(Ur,{bold:!0,children:n}),tr(Ur,{children:" "}),Ys(Ur,{color:r.colors.textMuted,children:["[",o,"]"]}),tr(Ur,{children:" "}),tr(Ur,{children:i})]})}function QA(e){if(e==null)return[];let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return[]}let r=t.data??t;return Array.isArray(r.messages)?r.messages:[]}var kS={displayName(){return"Inbox"},renderInput(e){let t=e?.from,r=e?.type,n=e?.unreadOnly,o=[];return t&&o.push(`from: ${String(t)}`),r&&o.push(`type: [${String(r)}]`),n===!0&&o.push("unread only"),o.length>0?o.join(" "):"Check messages"},renderRejection(){return tr(k,{})},renderOutput(e,{verbose:t}={}){let r=x(),n=QA(e);if(n.length===0)return tr(Ur,{color:r.colors.textMuted,children:"No messages"});let o=n[0];if(n.length===1&&o&&o.type==="incoming")return tr(YA,{msg:o});let s=n.length;return Ys(Fo,{flexDirection:"column",children:[Ys(Ur,{children:[s," message",s!==1?"s":""]}),tr(Fo,{flexDirection:"column",marginTop:1,paddingLeft:2,children:n.map((i,a)=>tr(JA,{msg:i,verbose:t??!1},a))})]})}};import{jsx as Uo,jsxs as Nu}from"react/jsx-runtime";import{Box as Ou,Text as Js}from"ink";D();var MS={displayName(){return"Search Messages"},renderInput(e,{verbose:t}={}){let r=String(e?.query??"");return r?`"${r}"`:"Search messages"},renderRejection(){return Uo(k,{})},renderOutput(e,{verbose:t}={}){let r=x();if(e==null)return Uo(Js,{color:r.colors.textMuted,children:"No results"});let n=e??{},o=n.data??n,s=Array.isArray(o.messages)?o.messages:Array.isArray(o.results)?o.results:[];if(!s||s.length===0)return Uo(Js,{color:r.colors.textMuted,children:"No results"});let i=s.length,a=Math.min(3,s.length),c=s.slice(0,a);return Nu(Ou,{flexDirection:"column",children:[Nu(Js,{children:[i," result",i!==1?"s":""]}),c.length>0&&Uo(Ou,{flexDirection:"column",marginTop:1,paddingLeft:2,children:c.map((l,d)=>{let f=String(l.from??l.sender??"Unknown"),u=String(l.content??l.text??""),h=u.length>40?u.substring(0,40)+"\u2026":u;return Nu(Ou,{flexDirection:"row",children:[Uo(Js,{bold:!0,children:f}),Uo(Js,{children:" "}),Uo(Js,{color:r.colors.textMuted,children:h})]},d)})}),s.length>a&&Uo(Ou,{marginTop:1,paddingLeft:2,children:Nu(Js,{color:r.colors.textMuted,children:["... and ",s.length-a," more"]})})]})}};import{jsx as Bo,jsxs as ju}from"react/jsx-runtime";import{Box as Pu,Text as Qs}from"ink";D();var DS={displayName(){return"Thread"},renderInput(e,{verbose:t}={}){let r=String(e?.messageId??e?.message_id??"");return r?`messageId: ${r}`:"Get thread"},renderRejection(){return Bo(k,{})},renderOutput(e,{verbose:t}={}){let r=x();if(e==null)return Bo(Qs,{color:r.colors.textMuted,children:"No messages in thread"});let n=e??{},o=n.data??n,s=Array.isArray(o.messages)?o.messages:[];if(!s||s.length===0)return Bo(Qs,{color:r.colors.textMuted,children:"No messages in thread"});let i=s.length,a=Math.min(3,s.length),c=s.slice(0,a);return ju(Pu,{flexDirection:"column",children:[ju(Qs,{children:[i," message",i!==1?"s":""," in thread"]}),c.length>0&&Bo(Pu,{flexDirection:"column",marginTop:1,paddingLeft:2,children:c.map((l,d)=>{let f=String(l.from??l.sender??"Unknown"),u=String(l.content??l.text??""),h=u.length>40?u.substring(0,40)+"\u2026":u;return ju(Pu,{flexDirection:"row",children:[Bo(Qs,{bold:!0,children:f}),Bo(Qs,{children:" "}),Bo(Qs,{color:r.colors.textMuted,children:h})]},d)})}),s.length>a&&Bo(Pu,{marginTop:1,paddingLeft:2,children:ju(Qs,{color:r.colors.textMuted,children:["... and ",s.length-a," more"]})})]})}};import{jsx as Zs,jsxs as $u}from"react/jsx-runtime";import{Box as sl,Text as il}from"ink";D();var LS={displayName(){return"Clients"},renderInput(e,{verbose:t}={}){return"List clients"},renderRejection(){return Zs(k,{})},renderOutput(e,{verbose:t}={}){let r=x();if(e==null)return Zs(sl,{flexDirection:"column",children:Zs(il,{children:"No clients connected"})});let n=e??{},o=n.data??n,s=Array.isArray(o.clients)?o.clients:[];if(!s||s.length===0)return Zs(sl,{flexDirection:"column",children:Zs(il,{children:"No clients connected"})});let i=s.length,a=s.map(c=>String(c.name??c.displayName??c.id??"Unknown")).slice(0,10);return $u(sl,{flexDirection:"column",children:[$u(il,{children:[i," client",i!==1?"s":""," connected"]}),a.length>0&&Zs(sl,{flexDirection:"column",marginTop:1,paddingLeft:2,children:a.map((c,l)=>$u(il,{color:r.colors.textMuted,children:["\u2022 ",c]},l))}),s.length>10&&Zs(sl,{marginTop:1,paddingLeft:2,children:$u(il,{color:r.colors.textMuted,children:["... and ",s.length-10," more"]})})]})}};import{jsx as ur,Fragment as ZA,jsxs as NS}from"react/jsx-runtime";import{Box as Ho,Text as Da}from"ink";D();var OS={displayName(){return"Remote Delegate"},renderInput(e,t={}){let r=[];if(e.node_id&&r.push(e.node_id),e.task){let n=e.task.length>40?`${e.task.slice(0,40)}...`:e.task;r.push(n)}return r.length>0?r.join(": "):Object.entries(e).map(([n,o])=>`${n}: ${JSON.stringify(o)}`).join(", ")},renderRejection(){return ur(k,{})},renderOutput(e,t={}){let r=x();return e?typeof e=="string"?ur(Ho,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:ur(Ho,{flexDirection:"row",children:ur(Da,{children:e})})}):e.error?ur(Ho,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:ur(Ho,{flexDirection:"row",children:ur(Da,{color:r.colors.error,children:e.error})})}):ur(Ho,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:NS(Ho,{flexDirection:"row",children:[ur(Da,{color:r.colors.success,children:"Delegated to node"}),e.quest_id&&NS(ZA,{children:[ur(Da,{children:" "}),ur(Da,{color:r.colors.textMuted,children:e.quest_id})]})]})}):ur(Ho,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:ur(Ho,{flexDirection:"row",children:ur(Da,{color:r.colors.textMuted,children:"(No content)"})})})}};import{jsx as wr}from"react/jsx-runtime";import{Box as Wo,Text as Fu}from"ink";D();var jS={displayName(){return"Pause"},renderInput(e,t={}){return e.id?e.id:Object.entries(e).map(([r,n])=>`${r}: ${JSON.stringify(n)}`).join(", ")},renderRejection(){return wr(k,{})},renderOutput(e,t={}){let r=x();return e?typeof e=="string"?wr(Wo,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:wr(Wo,{flexDirection:"row",children:wr(Fu,{children:e})})}):e.error?wr(Wo,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:wr(Wo,{flexDirection:"row",children:wr(Fu,{color:r.colors.error,children:e.error})})}):wr(Wo,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:wr(Wo,{flexDirection:"row",children:wr(Fu,{color:r.colors.success,children:"Paused"})})}):wr(Wo,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:wr(Wo,{flexDirection:"row",children:wr(Fu,{color:r.colors.textMuted,children:"(No content)"})})})}};import{jsx as mr,Fragment as eI,jsxs as PS}from"react/jsx-runtime";import{Box as qo,Text as La}from"ink";D();var $S={displayName(){return"Resume"},renderInput(e,t={}){return e.id?e.id:Object.entries(e).map(([r,n])=>`${r}: ${JSON.stringify(n)}`).join(", ")},renderRejection(){return mr(k,{})},renderOutput(e,t={}){let r=x();return e?typeof e=="string"?mr(qo,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:mr(qo,{flexDirection:"row",children:mr(La,{children:e})})}):e.error?mr(qo,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:mr(qo,{flexDirection:"row",children:mr(La,{color:r.colors.error,children:e.error})})}):mr(qo,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:PS(qo,{flexDirection:"row",children:[mr(La,{color:r.colors.success,children:"Resumed"}),e.quest_id&&PS(eI,{children:[mr(La,{children:" "}),mr(La,{color:r.colors.textMuted,children:e.quest_id})]})]})}):mr(qo,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:mr(qo,{flexDirection:"row",children:mr(La,{color:r.colors.textMuted,children:"(No content)"})})})}};import{jsx as Et,jsxs as FS}from"react/jsx-runtime";import{Box as yr,Text as ei}from"ink";D();var US={displayName(){return"Quest Report"},renderInput(e,t={}){return e.quest_id?e.quest_id:Object.entries(e).map(([r,n])=>`${r}: ${JSON.stringify(n)}`).join(", ")},renderRejection(){return Et(k,{})},renderOutput(e,t={}){let r=x();if(!e)return Et(yr,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Et(yr,{flexDirection:"row",children:Et(ei,{color:r.colors.textMuted,children:"(No content)"})})});if(typeof e=="string")return Et(yr,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Et(yr,{flexDirection:"row",children:Et(ei,{children:e})})});if(e.error)return Et(yr,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Et(yr,{flexDirection:"row",children:Et(ei,{color:r.colors.error,children:e.error})})});if(e.data){let{commits:n,filesChanged:o,cost:s}=e.data,i=[];return n!==void 0&&i.push(`${n} commit${n!==1?"s":""}`),o!==void 0&&i.push(`${o} file${o!==1?"s":""} changed`),FS(yr,{flexDirection:"column",children:[i.length>0&&Et(yr,{flexDirection:"row",children:Et(ei,{children:i.join(", ")})}),s!==void 0&&Et(yr,{flexDirection:"row",children:FS(ei,{color:r.colors.textMuted,children:["Cost: ",s]})})]})}return e.message?Et(yr,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Et(yr,{flexDirection:"row",children:Et(ei,{children:e.message})})}):Et(yr,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Et(yr,{flexDirection:"row",children:Et(ei,{color:r.colors.textMuted,children:"(No data)"})})})}};import{jsx as rt,jsxs as BS}from"react/jsx-runtime";import{Box as rr,Text as Go}from"ink";D();var HS={displayName(){return"Network"},renderInput(e,t={}){return e.action?e.action:Object.entries(e).map(([r,n])=>`${r}: ${JSON.stringify(n)}`).join(", ")},renderRejection(){return rt(k,{})},renderOutput(e,t={}){let r=x();if(!e)return rt(rr,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:rt(rr,{flexDirection:"row",children:rt(Go,{color:r.colors.textMuted,children:"(No content)"})})});if(typeof e=="string")return rt(rr,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:rt(rr,{flexDirection:"row",children:rt(Go,{children:e})})});if(e.error)return rt(rr,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:rt(rr,{flexDirection:"row",children:rt(Go,{color:r.colors.error,children:e.error})})});if(e.inviteToken){let n=e.inviteToken.length>20?`${e.inviteToken.slice(0,20)}...`:e.inviteToken;return rt(rr,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:rt(rr,{flexDirection:"row",children:rt(Go,{color:r.colors.success,children:n})})})}if(e.peers&&Array.isArray(e.peers)){let n=e.peers.map(o=>o.displayName||o.nodeId||"unknown").slice(0,3);return BS(rr,{flexDirection:"column",children:[rt(rr,{flexDirection:"row",children:BS(Go,{children:[e.peers.length," peer",e.peers.length!==1?"s":""]})}),n.length>0&&rt(rr,{flexDirection:"row",children:rt(Go,{color:r.colors.textMuted,children:n.join(", ")})})]})}return e.message?rt(rr,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:rt(rr,{flexDirection:"row",children:rt(Go,{children:e.message})})}):rt(rr,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:rt(rr,{flexDirection:"row",children:rt(Go,{color:r.colors.success,children:"Success"})})})}};import{jsx as _t,jsxs as WS}from"react/jsx-runtime";import{Box as xr,Text as ti}from"ink";D();var qS={displayName(){return"Deploy"},renderInput(e,t={}){let r=[];return e.target&&r.push(e.target),e.branch&&r.push(`(${e.branch})`),r.length>0?r.join(" "):Object.entries(e).map(([n,o])=>`${n}: ${JSON.stringify(o)}`).join(", ")},renderRejection(){return _t(k,{})},renderOutput(e,t={}){let r=x();return e?typeof e=="string"?_t(xr,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:_t(xr,{flexDirection:"row",children:_t(ti,{children:e})})}):e.error?_t(xr,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:_t(xr,{flexDirection:"row",children:_t(ti,{color:r.colors.error,children:e.error})})}):e.host&&e.port?WS(xr,{flexDirection:"column",children:[_t(xr,{flexDirection:"row",children:WS(ti,{color:r.colors.success,children:["Deployed to ",e.host,":",e.port]})}),e.fingerprint&&_t(xr,{flexDirection:"row",children:_t(ti,{color:r.colors.textMuted,children:e.fingerprint})})]}):e.message?_t(xr,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:_t(xr,{flexDirection:"row",children:_t(ti,{children:e.message})})}):_t(xr,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:_t(xr,{flexDirection:"row",children:_t(ti,{color:r.colors.success,children:"Deployed"})})}):_t(xr,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:_t(xr,{flexDirection:"row",children:_t(ti,{color:r.colors.textMuted,children:"(No content)"})})})}};import{jsx as Ct,jsxs as GS}from"react/jsx-runtime";import{Box as Sr,Text as ri}from"ink";D();var XS={displayName(){return"History"},renderInput(e,t={}){let r=[];return e.action&&r.push(e.action),e.query&&r.push(`"${e.query}"`),r.length>0?r.join(" "):Object.entries(e).map(([n,o])=>`${n}: ${JSON.stringify(o)}`).join(", ")},renderRejection(){return Ct(k,{})},renderOutput(e,t={}){let r=x();if(!e)return Ct(Sr,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Ct(Sr,{flexDirection:"row",children:Ct(ri,{color:r.colors.textMuted,children:"(No content)"})})});if(typeof e=="string")return Ct(Sr,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Ct(Sr,{flexDirection:"row",children:Ct(ri,{children:e})})});if(e.error)return Ct(Sr,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Ct(Sr,{flexDirection:"row",children:Ct(ri,{color:r.colors.error,children:e.error})})});if(e.data?.sessions&&Array.isArray(e.data.sessions)){let n=e.data.sessions,o=n.slice(0,3).map(s=>{let i=s.title||s.id||"untitled";return Ut(i.slice(0,50))});return GS(Sr,{flexDirection:"column",children:[Ct(Sr,{flexDirection:"row",children:GS(ri,{children:[n.length," session",n.length!==1?"s":""]})}),o.length>0&&Ct(Sr,{flexDirection:"row",children:Ct(ri,{color:r.colors.textMuted,children:o.join(", ")})})]})}return e.message?Ct(Sr,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Ct(Sr,{flexDirection:"row",children:Ct(ri,{children:e.message})})}):Ct(Sr,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:Ct(Sr,{flexDirection:"row",children:Ct(ri,{color:r.colors.success,children:"Success"})})})}};import{jsx as br}from"react/jsx-runtime";import{Box as Xo,Text as Uu}from"ink";D();var zS={displayName(){return"Restart"},renderInput(e,t={}){return e.reason?e.reason:Object.entries(e).map(([r,n])=>`${r}: ${JSON.stringify(n)}`).join(", ")},renderRejection(){return br(k,{})},renderOutput(e,t={}){let r=x();return e?typeof e=="string"?br(Xo,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:br(Xo,{flexDirection:"row",children:br(Uu,{children:e})})}):e.error?br(Xo,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:br(Xo,{flexDirection:"row",children:br(Uu,{color:r.colors.error,children:e.error})})}):br(Xo,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:br(Xo,{flexDirection:"row",children:br(Uu,{color:r.colors.warning,children:"Restarting..."})})}):br(Xo,{justifyContent:"space-between",overflowX:"hidden",width:"100%",children:br(Xo,{flexDirection:"row",children:br(Uu,{color:r.colors.textMuted,children:"(No content)"})})})}};var al={bash:Eo,exec:Eo,spawn:Eo,execute_command:Eo,file_edit:nu,edit_file:nu,file_read:mp,read_file:mp,file_write:hp,write_file:hp,grep:ox,search:Jx,glob:ix,web_search:Cx,rg:eS,ug:rS,frg:fS,fff:pS,probe:sS,sg:aS,lsp:mS,cbm:lS,serena:hS,list_dir:lu,ls:lu,web_fetch:Tx,browse:_x,recall:uu,recall_knowledge:uu,remember:Yc,forget:Yc,reflect:Yc,memory_read:uu,memory_write:Yc,learn:Rx,learn_tool:Ix,learn_skill:kx,create_tool:Mx,create_skill:Lx,use_skill:Ox,ask_user:Fx,quest_list:jx,quest_update:Px,kill:Eo,write_stdin:Eo,list_processes:lu,wait_process:Eo,spawn_worker:zx,apply_patch:nu,delegate_arion:xp,check_delegation:Kx,hatch_arion:Ux,rest_arion:Hx,wake_arion:qx,retire_arion:Xx,mcp:lx,think:mx,agent:xp,notebook_read:px,notebook_edit:hx,architect:yx,sticker_request:Sx,browser:Vx,process:Yx,self_diagnose:Qx,check_quip_documents:wS,send_quip_comment:xS,create_quip_document:bS,check_slack_messages:TS,send_slack_message:ES,react_slack_message:CS,check_outlook_messages:RS,send_outlook_message:AS,reply_outlook_message:IS,send_message:vS,check_messages:kS,search_messages:MS,get_thread:DS,list_clients:LS,delegate_remote:OS,pause_delegation:jS,resume_delegation:$S,quest_report:US,manage_network:HS,deploy:qS,session_history:XS,restart:zS};var rI=5;function YS({item:e,verbose:t}){let r=al[e.toolName.toLowerCase()],n=process.stdout.columns||80,o=Math.max(n-rI,1),s={terminalWidth:n,contentWidth:o};if(e.id.includes("synthetic_inbox_")&&e.output!=null)return Br(eu,{value:s,children:Up(r,e.output,t,e.input)??Br(Fp,{children:typeof e.output=="string"?e.output:JSON.stringify(e.output)})});let i=VS(()=>r?.displayName(e.input))??e.toolName,a=VS(()=>r?.renderInput(e.input,{verbose:t}));return tI(KS,{flexDirection:"column",children:[Br(qy,{displayName:i,args:a,status:e.status,durationMs:e.durationMs,verbose:t}),e.output!=null&&e.status!=="error"&&Br(np,{children:Br(eu,{value:s,children:Up(r,e.output,t,e.input)??Br(Fp,{children:typeof e.output=="string"?e.output:JSON.stringify(e.output)})})}),e.status==="error"&&Br(np,{children:Br(eu,{value:s,children:e.output!=null&&Up(r,e.output,t,e.input)||Br(Fp,{color:"red",children:e.error??"Tool error"})})}),t&&e.usage&&Br(KS,{marginLeft:2,children:Br(zy,{durationMs:e.durationMs,usage:{inputTokens:e.usage.inputTokens??0,outputTokens:e.usage.outputTokens??0,totalTokens:(e.usage.inputTokens??0)+(e.usage.outputTokens??0),estimatedCost:0}})})]})}function VS(e){try{return e()}catch{return}}function Up(e,t,r,n){if(!e?.renderOutput)return null;try{return e.renderOutput(t,{verbose:r},n)??null}catch{return null}}D();var Bu=JS.memo(function({item:t,displayMode:r,showPrefix:n,previewTailLines:o}){let s=r==="debug",{columns:i}=ft();switch(t.kind){case"user-message":return Hr(Vd,{param:{type:"text",text:t.text},userName:t.userName,columns:i,addMargin:n,showPrefix:n});case"user-image":return Hr(jy,{dataUri:t.dataUri,userName:t.userName,showPrefix:n});case"assistant-text":{let a=process.platform==="darwin"?"\u23FA":"\u25CF",c=t.arion?.color??"cyan",l=Math.max(i-4,20),d=St(t.text,{width:l,mode:t.committed?"final":"streaming"}),f=!t.committed&&o?Math.max(o-(n&&t.arion?1:0),1):void 0,u=f!=null?oI(d,l,f):d;return Wr(zo,{flexDirection:"column",children:[n&&t.arion&&Wr(zo,{flexDirection:"row",marginBottom:1,children:[Wr(wn,{children:[t.arion.emoji," "]}),Hr(wn,{bold:!0,color:c,children:t.arion.name})]}),Wr(zo,{flexDirection:"row",children:[Hr(zo,{minWidth:2,children:Hr(wn,{color:c,children:a})}),Hr(zo,{flexShrink:1,width:l,children:Hr(wn,{children:u})})]})]})}case"thinking":return!t.content&&t.durationSec!=null?Wr(zo,{flexDirection:"column",children:[n&&t.arion&&Wr(zo,{flexDirection:"row",marginBottom:1,children:[Wr(wn,{children:[t.arion.emoji," "]}),Hr(wn,{bold:!0,color:t.arion.color,children:t.arion.name})]}),Wr(wn,{dimColor:!0,children:["\u273B"," Thought for ",t.durationSec.toFixed(1),"s"]})]}):t.content?Hr(Zf,{content:t.content,expanded:s,durationSeconds:t.durationSec,arionName:n?t.arion?.name:void 0,arionEmoji:n?t.arion?.emoji:void 0,arionColor:n?t.arion?.color:void 0,isLive:!t.committed}):null;case"tool-execution":return Hr(YS,{item:t,verbose:s});case"error":{let a=x();return Wr(zo,{flexDirection:"column",children:[Hr(wn,{color:a.colors.error,children:t.message}),t.suggestion&&Wr(wn,{dimColor:!0,children:[" Suggestion: ",t.suggestion]})]})}case"handoff":return Wr(wn,{dimColor:!0,children:[t.direction==="outgoing"?"\u2192":"\u2190"," Handoff to ",t.target]})}});function oI(e,t,r){return e.split(`
|
|
449
|
-
`).flatMap(o=>nI(o,t,{hard:!1,trim:!1,wordWrap:!0}).split(`
|
|
450
|
-
`)).slice(-r).join(`
|
|
451
|
-
`)}function Bp(e,t){return t==="debug"?e:e.flatMap(r=>r.kind==="thinking"?t==="minimal"?[]:r.durationSec==null?[]:[{...r,content:""}]:[r])}D();import{jsx as QS,jsxs as iX}from"react/jsx-runtime";import{Box as sI,Text as iI}from"ink";import{useEffect as aI,useRef as lX,useState as cI}from"react";var ZS=process.platform==="darwin"?["\xB7","\u2722","\u2733","\u2217","\u273B","\u273D"]:["\xB7","\u2722","*","\u2217","\u273B","\u273D"],mX=Fc.map(e=>e.present);function Na(){let e=[...ZS,...[...ZS].reverse()],[t,r]=cI(0);return aI(()=>{let n=setInterval(()=>{r(o=>(o+1)%e.length)},120);return()=>clearInterval(n)},[e.length]),QS(sI,{flexWrap:"nowrap",height:1,width:2,children:QS(iI,{color:x().colors.primary,children:e[t]})})}D();import{jsxs as yn,jsx as nr}from"react/jsx-runtime";import{useEffect as lI,useRef as Hp,useState as Wp}from"react";import{Box as qr,Text as Mr,useInput as eb}from"ink";import{loginWithGitHubCopilotDeviceFlow as dI}from"@aria-cli/auth";function qp({provider:e,profileLabel:t,onCancel:r,isActive:n=!0,onComplete:o,verificationUri:s,userCode:i,onApprove:a}){let c=x(),[l,d]=Wp("starting"),[f,u]=Wp(""),[h,y]=Wp(null),S=Hp(!1),R=Hp(!1),I=Hp(null),v=process.stdin.isTTY??!1;return eb((C,T)=>{de(C,T)&&(I.current?.abort(),r())},{isActive:n&&v}),eb((C,T)=>{(T.return||C==="\r")&&(!s||!i||!a||(d("starting"),Promise.resolve(a()).catch(E=>{let _=E instanceof Error?E.message:String(E);u(_),d("error")})))},{isActive:n&&v}),lI(()=>{if(S.current)return;if(S.current=!0,s&&i&&a){y({verificationUri:s,userCode:i,expiresAt:Date.now()+5*6e4,intervalMs:5e3}),d("waiting");return}let C=new AbortController;return I.current=C,d("starting"),dI({profileLabel:t,signal:C.signal,onDeviceCode:T=>{y(T),d("waiting")}}).then(T=>{R.current||C.signal.aborted||(T.success?(d("success"),R.current=!0,setTimeout(()=>{o?.({success:!0,message:T.message})},1e3)):(u(T.message),d("error")))},T=>{if(R.current||C.signal.aborted)return;let E=T instanceof Error?T.message:String(T);u(E),d("error")}),()=>{C.abort()}},[a,o,t,i,s]),yn(qr,{flexDirection:"column",borderStyle:"round",borderColor:c.colors.secondary,paddingX:1,paddingY:1,width:64,children:[nr(qr,{marginBottom:1,children:yn(Mr,{bold:!0,children:["Sign in to ",e]})}),t&&nr(qr,{marginBottom:1,children:yn(Mr,{color:c.colors.textMuted,children:["Profile: github-copilot:",t]})}),l==="starting"&&yn(qr,{gap:1,children:[nr(Na,{}),nr(Mr,{children:"Requesting GitHub device code..."})]}),l==="waiting"&&h&&yn(qr,{flexDirection:"column",children:[nr(Mr,{children:"Authorize this device in your browser:"}),nr(qr,{marginTop:1,children:nr(Mr,{color:c.colors.primary,children:h.verificationUri})}),nr(qr,{marginTop:1,children:yn(Mr,{children:["Code: ",nr(Mr,{bold:!0,children:h.userCode})]})}),yn(qr,{marginTop:1,gap:1,children:[nr(Na,{}),nr(Mr,{children:s&&i&&a?"Press Enter after approving in GitHub, or Esc to cancel.":"Waiting for GitHub authorization..."})]})]}),l==="success"&&yn(Mr,{color:c.colors.success,children:["\u2713"," Logged in to ",e]}),l==="error"&&yn(qr,{flexDirection:"column",children:[yn(Mr,{color:c.colors.error,children:["\u2717"," ",f]}),nr(qr,{marginTop:1,children:nr(Mr,{color:c.colors.textMuted,children:"Press Esc to dismiss"})})]}),l!=="success"&&l!=="error"&&nr(qr,{marginTop:1,children:nr(Mr,{color:c.colors.textMuted,children:"Esc Cancel"})})]})}D();import{jsxs as cl,jsx as Oa}from"react/jsx-runtime";import{useRef as tb,useState as uI}from"react";import{Box as Hu,Text as ja,useInput as mI}from"ink";function fI({status:e}){let t=x();return e==="connected"?cl(ja,{color:t.colors.success,children:["\u2713"," available"]}):cl(ja,{color:t.colors.textMuted,children:["\xB7"," requires login"]})}function Gp({options:e,onSelect:t,onCancel:r,isActive:n=!0}){let o=x(),[s,i]=uI(0),a=tb(0),c=tb(!1),l=process.stdin.isTTY??!1,d=f=>{i(u=>{let h=f(u);return a.current=h,h})};return mI((f,u)=>{c.current||(u.upArrow?d(h=>Math.max(0,h-1)):u.downArrow?d(h=>Math.min(e.length-1,h+1)):u.return?(c.current=!0,t(e[a.current])):de(f,u)&&(c.current=!0,r()))},{isActive:n&&l}),cl(Hu,{flexDirection:"column",borderStyle:"round",borderColor:o.colors.secondary,paddingX:1,paddingY:1,width:72,children:[Oa(Hu,{marginBottom:1,children:Oa(ja,{bold:!0,children:"Select GitHub Copilot login source:"})}),e.map((f,u)=>{let h=u===s,y=h?"\u25B8":" ";return cl(Hu,{gap:1,children:[Oa(ja,{color:h?o.colors.primary:void 0,children:y}),Oa(ja,{color:h?o.colors.primary:void 0,bold:h,children:f.label.padEnd(44)}),Oa(fI,{status:f.status})]},f.id)}),Oa(Hu,{marginTop:1,children:cl(ja,{color:o.colors.textMuted,children:["\u2191\u2193"," Navigate Enter Select Esc Cancel"]})})]})}D();import{jsx as Ko,jsxs as ll}from"react/jsx-runtime";import{useState as Wu,useEffect as pI,useRef as rb,useCallback as hI}from"react";import{Box as qu,Text as Vn,useInput as gI,useStdout as wI}from"ink";import yI from"gradient-string";var xI=` \xB7 \xB7
|
|
452
|
-
\xB7 \xB7
|
|
453
|
-
( \u{1F98B} )
|
|
454
|
-
\xB7 \xB7
|
|
455
|
-
\xB7 \xB7`,nb=` \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557
|
|
456
|
-
\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557
|
|
457
|
-
\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551
|
|
458
|
-
\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551
|
|
459
|
-
\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551
|
|
460
|
-
\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D`,SI="\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",bI="A R I A",TI="\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",EI="\u2726 Adaptive Reasoning Intelligence Agent \u2726";function Xp({onComplete:e,skipAnimation:t=!1,version:r="1.0.0",whatsNew:n=[]}){let o=x(),{stdout:s}=wI(),i=s?.columns||80,[a,c]=Wu(t?"complete":"butterfly"),[l,d]=Wu(t),[f,u]=Wu(t),[h,y]=Wu(t),S=rb(!1),R=rb([]),I=hI(()=>{S.current||(S.current=!0,e())},[e]);gI(()=>{a!=="complete"&&(R.current.forEach(clearTimeout),R.current=[],c("complete"),d(!0),u(!0),y(!0),I())}),pI(()=>{if(t){I();return}let T=[];return T.push(setTimeout(()=>{c("logo"),d(!0)},400)),T.push(setTimeout(()=>{c("gradient"),y(!0)},800)),T.push(setTimeout(()=>{c("tagline"),u(!0)},1200)),T.push(setTimeout(()=>{c("complete"),I()},1600)),R.current=T,()=>{T.forEach(clearTimeout)}},[t,I]);let v=yI([o.banner.gradient.start,o.banner.gradient.middle,o.banner.gradient.end]),C=()=>l?h?v(nb):nb:null;return ll(qu,{flexDirection:"column",alignItems:"center",width:i,paddingY:1,children:[Ko(Vn,{color:o.colors.primary,children:xI}),l&&Ko(Vn,{children:C()}),f&&ll(qu,{flexDirection:"column",alignItems:"center",children:[Ko(Vn,{dimColor:!0,children:SI}),Ko(Vn,{bold:!0,children:bI}),Ko(Vn,{dimColor:!0,children:TI}),Ko(Vn,{color:o.colors.primary,children:EI})]}),f&&Ko(qu,{marginTop:1,children:ll(Vn,{dimColor:!0,children:["v",r]})}),f&&n.length>0&&ll(qu,{flexDirection:"column",alignItems:"center",marginTop:1,children:[Ko(Vn,{bold:!0,color:o.colors.secondary,children:"What's New"}),n.map((T,E)=>ll(Vn,{dimColor:!0,children:["\u2022 ",T]},E))]})]})}D();import{jsxs as OX,jsx as jX}from"react/jsx-runtime";import{Box as $X,Text as FX,useStdout as UX}from"ink";D();import{jsx as qX,jsxs as GX}from"react/jsx-runtime";import{Box as zX,Text as KX}from"ink";D();import{jsx as QX,jsxs as ZX}from"react/jsx-runtime";import{useState as t3,useRef as r3}from"react";import{Box as o3,Text as s3,useInput as i3}from"ink";D();import{jsx as Vo,jsxs as Gu}from"react/jsx-runtime";import{useState as CI,useRef as ob}from"react";import{Box as dl,Text as ni,useInput as RI}from"ink";import{AUTONOMY_LEVELS as Xu}from"@aria-cli/aria";var AI={minimal:"Confirm all tool calls",balanced:"Confirm dangerous only",high:"Auto-approve everything",full:"Auto-approve everything"};function zp({currentLevel:e,onSelect:t,onCancel:r,isActive:n=!0}){let o=x(),s=Xu.indexOf(e),i=s>=0?s:0,[a,c]=CI(i),l=ob(i),d=ob(!1),f=h=>{c(y=>{let S=h(y);return l.current=S,S})},u=process.stdin.isTTY??!1;return RI((h,y)=>{d.current||(y.upArrow?f(S=>Math.max(0,S-1)):y.downArrow?f(S=>Math.min(Xu.length-1,S+1)):y.return?(d.current=!0,t(Xu[l.current])):de(h,y)&&(d.current=!0,r()))},{isActive:n&&u}),Gu(dl,{flexDirection:"column",borderStyle:"round",borderColor:o.colors.secondary,paddingX:1,paddingY:1,width:48,children:[Vo(dl,{marginBottom:1,children:Vo(ni,{bold:!0,children:"Autonomy Level"})}),Vo(dl,{marginBottom:1,children:Gu(ni,{children:["Current: ",Vo(ni,{bold:!0,children:e})]})}),Xu.map((h,y)=>{let S=y===a,R=S?"\u25CF":"\u25CB",I=h==="high"||h==="full";return Gu(dl,{gap:1,children:[Vo(ni,{color:S?o.colors.primary:void 0,children:R}),Vo(ni,{color:S?o.colors.primary:I?o.colors.warning:void 0,bold:S,children:h.padEnd(10)}),Vo(ni,{color:o.colors.textMuted,children:AI[h]})]},h)}),Vo(dl,{marginTop:1,children:Gu(ni,{color:o.colors.textMuted,children:["\u2191\u2193"," Navigate Enter Select Esc Cancel"]})})]})}D();import{jsxs as x3,jsx as S3}from"react/jsx-runtime";import{Box as T3,Text as E3}from"ink";D();import{jsx as oi,jsxs as zu}from"react/jsx-runtime";import{Box as Ku,Text as si}from"ink";var II=1,vI=20,Kp={model_call:"model_call",tool_execution:"tool_exec",handoff:"handoff",approval:"approval",session_phase:"session",runner_phase:"runner"};function kI(e){if(e<1e3)return`${Math.round(e)}ms`;if(e<6e4)return`${(e/1e3).toFixed(1)}s`;let t=Math.floor(e/6e4),r=Math.round(e%6e4/1e3);return`${t}m ${r}s`}function sb(e,t,r){let n=Math.round(t*e),o=Math.max(II,Math.round(r*e)),s=Math.max(0,e-n-o);return"\u2591".repeat(n)+"\u2588".repeat(o)+"\u2591".repeat(s)}function Vp({spans:e,width:t}){let r=x(),n=t??vI,o=e.filter(d=>d.endTime!==void 0||d.durationMs!==void 0);if(o.length===0)return oi(Ku,{children:oi(si,{dimColor:!0,children:"(no completed spans)"})});let s=o.map(d=>{let f=d.durationMs??d.endTime-d.startTime,u=d.endTime??d.startTime+f;return{...d,durationMs:f,endTime:u}}),i=Math.min(...s.map(d=>d.startTime)),c=Math.max(...s.map(d=>d.endTime))-i;if(c<=0)return oi(Ku,{flexDirection:"column",children:s.map(d=>zu(si,{dimColor:!0,children:[Kp[d.spanType]??d.spanType," ","\u2588"," 0ms (",d.name,")"]},d.spanId))});let l=Math.max(...s.map(d=>{let f=Kp[d.spanType]??d.spanType;return(d.parentSpanId!==void 0?2:0)+f.length}));return oi(Ku,{flexDirection:"column",children:s.map(d=>{let f=d.parentSpanId!==void 0,u=f?" ":"",h=Kp[d.spanType]??d.spanType,y=(u+h).padEnd(l),S=(d.startTime-i)/c,R=d.durationMs/c,I=sb(n,S,R),v=kI(d.durationMs),C=d.spanType==="tool_execution"&&d.name?` (${d.name})`:"";return zu(Ku,{children:[zu(si,{color:r.colors.textMuted,children:[" ",y]}),oi(si,{children:" "}),oi(si,{color:f?r.colors.info:r.colors.success,children:I}),oi(si,{children:" "}),zu(si,{dimColor:!0,children:[v,C]})]},d.spanId)})})}D();import{jsxs as Pa}from"react/jsx-runtime";import{Box as ib,Text as Vu}from"ink";function ab(e){return e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(2)}s`}function Yp({report:e}){let t=x();return!e||e.phases.length===0?null:Pa(ib,{flexDirection:"column",marginTop:1,children:[Pa(Vu,{color:t.colors.textMuted,children:[" Pipeline timing (",ab(e.totalMs),")"]}),e.phases.map(r=>Pa(ib,{children:[Pa(Vu,{color:t.colors.info,children:[" ",r.phase.padEnd(24)]}),Pa(Vu,{color:t.colors.text,children:[" ",ab(r.durationMs)]}),Pa(Vu,{color:t.colors.textMuted,children:[" (",r.pct,"%)"]})]},`${r.phase}:${r.durationMs}`))]})}D();import{jsxs as cb,jsx as MI}from"react/jsx-runtime";import{useRef as DI}from"react";import{Box as LI,Text as lb}from"ink";import NI from"gradient-string";var Jp=["#5f97cd","#7baed4","#97c4db","#7baed4"],db=process.platform==="darwin"?["\xB7","\u2722","\u2733","\u2217","\u273B","\u273D"]:["\xB7","\u2722","*","\u2217","\u273B","\u273D"];function ub(e){if(e<60)return`${e}s`;let t=Math.floor(e/60),r=e%60;return`${t}m ${r}s`}function OI(e){return e>=1e3?`${(e/1e3).toFixed(1)}k tokens`:`${e} tokens`}function Qp({state:e,elapsedSeconds:t,totalTokens:r,thoughtForSeconds:n,currentVerb:o}){let s=[...db,...[...db].reverse()],i=Math.floor(Date.now()/120)%s.length,a=DI(Nr().present),c=o||a.current,l=x(),d=i%Jp.length,f=[...Jp.slice(d),...Jp.slice(0,d)],u=NI(f),h=`${s[i]} ${c}\u2026`,y=u(h),S=ub(t),R=OI(r),I;return e==="thinking"?I="(thinking)":n&&n>0?I=`(${S} \xB7 \u2193 ${R} \xB7 thought for ${ub(n)})`:I=`(${S} \xB7 \u2193 ${R} \xB7 esc to cancel)`,cb(LI,{flexDirection:"row",marginTop:1,children:[cb(lb,{children:[y," "]}),MI(lb,{color:l.colors.textMuted,children:I})]})}import{jsx as Wv}from"react/jsx-runtime";import{useInput as qv}from"ink";D();import{jsx as Qu,jsxs as ch}from"react/jsx-runtime";import{Box as bb,Text as Tb}from"ink";import{useMemo as iv}from"react";import{basename as av,extname as cv,isAbsolute as lv,resolve as lh}from"path";D();import{jsxs as fb,jsx as mb}from"react/jsx-runtime";import{Box as jI,Text as pb}from"ink";function Zp(e){return e>=70?"high":e>=30?"moderate":"low"}function PI(e){let t=x();switch(e){case"low":return{highlightColor:t.colors.success,textColor:t.colors.primary};case"moderate":return{highlightColor:t.colors.warning,textColor:t.colors.warning};case"high":return{highlightColor:t.colors.error,textColor:t.colors.error}}}function xn(e){if(e===null)return x().colors.primary;let t=Zp(e);return PI(t).textColor}function $I({riskScore:e}){let t=Zp(e);return fb(pb,{color:xn(e),children:["Risk: ",t]})}function Gr({title:e,riskScore:t}){return fb(jI,{flexDirection:"column",children:[mb(pb,{bold:!0,color:x().colors.primary,children:e}),t!==null&&mb($I,{riskScore:t})]})}import{jsx as Ju,jsxs as UI}from"react/jsx-runtime";import{existsSync as BI,readFileSync as HI}from"fs";import{useMemo as hb}from"react";D();import{Box as eh,Text as WI}from"ink";import{relative as qI}from"path";import{structuredPatch as FI}from"diff";function Yu(e,t,r,n=3){let o=FI(e,e,t,r,"","",{context:n}),s=0,i=0,a=o.hunks.map(c=>{let l=[],d=c.oldStart,f=c.newStart;for(let u of c.lines){let h=u.slice(1);u.startsWith("+")?(l.push({type:"added",content:h,newLineNo:f++}),s++):u.startsWith("-")?(l.push({type:"removed",content:h,oldLineNo:d++}),i++):l.push({type:"unchanged",content:h,oldLineNo:d++,newLineNo:f++})}return{oldStart:c.oldStart,oldLines:c.oldLines,newStart:c.newStart,newLines:c.newLines,lines:l}});return{filePath:e,hunks:a,additions:s,deletions:i}}function gb({file_path:e,new_string:t,old_string:r,verbose:n,useBorder:o=!0,width:s}){let i=hb(()=>BI(e)?HI(e,"utf8"):"",[e]),a=hb(()=>{let c=i.replace(r,t);return Yu(e,i,c)},[e,i,r,t]);return Ju(eh,{flexDirection:"column",children:UI(eh,{borderColor:x().colors.secondary,borderStyle:o?"round":void 0,flexDirection:"column",paddingX:1,children:[Ju(eh,{paddingBottom:1,children:Ju(WI,{bold:!0,children:n?e:qI(process.cwd(),e)})}),Ju(Is,{diff:a,dim:!1,width:s,showHeader:!1})]})})}import dv from"chalk";import{jsx as ah,Fragment as rv,jsxs as nv}from"react/jsx-runtime";import{Box as ov,Text as sv}from"ink";D();import{jsx as th,jsxs as GI}from"react/jsx-runtime";import{Box as XI,Text as rh}from"ink";var zI="\u276F",KI="\u25BE",VI="\u2714";function wb({isFocused:e,isSelected:t,smallPointer:r,children:n}){let o=x();return GI(XI,{gap:1,children:[e&&th(rh,{color:o.colors.primary,children:r?KI:zI}),th(rh,{color:e?o.colors.primary:void 0,bold:t,children:n}),t&&th(rh,{color:o.colors.success,children:VI})]})}import{isDeepStrictEqual as YI}from"node:util";import{useReducer as JI,useCallback as oh,useMemo as QI,useState as ZI,useEffect as sh}from"react";var ul=class extends Map{first;constructor(t){let r=[],n,o,s=0;for(let i of t){let a={...i,previous:o,next:void 0,index:s};o&&(o.next=a),n||=a;let c="value"in i?i.value:nh(i);r.push([c,a]),s++,o=a}super(r),this.first=n}};var ev=(e,t)=>{switch(t.type){case"focus-next-option":{if(!e.focusedValue)return e;let r=e.optionMap.get(e.focusedValue);if(!r)return e;let n=r.next;for(;n&&!("value"in n);)n=n.next;if(!n)return e;if(!(n.index>=e.visibleToIndex))return{...e,focusedValue:n.value};let s=Math.min(e.optionMap.size,e.visibleToIndex+1),i=s-e.visibleOptionCount;return{...e,focusedValue:n.value,visibleFromIndex:i,visibleToIndex:s}}case"focus-previous-option":{if(!e.focusedValue)return e;let r=e.optionMap.get(e.focusedValue);if(!r)return e;let n=r.previous;for(;n&&!("value"in n);)n=n.previous;if(!n)return e;if(!(n.index<=e.visibleFromIndex))return{...e,focusedValue:n.value};let s=Math.max(0,e.visibleFromIndex-1),i=s+e.visibleOptionCount;return{...e,focusedValue:n.value,visibleFromIndex:s,visibleToIndex:i}}case"select-focused-option":return{...e,previousValue:e.value,value:e.focusedValue};case"reset":return t.state;case"set-focus":return{...e,focusedValue:t.value}}},ih=e=>e.flatMap(t=>{if("options"in t){let r=ih(t.options),n=r.flatMap(s=>"value"in s?s.value:[]);return[...t.header!==void 0?[{header:t.header,optionValues:n}]:[],...r]}return t}),yb=({visibleOptionCount:e,defaultValue:t,options:r})=>{let n=ih(r),o=typeof e=="number"?Math.min(e,n.length):n.length,s=new ul(n),i=s.first,a=i&&"value"in i?i.value:void 0;return{optionMap:s,visibleOptionCount:o,focusedValue:a,visibleFromIndex:0,visibleToIndex:o,previousValue:t,value:t}},xb=({visibleOptionCount:e=5,options:t,defaultValue:r,onChange:n,onFocus:o,focusValue:s})=>{let i=ih(t),[a,c]=JI(ev,{visibleOptionCount:e,defaultValue:r,options:t},yb),[l,d]=ZI(i);i!==l&&!YI(i,l)&&(c({type:"reset",state:yb({visibleOptionCount:e,defaultValue:r,options:t})}),d(i));let f=oh(()=>{c({type:"focus-next-option"})},[]),u=oh(()=>{c({type:"focus-previous-option"})},[]),h=oh(()=>{c({type:"select-focused-option"})},[]),y=QI(()=>i.map((S,R)=>({...S,index:R})).slice(a.visibleFromIndex,a.visibleToIndex),[i,a.visibleFromIndex,a.visibleToIndex]);return sh(()=>{a.value&&a.previousValue!==a.value&&n?.(a.value)},[a.previousValue,a.value,t,n]),sh(()=>{a.focusedValue&&o?.(a.focusedValue)},[a.focusedValue,o]),sh(()=>{s&&c({type:"set-focus",value:s})},[s]),{focusedValue:a.focusedValue,visibleFromIndex:a.visibleFromIndex,visibleToIndex:a.visibleToIndex,value:a.value,visibleOptions:y,focusNextOption:f,focusPreviousOption:u,selectFocusedOption:h}};import{useInput as tv}from"ink";var Sb=({isDisabled:e=!1,state:t})=>{tv((r,n)=>{n.downArrow&&t.focusNextOption(),n.upArrow&&t.focusPreviousOption(),n.return&&t.selectFocusedOption()},{isActive:!e})};D();var nh=e=>`HEADER-${e.optionValues.join(",")}`;function Xr({isDisabled:e=!1,visibleOptionCount:t=5,highlightText:r,options:n,defaultValue:o,onChange:s,onFocus:i,focusValue:a}){let c=xb({visibleOptionCount:t,options:n,defaultValue:o,onChange:s,onFocus:i,focusValue:a});Sb({isDisabled:e,state:c});let l=x();return ah(ov,{flexDirection:"column",children:c.visibleOptions.map(d=>{let f="value"in d?d.value:nh(d),u=!e&&c.focusedValue!==void 0&&("value"in d?c.focusedValue===d.value:d.optionValues.includes(c.focusedValue)),h=!!c.value&&("value"in d?c.value===d.value:d.optionValues.includes(c.value)),y="header"in d,S="label"in d?d.label:d.header,R=S;if(r&&S.includes(r)){let I=S.indexOf(r);R=nv(rv,{children:[S.slice(0,I),ah(sv,{color:l.colors.primary,bold:!0,children:r}),S.slice(I+r.length)]})}return ah(wb,{isFocused:u,isSelected:h,smallPointer:y,children:R},f)})})}function uv(e){return(lv(e)?lh(e):lh(process.cwd(),e)).startsWith(lh(process.cwd()))}function mv(e){let t=uv(e)?[{label:"Yes, and don't ask again this session",value:"yes-dont-ask-again"}]:[];return[{label:"Yes",value:"yes"},...t,{label:`No, and provide instructions (${dv.bold.hex(x().colors.warning)("esc")})`,value:"no"}]}function Eb({toolUseConfirm:e,onDone:t,verbose:r}){let{columns:n}=ft(),{file_path:o,new_string:s,old_string:i}=e.input,a=iv(()=>({completion_type:"str_replace_single",language_name:fv(o)}),[o]);return ch(bb,{flexDirection:"column",borderStyle:"round",borderColor:xn(e.riskScore),marginTop:1,paddingLeft:1,paddingRight:1,paddingBottom:1,children:[Qu(Gr,{title:"Edit file",riskScore:e.riskScore}),Qu(gb,{file_path:o,new_string:s,old_string:i,verbose:r,width:n-12}),ch(bb,{flexDirection:"column",children:[ch(Tb,{children:["Do you want to make this edit to ",Qu(Tb,{bold:!0,children:av(o)}),"?"]}),Qu(Xr,{options:mv(o),onChange:c=>{switch(c){case"yes":t(),e.onAllow("temporary");break;case"yes-dont-ask-again":t(),e.onAllow("permanent");break;case"no":t(),e.onReject();break}}})]})]})}function fv(e){let t=cv(e);return t?t.slice(1):"unknown"}import{jsx as pl,jsxs as dh}from"react/jsx-runtime";import{Box as uh,Text as mh}from"ink";import{useMemo as hv}from"react";D();import ml from"chalk";D();function pv(e){let r=e.replace(/'[^']*'/g,"").replace(/"[^"]*"/g,"");return!!(/&&|\|\||[;|]/.test(r)||/`/.test(r)||/\$\(/.test(r))}function _b({toolUseConfirm:e,command:t}){let r=!pv(t)&&e.commandPrefix&&!e.commandPrefix.commandInjectionDetected,n=fl(e),o=r&&n!==null,s=[];return o?s=[{label:`Yes, and don't ask again for ${ml.bold(n)} commands in ${ml.bold(process.cwd())}`,value:"yes-dont-ask-again-prefix"}]:r&&(s=[{label:`Yes, and don't ask again for ${ml.bold(t)} commands in ${ml.bold(process.cwd())}`,value:"yes-dont-ask-again-full"}]),[{label:"Yes",value:"yes"},...s,{label:`No, and provide instructions (${ml.bold.hex(x().colors.warning)("esc")})`,value:"no"}]}function Cb({toolUseConfirm:e,onDone:t}){let r=x(),{command:n}=e.tool.inputSchema.parse(e.input),o=hv(()=>({completion_type:"tool_use_single",language_name:"none"}),[]);return dh(uh,{flexDirection:"column",borderStyle:"round",borderColor:r.colors.primary,marginTop:1,paddingLeft:1,paddingRight:1,paddingBottom:1,children:[pl(Gr,{title:"Bash command",riskScore:e.riskScore}),dh(uh,{flexDirection:"column",paddingX:2,paddingY:1,children:[pl(mh,{children:e.tool.renderToolUseMessage({command:n},{verbose:!1})}),pl(mh,{color:r.colors.textMuted,children:e.description})]}),dh(uh,{flexDirection:"column",children:[pl(mh,{children:"Do you want to proceed?"}),pl(Xr,{options:_b({toolUseConfirm:e,command:n}),onChange:s=>{switch(s){case"yes":e.onAllow("temporary"),t();break;case"yes-dont-ask-again-prefix":{fl(e)!==null&&(e.onAllow("permanent"),t());break}case"yes-dont-ask-again-full":e.onAllow("permanent"),t();break;case"no":e.onReject(),t();break}}})]})]})}D();import{jsx as hl,jsxs as em}from"react/jsx-runtime";import{Box as fh,Text as tm}from"ink";import{useMemo as gv}from"react";import ph from"chalk";function rm({toolUseConfirm:e,onDone:t,verbose:r}){let n=x(),o=e.tool.userFacingName(e.input),s=o.endsWith(" (MCP)")?o.slice(0,-6):o,i=gv(()=>({completion_type:"tool_use_single",language_name:"none"}),[]);return em(fh,{flexDirection:"column",borderStyle:"round",borderColor:xn(e.riskScore),marginTop:1,paddingLeft:1,paddingRight:1,paddingBottom:1,children:[hl(Gr,{title:"Tool use",riskScore:e.riskScore}),em(fh,{flexDirection:"column",paddingX:2,paddingY:1,children:[em(tm,{children:[s,"(",e.tool.renderToolUseMessage(e.input,{verbose:r}),")",o.endsWith(" (MCP)")?hl(tm,{color:n.colors.textMuted,children:" (MCP)"}):""]}),hl(tm,{color:n.colors.textMuted,children:e.description})]}),em(fh,{flexDirection:"column",children:[hl(tm,{children:"Do you want to proceed?"}),hl(Xr,{options:[{label:"Yes",value:"yes"},{label:`Yes, and don't ask again for ${ph.bold(s)} commands in ${ph.bold(process.cwd())}`,value:"yes-dont-ask-again"},{label:`No, and provide instructions (${ph.bold.hex(x().colors.warning)("esc")})`,value:"no"}],onChange:a=>{switch(a){case"yes":e.onAllow("temporary"),t();break;case"yes-dont-ask-again":e.onAllow("permanent"),t();break;case"no":e.onReject(),t();break}}})]})]})}D();import{jsx as gl,jsxs as gh}from"react/jsx-runtime";import{Box as wh,Text as Ib}from"ink";import{useMemo as vb}from"react";import{basename as Ev,extname as _v}from"path";import{existsSync as Cv}from"fs";import Rv from"chalk";import{jsx as nm,jsxs as wv}from"react/jsx-runtime";import{existsSync as yv,readFileSync as xv}from"fs";import{useMemo as hh}from"react";D();import{Box as Rb,Text as Sv}from"ink";import{extname as bv,relative as Tv}from"path";function Ab({file_path:e,content:t,verbose:r,width:n}){let o=hh(()=>yv(e),[e]),s=hh(()=>o?xv(e,"utf8"):"",[e,o]),i=hh(()=>o?Yu(e,s,t):null,[o,e,s,t]);return wv(Rb,{borderColor:x().colors.secondary,borderStyle:"round",flexDirection:"column",paddingX:1,children:[nm(Rb,{paddingBottom:1,children:nm(Sv,{bold:!0,children:r?e:Tv(process.cwd(),e)})}),i?nm(Is,{diff:i,dim:!1,width:n,showHeader:!1}):nm(jr,{code:t||"(No content)",language:bv(e).slice(1)})]})}function kb({toolUseConfirm:e,onDone:t,verbose:r}){let{file_path:n,content:o}=e.input,s=vb(()=>Cv(n),[n]),i=vb(()=>({completion_type:"write_file_single",language_name:Av(n)}),[n]),{columns:a}=ft();return gh(wh,{flexDirection:"column",borderStyle:"round",borderColor:xn(e.riskScore),marginTop:1,paddingLeft:1,paddingRight:1,paddingBottom:1,children:[gl(Gr,{title:`${s?"Edit":"Create"} file`,riskScore:e.riskScore}),gl(wh,{flexDirection:"column",children:gl(Ab,{file_path:n,content:o,verbose:r,width:a-12})}),gh(wh,{flexDirection:"column",children:[gh(Ib,{children:["Do you want to ",s?"make this edit to":"create"," ",gl(Ib,{bold:!0,children:Ev(n)}),"?"]}),gl(Xr,{options:[{label:"Yes",value:"yes"},{label:"Yes, and don't ask again this session",value:"yes-dont-ask-again"},{label:`No, and provide instructions (${Rv.bold.hex(x().colors.warning)("esc")})`,value:"no"}],onChange:c=>{switch(c){case"yes":e.onAllow("temporary"),t();break;case"yes-dont-ask-again":e.onAllow("permanent"),t();break;case"no":e.onReject(),t();break}}})]})]})}function Av(e){let t=_v(e);return t?t.slice(1):"unknown"}D();import{jsx as $a,jsxs as yh}from"react/jsx-runtime";import{Box as xh,Text as Mb}from"ink";import{useMemo as Iv}from"react";import vv from"chalk";import{isAbsolute as kv,resolve as Db}from"path";function om(e){return kv(e)?Db(e):Db(process.cwd(),e)}function Mv(e){return om(e).startsWith(om(process.cwd()))}var Dv=!1;function Lv(){Dv=!0}var Nv=new Set(["Edit","file_edit","str_replace_editor","Write","file_write","create_file","Read","file_read","read_file"]),Ov=new Set(["Glob","glob","Grep","grep","LS","ls"]),jv=new Set(["NotebookEdit","notebook_edit","NotebookRead","notebook_read"]),Pv=new Set(["Glob","glob","Grep","grep","LS","ls"]);function $v(e){let t=e.tool.name;return Nv.has(t)?"file_path":Ov.has(t)?"path":jv.has(t)?"notebook_path":null}function Fv(e){return Pv.has(e.tool.name)}function Uv(e){let t=$v(e),r=e.input;return t&&t in r?typeof r[t]=="string"?om(r[t]):om(process.cwd()):null}function Lb({toolUseConfirm:e,onDone:t,verbose:r}){let n=Uv(e);return n?$a(Hv,{toolUseConfirm:e,path:n,onDone:t,verbose:r}):$a(rm,{toolUseConfirm:e,onDone:t,verbose:r})}function Bv(e,t){return e.tool.isReadOnly()?[]:Mv(t)?[{label:"Yes, and don't ask again for file edits this session",value:"yes-dont-ask-again"}]:[]}function Hv({toolUseConfirm:e,path:t,onDone:r,verbose:n}){let o=e.tool.userFacingName(e.input),i=`${e.tool.isReadOnly()?"Read":"Edit"} ${Fv(e)?"files":"file"}`,a=Iv(()=>({completion_type:"tool_use_single",language_name:"none"}),[]);return yh(xh,{flexDirection:"column",borderStyle:"round",borderColor:xn(e.riskScore),marginTop:1,paddingLeft:1,paddingRight:1,paddingBottom:1,children:[$a(Gr,{title:i,riskScore:e.riskScore}),$a(xh,{flexDirection:"column",paddingX:2,paddingY:1,children:yh(Mb,{children:[o,"(",e.tool.renderToolUseMessage(e.input,{verbose:n}),")"]})}),yh(xh,{flexDirection:"column",children:[$a(Mb,{children:"Do you want to proceed?"}),$a(Xr,{options:[{label:"Yes",value:"yes"},...Bv(e,t),{label:`No, and provide instructions (${vv.bold.hex(x().colors.warning)("esc")})`,value:"no"}],onChange:c=>{switch(c){case"yes":e.onAllow("temporary"),r();break;case"yes-dont-ask-again":Lv(),e.onAllow("permanent"),r();break;case"no":e.onReject(),r();break}}})]})]})}var Gv=new Set(["Edit","file_edit","str_replace_editor"]),Xv=new Set(["Write","file_write","create_file"]),zv=new Set(["Bash","bash","execute_command"]),Kv=new Set(["Glob","glob","Grep","grep","LS","ls","Read","file_read","read_file","NotebookRead","notebook_read","NotebookEdit","notebook_edit"]);function Vv(e){return Gv.has(e)?Eb:Xv.has(e)?kb:zv.has(e)?Cb:Kv.has(e)?Lb:rm}function fl(e){return e.commandPrefix&&!e.commandPrefix.commandInjectionDetected&&e.commandPrefix.commandPrefix||null}function Sh({toolUseConfirm:e,onDone:t,verbose:r}){qv((o,s)=>{s.ctrl&&o==="c"&&(t(),e.onReject())});let n=Vv(e.tool.name);return Wv(n,{toolUseConfirm:e,onDone:t,verbose:r})}import{jsx as sm,jsxs as Fa}from"react/jsx-runtime";import{useState as Nb,useEffect as Ob}from"react";import{Box as im,Text as Ua,useInput as Yv}from"ink";function bh(e){return/\s/.test(e.trimStart())}function Jv(e){return e.trimStart().split(/\s+/,1)[0]??""}function Th({commands:e,initialFilter:t="",onSelect:r,onHandOffInput:n,onCancel:o}){let[s,i]=Nb(0),[a,c]=Nb(t),l=Jv(a).toLowerCase(),d=e.filter(h=>h.name.toLowerCase().includes(l));Ob(()=>{i(h=>Math.min(h,Math.max(0,d.length-1)))},[d.length]),Ob(()=>{!n||!bh(a)||n(`/${a}`)},[a,n]);let f=d.length>0?Math.min(s,d.length-1):0,u=process.stdin.isTTY??!1;return Yv((h,y)=>{if(de(h,y)){o();return}if(y.return&&bh(a)&&n){n(`/${a}`);return}if(y.return&&d.length>0){r(d[f]);return}if(y.upArrow){i(S=>Math.max(0,S-1));return}if(y.downArrow){i(S=>Math.min(d.length-1,S+1));return}if(y.backspace||y.delete){c(S=>S.slice(0,-1));return}if(h&&!y.ctrl&&!y.meta){let S=a+h;if(n&&bh(S)){n(`/${S}`);return}c(S)}},{isActive:u}),Fa(im,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,children:[Fa(im,{marginBottom:1,children:[sm(Ua,{bold:!0,children:"Commands"}),a&&Fa(Ua,{dimColor:!0,children:[" /",a]})]}),d.map((h,y)=>Fa(im,{children:[Fa(Ua,{inverse:y===f,children:["/",h.name]}),Fa(Ua,{dimColor:!0,children:[" ",h.description]})]},h.name)),d.length===0&&sm(Ua,{dimColor:!0,children:"No matching commands"}),sm(im,{marginTop:1,children:sm(Ua,{dimColor:!0,children:"\u2191\u2193 navigate \u23CE select esc cancel"})})]})}import{jsx as wl,jsxs as Ba}from"react/jsx-runtime";import{useState as jb,useEffect as Qv}from"react";import{Box as am,Text as ii,useInput as Zv}from"ink";function Eh({arions:e,initialFilter:t="",statusFilter:r="all",onSelect:n,onCancel:o}){let[s,i]=jb(0),[a,c]=jb(t),l=e.filter(u=>r==="active"&&u.isResting||r==="resting"&&!u.isResting?!1:u.name.toLowerCase().includes(a.toLowerCase()));Qv(()=>{i(u=>Math.min(u,Math.max(0,l.length-1)))},[l.length]);let d=l.length>0?Math.min(s,l.length-1):0,f=process.stdin.isTTY??!1;return Zv((u,h)=>{if(de(u,h)){o();return}if(h.return&&l.length>0){n(l[d]);return}if(h.upArrow){i(y=>Math.max(0,y-1));return}if(h.downArrow){i(y=>Math.min(l.length-1,y+1));return}if(h.backspace||h.delete){c(y=>y.slice(0,-1));return}u&&!h.ctrl&&!h.meta&&c(y=>y+u)},{isActive:f}),Ba(am,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,children:[Ba(am,{marginBottom:1,children:[wl(ii,{bold:!0,children:r==="active"?"Active Arions":r==="resting"?"Resting Arions":"Arions"}),a&&Ba(ii,{dimColor:!0,children:[" @",a]})]}),l.length===0&&wl(ii,{dimColor:!0,children:e.length===0?"No arions available. Create one with /hatch":r==="active"?"No active arions":r==="resting"?"No resting arions":"No matching arions"}),l.map((u,h)=>{let y=Ac(u.color),S=u.isActive?" (active)":u.isResting?" (resting)":"";return Ba(am,{children:[Ba(ii,{inverse:h===d,children:[u.emoji," ",wl(ii,{color:y,children:u.name})]}),Ba(ii,{dimColor:!0,children:[" ",u.description,S]})]},u.name)}),wl(am,{marginTop:1,children:wl(ii,{dimColor:!0,children:"\u2191\u2193 navigate \u23CE select esc cancel"})})]})}import{jsx as Tr,jsxs as zr}from"react/jsx-runtime";import{useState as _h,useEffect as ek,useMemo as tk}from"react";import{Box as Yo,Text as qt,useInput as rk}from"ink";var nk={anthropic:"Anthropic","openai-codex":"OpenAI Codex",google:"Google",bedrock:"AWS Bedrock","bedrock-converse":"AWS Bedrock (Converse)","github-copilot":"GitHub Copilot",openai:"OpenAI",local:"Local"},Pb=["anthropic","openai-codex","google","bedrock","bedrock-converse","github-copilot","openai","local"];function ok(e){return nk[e]||e}function $b(e){let t=Pb.indexOf(e);return t>=0?t:Pb.length}function sk(e,t,r){let n=new Map;for(let i of e){let a=i.provider||"other",c=n.get(a)??[];c.push(i),n.set(a,c)}let o={powerful:0,balanced:1,fast:2,ensemble:3},s=[...n.entries()].sort(([i],[a])=>$b(i)-$b(a));for(let[i,a]of s){t.push({type:"header",label:ok(i),provider:i});let c=u=>{if(!u)return"balanced";let h=u.toLowerCase();return h.includes("deep")?"powerful":h.includes("quick")?"fast":"balanced"},l=[/^claude-opus-|^opus-|^bedrock-opus-/,/^claude-sonnet-|^sonnet-|^bedrock-sonnet-/,/^claude-haiku-|^haiku-|^bedrock-haiku-/,/^claude-/,/^gpt-/,/^o[0-9]/,/^gemini-/],d=u=>{let h=u.toLowerCase();for(let y=0;y<l.length;y++)if(l[y].test(h))return y;return l.length},f=[...a].sort((u,h)=>{let y=d(u.name),S=d(h.name);return y!==S?y-S:h.name.localeCompare(u.name)});for(let u of f)r.push(t.length),t.push({type:"model",model:u})}}var yl=["low","medium","high","max"],ik={low:"\u258C",medium:"\u258C\u258C",high:"\u258C\u258C\u258C",max:"\u258C\u258C\u258C\u258C"},ak={low:"Low",medium:"Medium",high:"High",max:"Max"},Fb={low:"blue",medium:"cyan",high:"yellow",max:"magenta"};function Ch({models:e,initialFilter:t="",effortLevel:r,onSelect:n,onCancel:o}){let[s,i]=_h(t),[a,c]=_h(r??"high"),d=e.filter(C=>C.name.toLowerCase().includes(s.toLowerCase())),{items:f,selectableIndices:u}=tk(()=>{if(!d.some(_=>_.provider))return{items:d.map(_=>({type:"model",model:_})),selectableIndices:d.map((_,P)=>P)};let T=[],E=[];return sk(d,T,E),{items:T,selectableIndices:E}},[d]),h=u.findIndex(C=>{let T=f[C];return T?.type==="model"&&T.model.isCurrent}),[y,S]=_h(h>=0?h:0);ek(()=>{S(C=>Math.min(C,Math.max(0,u.length-1)))},[u.length]);let R=u.length>0?Math.min(y,u.length-1):0,I=process.stdin.isTTY??!1;rk((C,T)=>{if(de(C,T)){o();return}if(T.return&&u.length>0){let E=u[R],_=f[E];_.type==="model"&&n(_.model,a);return}if(T.leftArrow){c(E=>{let _=yl.indexOf(E);return yl[Math.max(0,_-1)]});return}if(T.rightArrow){c(E=>{let _=yl.indexOf(E);return yl[Math.min(yl.length-1,_+1)]});return}if(T.upArrow){S(E=>Math.max(0,E-1));return}if(T.downArrow){S(E=>Math.min(u.length-1,E+1));return}if(T.backspace||T.delete){i(E=>E.slice(0,-1));return}C&&!T.ctrl&&!T.meta&&i(E=>E+C)},{isActive:I});let v=u.length>0?` [${R+1}/${u.length}]`:"";return zr(Yo,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,children:[zr(Yo,{marginBottom:1,children:[Tr(qt,{bold:!0,children:"Model"}),Tr(qt,{dimColor:!0,children:v}),Tr(qt,{children:" "}),s?Tr(qt,{color:"cyan",children:s}):Tr(qt,{dimColor:!0,children:"Type to search..."})]}),d.length===0&&Tr(qt,{dimColor:!0,children:"No matching models"}),(()=>{let C=f.reduce((T,E)=>E.type!=="model"?T:Math.max(T,E.model.name.length),0);return f.map((T,E)=>{if(T.type==="header"){let ze=kw(T.provider);return zr(Yo,{marginTop:E>0?1:0,children:[zr(qt,{color:ze.color,children:[ze.icon," "]}),Tr(qt,{bold:!0,color:ze.color,children:T.label})]},`header-${T.label}-${E}`)}if(T.type==="hint")return Tr(Yo,{marginTop:1,children:Tr(qt,{dimColor:!0,italic:!0,children:T.label})},"hint");let _=u[R]===E,P=T.model.description,Z=T.model.name.padEnd(C),nt=Id(T.model.name);return zr(Yo,{children:[zr(qt,{inverse:_,color:_?void 0:nt,dimColor:_?!1:!nt,children:[T.model.isCurrent?"\u25CF":"\u25CB"," ",Z]}),P&&zr(qt,{dimColor:!0,children:[" ",T.model.description]})]},T.model.value??`${T.model.provider}-${T.model.name}`)})})(),zr(Yo,{marginTop:1,flexDirection:"column",children:[zr(Yo,{children:[zr(qt,{color:Fb[a],children:[ik[a]," "]}),zr(qt,{color:Fb[a],bold:!0,children:[ak[a]," effort"]}),a==="high"&&Tr(qt,{dimColor:!0,children:" (default)"}),Tr(qt,{dimColor:!0,children:" \u2190 \u2192 to adjust"})]}),Tr(Yo,{marginTop:0,children:Tr(qt,{dimColor:!0,children:"\u2191\u2193 navigate \u2190 \u2192 effort \u23CE select esc cancel"})})]})]})}import{jsx as Jo,jsxs as Sn}from"react/jsx-runtime";import{useState as Rh,useEffect as ck}from"react";import{Box as Ha,Text as Kr,useInput as lk}from"ink";import dk from"ink-spinner";function Ah({memories:e,mode:t="browse",isLoading:r=!1,onSelect:n,onCancel:o}){let[s,i]=Rh(0),[a,c]=Rh(""),[l,d]=Rh(0),f=8,u=e.filter(T=>T.content.toLowerCase().includes(a.toLowerCase())),h=Math.max(1,Math.ceil(u.length/f)),y=u.slice(l*f,(l+1)*f);ck(()=>{i(T=>Math.min(T,Math.max(0,y.length-1)))},[y.length]);let S=y.length>0?Math.min(s,y.length-1):0,R=process.stdin.isTTY??!1;lk((T,E)=>{if(de(T,E)){o();return}if(E.return&&y.length>0&&t==="forget"){n?.(y[S]);return}if(E.upArrow){i(_=>Math.max(0,_-1));return}if(E.downArrow){i(_=>Math.min(y.length-1,_+1));return}if(E.leftArrow&&l>0){d(_=>_-1),i(0);return}if(E.rightArrow&&l<h-1){d(_=>_+1),i(0);return}if(E.backspace||E.delete){c(_=>_.slice(0,-1)),d(0),i(0);return}T&&!E.ctrl&&!E.meta&&(c(_=>_+T),d(0),i(0))},{isActive:R});function I(T){let E=T instanceof Date?T:new Date(T);if(isNaN(E.getTime()))return"unknown";let P=new Date().getTime()-E.getTime(),Z=Math.floor(P/(1e3*60*60*24));return Z===0?"today":Z===1?"yesterday":Z<7?`${Z}d ago`:Z<30?`${Math.floor(Z/7)}w ago`:`${Math.floor(Z/30)}mo ago`}function v(T,E){return T.length<=E?T:T.slice(0,E-3)+"..."}return Sn(Ha,{flexDirection:"column",borderStyle:"round",borderColor:t==="forget"?"red":"cyan",paddingX:1,children:[Sn(Ha,{marginBottom:1,children:[Jo(Kr,{bold:!0,color:t==="forget"?"red":"cyan",children:t==="forget"?"Select Memory to Delete":"Memories"}),a&&Sn(Kr,{dimColor:!0,children:[' (filter: "',a,'")']}),Sn(Kr,{dimColor:!0,children:[" - ",u.length," memories"]})]}),r&&Sn(Ha,{children:[Jo(Kr,{color:"cyan",children:Jo(dk,{type:"dots"})}),Jo(Kr,{dimColor:!0,children:" Loading memories..."})]}),!r&&u.length===0&&Jo(Kr,{dimColor:!0,children:e.length===0?"No memories stored yet. Use /remember to add some.":"No memories match your filter."}),!r&&y.map((T,E)=>{let _=E===S,P=I(T.createdAt),Z=v(T.content,60);return Sn(Ha,{flexDirection:"row",children:[Sn(Kr,{inverse:_,children:[_?">":" "," ",Z]}),Sn(Kr,{dimColor:!0,children:[" [",P,"]"]}),T.network&&Sn(Kr,{dimColor:!0,children:[" (",T.network,")"]})]},T.id)}),!r&&h>1&&Jo(Ha,{marginTop:1,children:Sn(Kr,{dimColor:!0,children:["Page ",l+1,"/",h]})}),Jo(Ha,{marginTop:1,children:Jo(Kr,{dimColor:!0,children:t==="forget"?"type to filter arrows navigate enter delete esc cancel":"type to filter arrows navigate esc close"})})]})}import{jsx as xl,jsxs as bn}from"react/jsx-runtime";import{useState as Ih,useEffect as Ub}from"react";import{Box as Wa,Text as Yn,useInput as uk}from"ink";function mk(e){let r=Date.now()-e.getTime(),n=Math.floor(r/6e4),o=Math.floor(r/36e5),s=Math.floor(r/864e5);return n<1?"just now":n<60?`${n}m ago`:o<24?`${o}h ago`:s<7?`${s}d ago`:e.toLocaleDateString()}function vh({sessions:e,onSelect:t,onCancel:r,onSearch:n,onPageChange:o}){let{columns:s}=ft(),[i,a]=Ih(0),[c,l]=Ih(""),[d,f]=Ih(0),u=8,h=Math.max(1,Math.ceil(e.length/u)),y=e.slice(d*u,(d+1)*u);Ub(()=>{a(C=>Math.min(C,Math.max(0,y.length-1)))},[y.length]),Ub(()=>{f(C=>Math.min(C,Math.max(0,h-1)))},[h]);let S=y.length>0?Math.min(i,y.length-1):0,R=process.stdin.isTTY??!1;uk((C,T)=>{if(de(C,T))r();else if(T.return&&y.length>0)t(y[S].id);else if(T.upArrow)a(E=>Math.max(0,E-1));else if(T.downArrow)a(E=>Math.min(y.length-1,E+1));else if(T.leftArrow&&d>0)f(E=>E-1),a(0);else if(T.leftArrow&&d===0)o?.("prev"),a(0);else if(T.rightArrow&&d<h-1)f(E=>E+1),a(0);else if(T.rightArrow&&d===h-1)o?.("next"),a(0);else if(T.backspace||T.delete){let E=c.slice(0,-1);l(E),f(0),a(0),n(E)}else if(C&&!T.ctrl&&!T.meta){let E=c+C;l(E),f(0),a(0),n(E)}},{isActive:R});function I(C,T){return C.length<=T?C:C.slice(0,T-3)+"..."}let v=Math.max(30,Math.min(120,s-28));return bn(Wa,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:1,children:[bn(Wa,{marginBottom:1,children:[xl(Yn,{bold:!0,color:"cyan",children:"Sessions"}),c&&bn(Yn,{dimColor:!0,children:[' (filter: "',c,'")']}),bn(Yn,{dimColor:!0,children:[" - ",e.length," sessions"]})]}),e.length===0?xl(Yn,{dimColor:!0,children:c?"No sessions match your filter.":"No sessions yet."}):y.map((C,T)=>{let E=T===S,_=mk(C.updatedAt),P=C.title??C.preview??"Untitled session",Z=d*u+T;return bn(Wa,{flexDirection:"column",marginBottom:T<y.length-1?1:0,children:[bn(Wa,{flexDirection:"row",children:[bn(Yn,{inverse:E,children:[E?">":" "," ",Z+1,". ",I(P,v)]}),bn(Yn,{dimColor:!0,children:[" [",_,"]"]})]}),bn(Yn,{dimColor:!0,children:[" ",C.arion," | ",C.model," | ",C.messageCount," messages"]})]},C.id)}),e.length>0&&h>1&&xl(Wa,{marginTop:1,children:bn(Yn,{dimColor:!0,children:["Page ",d+1,"/",h]})}),xl(Wa,{marginTop:1,children:xl(Yn,{dimColor:!0,children:"type to search arrows navigate enter resume esc cancel"})})]})}import{jsx as Sl,jsxs as ai}from"react/jsx-runtime";import{useState as kh,useEffect as cm,useMemo as fk}from"react";import{Box as lm,Text as Qo,useInput as pk}from"ink";function hk(e,t){return e.length<=t?e:e.slice(0,t-3)+"\u2026"}function gk(e){switch(e){case"user":return"\u{1F464}";case"assistant":return"\u{1F916}";case"system":return"\u2699\uFE0F";case"tool":return"\u{1F527}";default:return" "}}function wk(e){switch(e){case"user":return"cyan";case"assistant":return"green";case"system":return"yellow";case"tool":return"gray";default:return"white"}}function Mh({messages:e,onSelect:t,onCancel:r}){let{columns:n,rows:o}=ft(),[s,i]=kh(0),[a,c]=kh(""),l=fk(()=>{if(!a)return e;let I=a.toLowerCase();return e.filter(v=>v.text.toLowerCase().includes(I)||v.role.toLowerCase().includes(I)||v.arion&&v.arion.toLowerCase().includes(I))},[e,a]);cm(()=>{i(I=>Math.min(I,Math.max(0,l.length-1)))},[l.length]),cm(()=>{if(!a){let I=l.reduce((v,C,T)=>C.role==="user"?T:v,0);i(I)}},[]);let d=Math.max(4,o-10),[f,u]=kh(0);cm(()=>{s<f?u(s):s>=f+d&&u(s-d+1)},[s,d,f]),cm(()=>{let I=l.reduce((v,C,T)=>C.role==="user"?T:v,0);u(Math.max(0,I-d+2))},[a]);let h=l.slice(f,f+d),y=l.length>0?Math.min(s,l.length-1):0,S=process.stdin.isTTY??!1;pk((I,v)=>{if(de(I,v))r();else if(v.return&&l.length>0){let C=l[y];C&&C.role==="user"&&t(C.index,C.text)}else if(v.upArrow)i(C=>Math.max(0,C-1));else if(v.downArrow)i(C=>Math.min(l.length-1,C+1));else if(v.backspace||v.delete){let C=a.slice(0,-1);c(C),i(0)}else if(I&&!v.ctrl&&!v.meta){let C=a+I;c(C),i(0)}},{isActive:S});let R=Math.max(30,Math.min(120,n-16));return ai(lm,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:1,children:[ai(lm,{marginBottom:1,children:[Sl(Qo,{bold:!0,color:"cyan",children:"Edit Message"}),a?ai(Qo,{dimColor:!0,children:[" ",'(search: "',a,'") \u2014 ',l.length,"/",e.length," messages"]}):ai(Qo,{dimColor:!0,children:[" \u2014 ",e.length," messages \xB7 select a user message to edit"]})]}),f>0&&ai(Qo,{dimColor:!0,children:[" \u2191 ",f," more above"]}),l.length===0?Sl(Qo,{dimColor:!0,children:a?`No messages match "${a}".`:"No messages."}):h.map((I,v)=>{let T=f+v===y,E=I.role==="user",_=gk(I.role),P=wk(I.role),Z=T?"\u276F":" ",nt=hk(I.text.replace(/\n/g," ").trim()||"(empty)",R);return Sl(lm,{flexDirection:"row",children:ai(Qo,{inverse:T,color:T?void 0:P,dimColor:!E&&!T,bold:E,children:[Z," ",_," ",nt]})},`${I.index}-${v}`)}),f+d<l.length&&ai(Qo,{dimColor:!0,children:[" \u2193 ",l.length-f-d," more below"]}),Sl(lm,{marginTop:1,children:Sl(Qo,{dimColor:!0,children:"type to search \xB7 \u2191\u2193 navigate \xB7 enter select user message \xB7 esc cancel"})})]})}import{jsx as Q,jsxs as Lt}from"react/jsx-runtime";import yk,{useState as xk,useMemo as Dh}from"react";import{Box as Dt,Text as te,useInput as Sk}from"ink";D();var bk={standard:"Standard",claude:"Claude",accessible:"Accessible"},Tk=["standard","claude","accessible"];function Bb(e){return e.includes("daltonized")||e.includes("accessible")?"accessible":e.startsWith("claude-")?"claude":"standard"}function Ek(e){let t=e.colors.text.replace("#",""),r=parseInt(t.slice(0,2),16),n=parseInt(t.slice(2,4),16),o=parseInt(t.slice(4,6),16);return(r*299+n*587+o*114)/1e3<128}function _k(e){return cn().map(t=>{let r=Dd(t);return{name:t,displayName:r.displayName,isCurrent:t===e,isLight:Ek(r),category:Bb(t)}})}function Ck({theme:e}){let t=e.colors,r=t.primary,n=t.info,o=t.success,s=t.textMuted,i=t.text;return Lt(Dt,{flexDirection:"column",children:[Q(te,{color:s,children:"// fetch a user by ID"}),Lt(Dt,{children:[Q(te,{color:r,children:"async function "}),Q(te,{color:i,children:"fetchUser"}),Q(te,{color:i,children:"("}),Q(te,{color:i,children:"id"}),Q(te,{color:i,children:": "}),Q(te,{color:o,children:"string"}),Q(te,{color:i,children:") {"})]}),Lt(Dt,{children:[Q(te,{color:i,children:" "}),Q(te,{color:r,children:"const "}),Q(te,{color:i,children:"res = "}),Q(te,{color:r,children:"await "}),Q(te,{color:i,children:"fetch("}),Q(te,{color:n,children:"`/api/users/${"}),Q(te,{color:i,children:"id"}),Q(te,{color:n,children:"}`"}),Q(te,{color:i,children:")"})]}),Lt(Dt,{children:[Q(te,{color:i,children:" "}),Q(te,{color:r,children:"if "}),Q(te,{color:i,children:"(!res.ok) "}),Q(te,{color:r,children:"throw new "}),Q(te,{color:o,children:"Error"}),Q(te,{color:i,children:"("}),Q(te,{color:n,children:"`HTTP ${"}),Q(te,{color:i,children:"res.status"}),Q(te,{color:n,children:"}`"}),Q(te,{color:i,children:")"})]}),Lt(Dt,{children:[Q(te,{color:i,children:" "}),Q(te,{color:r,children:"return "}),Q(te,{color:i,children:"res.json() "}),Q(te,{color:r,children:"as "}),Q(te,{color:o,children:"Promise"}),Q(te,{color:i,children:"<"}),Q(te,{color:o,children:"User"}),Q(te,{color:i,children:">"})]}),Q(te,{color:i,children:"}"})]})}function Rk({theme:e}){let t=e.colors,r=e.symbols;return Lt(Dt,{flexDirection:"column",borderStyle:"single",borderColor:t.secondary,paddingX:1,children:[Lt(te,{bold:!0,color:t.primary,children:[r.prompt," ",e.displayName]}),Q(Dt,{marginTop:1,flexDirection:"column",children:Q(Ck,{theme:e})}),Lt(Dt,{marginTop:1,flexDirection:"column",children:[Lt(te,{color:t.success,children:[r.success," Tests passed (3/3)"]}),Lt(te,{color:t.error,children:[r.error," Error: connection refused"]}),Lt(te,{color:t.warning,children:[r.warning," Deprecated API call"]}),Q(Dt,{children:Q(te,{color:t.diffAdded,children:"+ const data = await fetch(url);"})}),Q(Dt,{children:Q(te,{color:t.diffRemoved,children:"- const data = http.get(url);"})}),Lt(te,{color:t.textMuted,children:[r.info," 1.2k tokens ",r.bullet," $0.01 ",r.bullet," 0.8s"]})]})]})}function Lh({onSelect:e,onCancel:t}){let r=Dh(()=>x().name,[]),n=Dh(()=>_k(r),[r]),{items:o,selectableIndices:s}=Dh(()=>{let S=[],R=[],I=new Map;for(let v of n){let C=I.get(v.category)??[];C.push(v),I.set(v.category,C)}for(let v of Tk){let C=I.get(v);if(C?.length){S.push({type:"header",label:bk[v]??v});for(let T of C)R.push(S.length),S.push({type:"theme",option:T})}}return{items:S,selectableIndices:R}},[n]),i=s.findIndex(S=>{let R=o[S];return R?.type==="theme"&&R.option.isCurrent}),[a,c]=xk(i>=0?i:0),l=s.length>0?Math.min(a,s.length-1):0,d=o[s[l]],f=d?.type==="theme"?d.option.name:null;f&&an(f);let u=yk.useCallback(()=>{an(r),t()},[r,t]),h=process.stdin.isTTY??!1;Sk((S,R)=>{if(de(S,R)){u();return}if(R.return&&s.length>0){let I=s[l],v=o[I];v.type==="theme"&&e({name:v.option.name,displayName:v.option.displayName});return}if(R.upArrow){c(I=>Math.max(0,I-1));return}if(R.downArrow){c(I=>Math.min(s.length-1,I+1));return}},{isActive:h});let y=x();return Lt(Dt,{flexDirection:"column",borderStyle:"round",borderColor:y.colors.primary,paddingX:1,children:[Lt(Dt,{marginBottom:1,children:[Q(te,{bold:!0,color:y.colors.primary,children:"Theme"}),Lt(te,{color:y.colors.textMuted,children:[" ",y.symbols.arrow," select a color theme"]})]}),Lt(Dt,{children:[Q(Dt,{flexDirection:"column",width:38,children:o.map((S,R)=>{if(S.type==="header")return Q(Dt,{marginTop:R>0?1:0,children:Q(te,{bold:!0,color:y.colors.textMuted,children:S.label})},`header-${S.label}`);let I=s[l]===R,{option:v}=S;return Q(Dt,{children:Lt(te,{inverse:I,color:I?y.colors.primary:y.colors.text,children:[v.isCurrent?"\u25CF":"\u25CB"," ",v.displayName]})},v.name)})}),Q(Dt,{flexDirection:"column",flexGrow:1,marginLeft:2,children:Q(Rk,{theme:y})})]}),Q(Dt,{marginTop:1,children:Lt(te,{color:y.colors.textMuted,children:["\u2191\u2193"," navigate ","\u23CE"," select esc cancel"]})})]})}D();import{jsxs as ci,jsx as dm}from"react/jsx-runtime";import{useState as Hb,useEffect as Ak,useMemo as Ik}from"react";import{Box as Nh,Text as Zo,useInput as vk}from"ink";function kk(e,t){let r=t.trim().toLowerCase();return r?[e.displayNameSnapshot,e.nodeId,e.host,e.port?.toString(),e.principalFingerprint,e.transport,e.status].filter(o=>typeof o=="string"&&o.length>0).map(o=>o.toLowerCase()).some(o=>o.includes(r)):!0}function Oh(e,t){return t<=0?0:Math.min(e,t-1)}function jh({peers:e,sameHomeClientsAvailable:t=!1,onSelect:r,onCancel:n}){let[o,s]=Hb(0),[i,a]=Hb(""),c=x(),l=Ik(()=>e.filter(h=>kk(h,i)),[e,i]);Ak(()=>{s(h=>Oh(h,l.length))},[l.length]);let d=Oh(o,l.length),f=process.stdin.isTTY??!1;vk((h,y)=>{if(de(h,y)){n();return}if(y.return){l.length>0&&r(l[d]);return}if(y.upArrow){s(S=>Math.max(0,S-1));return}if(y.downArrow){s(S=>Oh(S+1,l.length));return}if(y.backspace||y.delete){a(S=>S.slice(0,-1)),s(0);return}if(h&&!y.ctrl&&!y.meta){a(S=>S+h),s(0);return}},{isActive:f});let u=h=>`${h.slice(0,4)} ${h.slice(4,8)} ${h.slice(8,12)} ${h.slice(12,16)}`;return ci(Nh,{flexDirection:"column",borderStyle:"round",borderColor:c.colors.secondary,paddingX:1,children:[ci(Zo,{bold:!0,color:c.colors.primary,children:[" ","Nearby Peers"," "]}),i?ci(Zo,{dimColor:!0,children:[' (filter: "',i,'")']}):null,l.length===0&&dm(Zo,{dimColor:!0,children:i?"No peers match your filter.":t?"No peer nodes. Use /clients for same-home terminals.":"Scanning... no peers found yet"}),l.map((h,y)=>ci(Nh,{children:[ci(Zo,{inverse:y===d,color:y===d?c.colors.primary:void 0,children:[y===d?" \u25B8 ":" ",h.displayNameSnapshot]}),h.status==="connected"?dm(Zo,{color:"green",children:" \u2713 connected"}):ci(Zo,{dimColor:!0,children:[" ",h.host,":",h.port]}),h.principalFingerprint?ci(Zo,{color:c.colors.secondary,children:[" ",u(h.principalFingerprint)]}):null]},`${h.displayNameSnapshot}-${h.nodeId}-${y}`)),dm(Nh,{marginTop:l.length>0?1:0,children:dm(Zo,{dimColor:!0,children:"type to search \u2191\u2193 navigate \u23CE connect esc cancel"})})]})}D();import{jsxs as qa,jsx as Ph}from"react/jsx-runtime";import{useEffect as Mk,useMemo as Dk,useState as Wb}from"react";import{Box as $h,Text as Ga,useInput as Lk}from"ink";function Nk(e,t){let r=t.trim().toLowerCase();return r?e.displayLabel.toLowerCase().includes(r)||e.clientId.toLowerCase().includes(r)||e.clientKind.toLowerCase().includes(r):!0}function Fh(e,t){return t<=0?0:Math.min(e,t-1)}function Uh({clients:e,onSelect:t,onCancel:r}){let[n,o]=Wb(0),[s,i]=Wb(""),a=x(),c=Dk(()=>e.filter(f=>Nk(f,s)),[e,s]);Mk(()=>{o(f=>Fh(f,c.length))},[c.length]);let l=Fh(n,c.length),d=process.stdin.isTTY??!1;return Lk((f,u)=>{if(de(f,u)){r();return}if(u.return){c.length>0&&!c[l]?.self&&t(c[l]);return}if(u.upArrow){o(h=>Math.max(0,h-1));return}if(u.downArrow){o(h=>Fh(h+1,c.length));return}if(u.backspace||u.delete){i(h=>h.slice(0,-1)),o(0);return}f&&!u.ctrl&&!u.meta&&(i(h=>h+f),o(0))},{isActive:d}),qa($h,{flexDirection:"column",borderStyle:"round",borderColor:a.colors.secondary,paddingX:1,children:[qa(Ga,{bold:!0,color:a.colors.primary,children:[" ","Same-Home Clients"," "]}),s?qa(Ga,{dimColor:!0,children:[' (filter: "',s,'")']}):null,c.length===0&&Ph(Ga,{dimColor:!0,children:"No same-home clients found."}),c.map((f,u)=>qa($h,{flexDirection:"column",children:[qa(Ga,{inverse:u===l,color:u===l?a.colors.primary:void 0,children:[u===l?" \u25B8 ":" ",f.displayLabel]}),qa(Ga,{dimColor:!0,children:[" ",f.clientId,f.self?" self \xB7 not sendable":""]})]},`${f.clientId}-${u}`)),Ph($h,{marginTop:c.length>0?1:0,children:Ph(Ga,{dimColor:!0,children:"type to search \u2191\u2193 navigate \u23CE select esc cancel"})})]})}D();import{jsx as es,jsxs as bl}from"react/jsx-runtime";import{Box as um,Text as Jn,useInput as Ok}from"ink";function Bh({inviteToken:e,inviteLabel:t,expiresAt:r,onClose:n}){let o=x(),s=process.stdin.isTTY??!1;return Ok((i,a)=>{(a.return||de(i,a))&&n()},{isActive:s}),bl(um,{flexDirection:"column",borderStyle:"round",borderColor:o.colors.secondary,paddingX:1,paddingY:1,children:[es(Jn,{bold:!0,color:o.colors.primary,children:"Internet Invite"}),t?bl(Jn,{children:["Label: ",es(Jn,{bold:!0,children:t})]}):null,r?bl(Jn,{dimColor:!0,children:["Expires: ",r]}):null,bl(um,{marginTop:1,flexDirection:"column",children:[es(Jn,{children:"Share this token:"}),es(Jn,{children:e})]}),bl(um,{marginTop:1,flexDirection:"column",children:[es(Jn,{children:"Join with:"}),es(Jn,{children:`aria pairing join ${e}`})]}),es(um,{marginTop:1,children:es(Jn,{dimColor:!0,children:"Press Enter or Esc to close."})})]})}D();import{jsx as ts,jsxs as jk}from"react/jsx-runtime";import{useState as Pk}from"react";import{Box as mm,Text as Tl,useInput as $k}from"ink";function Hh({onSubmit:e,onCancel:t,error:r}){let[n,o]=Pk(""),s=x(),i=process.stdin.isTTY??!1;return $k((a,c)=>{if(de(a,c)){t();return}if(c.return){let l=n.trim();l.length>0&&e(l);return}if(c.backspace||c.delete){o(l=>l.slice(0,-1));return}a&&!c.ctrl&&!c.meta&&o(l=>l+a)},{isActive:i}),jk(mm,{flexDirection:"column",borderStyle:"round",borderColor:s.colors.secondary,paddingX:1,paddingY:1,children:[ts(Tl,{bold:!0,color:s.colors.primary,children:"Join Invite"}),ts(Tl,{children:"Paste the invite token and press Enter."}),ts(mm,{marginTop:1,children:ts(Tl,{children:n||" "})}),r?ts(mm,{marginTop:1,children:ts(Tl,{color:s.colors.error,children:r})}):null,ts(mm,{marginTop:1,children:ts(Tl,{dimColor:!0,children:"Type token, Enter to join, Esc to cancel."})})]})}D();import{jsxs as li,jsx as El}from"react/jsx-runtime";import{useState as Fk,useRef as Uk}from"react";import{Box as _l,Text as di,useInput as Bk}from"ink";function Wh({request:e,onAccept:t,onReject:r}){let[n,o]=Fk("accept"),s=Uk(!1),i=x(),a=process.stdin.isTTY??!1,c=l=>`${l.slice(0,4)} ${l.slice(4,8)} ${l.slice(8,12)} ${l.slice(12,16)}`;return Bk((l,d)=>{if(!s.current){if(d.return){s.current=!0,n==="accept"?t():r();return}if(de(l,d)){s.current=!0,r();return}(d.leftArrow||d.rightArrow||d.tab)&&o(f=>f==="accept"?"reject":"accept")}},{isActive:a}),li(_l,{flexDirection:"column",borderStyle:"round",borderColor:i.colors.warning,paddingX:2,paddingY:1,children:[li(di,{bold:!0,color:i.colors.warning,children:[" ","Connection Request"," "]}),El(_l,{marginTop:1,children:li(di,{children:[El(di,{bold:!0,children:e.displayNameSnapshot??e.nodeId})," wants to connect"]})}),El(_l,{children:li(di,{dimColor:!0,children:["Fingerprint: ",c(e.principalFingerprint)]})}),li(_l,{marginTop:1,gap:2,children:[li(di,{inverse:n==="accept",color:n==="accept"?i.colors.success:void 0,children:[" ","Accept"," "]}),li(di,{inverse:n==="reject",color:n==="reject"?i.colors.error:void 0,children:[" ","Reject"," "]})]}),El(_l,{marginTop:1,children:El(di,{dimColor:!0,children:"\u2190\u2192 select \u23CE confirm esc reject"})})]})}D();import{jsxs as za,jsx as Xa}from"react/jsx-runtime";import{useEffect as Hk,useState as Wk,useRef as qb}from"react";import{Box as fm,Text as ui,useInput as qk}from"ink";function Gk({status:e}){let t=x();switch(e){case"connected":return za(ui,{color:t.colors.success,children:["\u2713"," connected"]});case"expired":return za(ui,{color:t.colors.error,children:["\u2717"," expired"]});case"none":return za(ui,{color:t.colors.textMuted,children:["\xB7"," not connected"]})}}function Gb({providers:e,onSelect:t,onCancel:r,isActive:n=!0}){let o=x(),[s,i]=Wk(0),a=qb(0),c=qb(!1);Hk(()=>{c.current=!1,a.current=0,i(0)},[e]);let l=f=>{i(u=>{let h=f(u);return a.current=h,h})},d=process.stdin.isTTY??!1;return qk((f,u)=>{c.current||(u.upArrow?l(h=>Math.max(0,h-1)):u.downArrow?l(h=>Math.min(e.length-1,h+1)):u.return?(c.current=!0,t(e[a.current])):de(f,u)&&(c.current=!0,r()))},{isActive:n&&d}),za(fm,{flexDirection:"column",borderStyle:"round",borderColor:o.colors.secondary,paddingX:1,paddingY:1,width:56,children:[Xa(fm,{marginBottom:1,children:Xa(ui,{bold:!0,children:"Select a provider:"})}),e.map((f,u)=>{let h=u===s,y=h?"\u25B8":" ";return za(fm,{gap:1,children:[Xa(ui,{color:h?o.colors.primary:void 0,children:y}),Xa(ui,{color:h?o.colors.primary:void 0,bold:h,children:f.label.padEnd(28)}),Xa(Gk,{status:f.status})]},f.id)}),Xa(fm,{marginTop:1,children:za(ui,{color:o.colors.textMuted,children:["\u2191\u2193"," Navigate Enter Select Esc Cancel"]})})]})}D();import{jsxs as Qn,jsx as Gt}from"react/jsx-runtime";import{useEffect as Xk,useRef as qh,useState as pm}from"react";import{Box as Vr,Text as Yr,useInput as zk}from"ink";import{collectOAuthAuthorizationCode as Kk,loginWithOAuth as Vk}from"@aria-cli/auth";function Xb({provider:e,onCancel:t,isActive:r=!0,onComplete:n,authorizeUrl:o,expectedState:s,onCodeSubmit:i}){let a=x(),[c,l]=pm("starting"),[d,f]=pm(""),[u,h]=pm(""),[y,S]=pm(""),R=qh(null),I=qh(!1),v=qh(!1),C=process.stdin.isTTY??!1;zk((E,_)=>{de(E,_)&&t()},{isActive:r&&C}),Xk(()=>{if(I.current)return;I.current=!0,l("waiting");let E=new Promise(P=>{R.current=P}),_=P=>{f(P),l("manual")};if(o&&i){f(o),Kk(e,{authorizeUrl:o,expectedState:s,onManualFallback:_,manualCodePromise:E}).then(async P=>{v.current||(l("exchanging"),await i(P),v.current=!0,l("success"))},P=>{if(v.current)return;let Z=P instanceof Error?P.message:String(P);h(Z),l("error")});return}Vk(e,{onManualFallback:_,manualCodePromise:E}).then(P=>{v.current||(P.success?(l("success"),v.current=!0,setTimeout(()=>{n?.({success:!0,message:P.message})},1e3)):(h(P.message),l("error")))},P=>{if(v.current)return;let Z=P instanceof Error?P.message:String(P);h(Z),l("error")})},[s,o,i,n,e]);let T=E=>{let _=E.trim();_&&(l("exchanging"),R.current&&(R.current(_),R.current=null))};return Qn(Vr,{flexDirection:"column",borderStyle:"round",borderColor:a.colors.secondary,paddingX:1,paddingY:1,width:64,children:[Gt(Vr,{marginBottom:1,children:Qn(Yr,{bold:!0,children:["Sign in to ",e]})}),(c==="starting"||c==="waiting")&&Qn(Vr,{gap:1,children:[Gt(Na,{}),Gt(Yr,{children:"Opening browser to sign in..."})]}),c==="manual"&&Qn(Vr,{flexDirection:"column",children:[Gt(Yr,{children:"Open this URL in your browser:"}),Gt(Vr,{marginTop:1,children:Gt(Yr,{color:a.colors.primary,wrap:"wrap",children:d})}),Gt(Vr,{marginTop:1,children:Gt(Yr,{children:"Paste the authorization code below:"})}),Qn(Vr,{marginTop:1,children:[Gt(Yr,{color:a.colors.textMuted,children:"> "}),Gt(oa,{value:y,onChange:S,onSubmit:T,placeholder:"paste code here",focus:r,showCursor:!0})]})]}),c==="exchanging"&&Qn(Vr,{gap:1,children:[Gt(Na,{}),Gt(Yr,{children:"Exchanging code for tokens..."})]}),c==="success"&&Qn(Yr,{color:a.colors.success,children:["\u2713"," Logged in to ",e]}),c==="error"&&Qn(Vr,{flexDirection:"column",children:[Qn(Yr,{color:a.colors.error,children:["\u2717"," ",u]}),Gt(Vr,{marginTop:1,children:Gt(Yr,{color:a.colors.textMuted,children:"Press Esc to dismiss"})})]}),c!=="success"&&c!=="error"&&Gt(Vr,{marginTop:1,children:Gt(Yr,{color:a.colors.textMuted,children:"Esc Cancel"})})]})}import{jsx as eM}from"react/jsx-runtime";D();import{jsxs as Va,jsx as Zn}from"react/jsx-runtime";import{useEffect as Yk,useRef as zb,useState as Jk}from"react";import{Box as Ka,Text as rs,useInput as Qk}from"ink";function Zk({status:e}){let t=x();return e==="connected"?Va(rs,{color:t.colors.success,children:["\u2713"," connected"]}):e==="available"?Va(rs,{color:t.colors.success,children:["\u2713"," available"]}):Zn(rs,{color:t.colors.textMuted,children:"\xB7"})}function Ya({options:e,onSelect:t,onCancel:r,title:n="Select login method:",isActive:o=!0}){let s=x(),[i,a]=Jk(0),c=zb(0),l=zb(!1),d=process.stdin.isTTY??!1;Yk(()=>{l.current=!1,c.current=0,a(0)},[e]);let f=u=>{a(h=>{let y=u(h);return c.current=y,y})};return Qk((u,h)=>{l.current||(h.upArrow?f(y=>Math.max(0,y-1)):h.downArrow?f(y=>Math.min(e.length-1,y+1)):h.return?(l.current=!0,t(e[c.current])):de(u,h)&&(l.current=!0,r()))},{isActive:o&&d}),Va(Ka,{flexDirection:"column",borderStyle:"round",borderColor:s.colors.secondary,paddingX:1,paddingY:1,width:64,children:[Zn(Ka,{marginBottom:1,children:Zn(rs,{bold:!0,children:n})}),e.map((u,h)=>{let y=h===i,S=y?"\u25B8":" ";return Va(Ka,{flexDirection:"column",children:[Va(Ka,{gap:1,children:[Zn(rs,{color:y?s.colors.primary:void 0,children:S}),Zn(rs,{color:y?s.colors.primary:void 0,bold:y,children:u.label}),Zn(Zk,{status:u.status})]}),u.description&&Zn(Ka,{marginLeft:3,children:Zn(rs,{color:s.colors.textMuted,dimColor:!0,children:u.description})})]},u.id)}),Zn(Ka,{marginTop:1,children:Va(rs,{color:s.colors.textMuted,children:["\u2191\u2193"," Navigate Enter Select Esc Cancel"]})})]})}function Kb({options:e,onSelect:t,onCancel:r,isActive:n=!0}){return eM(Ya,{options:e,onSelect:t,onCancel:r,title:"Select Anthropic login method:",isActive:n})}D();import{jsx as ns,jsxs as Gh}from"react/jsx-runtime";import{useRef as tM,useState as rM}from"react";import{Box as Cl,Text as Ja,useInput as nM}from"ink";function Qa({title:e,hint:t,onSubmit:r,onCancel:n,isActive:o=!0}){let s=x(),[i,a]=rM(""),c=tM(!1),l=process.stdin.isTTY??!1;nM((f,u)=>{if(!c.current){if(de(f,u)){c.current=!0,n();return}if(u.return){i.trim().length>0&&(c.current=!0,r(i.trim()));return}if(u.backspace||u.delete){a(h=>h.slice(0,-1));return}u.upArrow||u.downArrow||u.leftArrow||u.rightArrow||u.tab||f&&!u.ctrl&&!u.meta&&a(h=>h+f)}},{isActive:o&&l});let d=i.length>0?i.slice(0,4)+"\u2022".repeat(Math.max(0,i.length-4)):"";return Gh(Cl,{flexDirection:"column",borderStyle:"round",borderColor:s.colors.secondary,paddingX:1,paddingY:1,width:64,children:[ns(Cl,{marginBottom:1,children:ns(Ja,{bold:!0,children:e})}),t&&ns(Cl,{marginBottom:1,children:ns(Ja,{color:s.colors.textMuted,dimColor:!0,children:t})}),Gh(Cl,{children:[Gh(Ja,{color:s.colors.primary,children:["\u25B8"," "]}),ns(Ja,{children:d||" "}),ns(Ja,{color:s.colors.textMuted,children:"_"})]}),ns(Cl,{marginTop:1,children:ns(Ja,{color:s.colors.textMuted,children:"Enter Submit Esc Cancel"})})]})}function Vb(e,t,r={}){let n=r.userName||"User",o=[],s=new Map;function i(a,c){for(let l of a.content)switch(l.type){case"text":{if(a.role==="user"){let d=Yf(l.text);for(let f of d)f.type==="image"&&Yd(f.dataUri)?o.push({kind:"user-image",id:`${a.id}-image-${o.length}`,dataUri:f.dataUri,userName:n,committed:c}):f.type==="text"&&f.text.length>0&&o.push({kind:"user-message",id:`${a.id}-text-${o.length}`,text:f.text,userName:n,committed:c})}else a.role==="system"&&l.text.length>0?o.push({kind:"user-message",id:`${a.id}-text-${o.length}`,text:l.text,userName:"System",committed:c}):a.role==="assistant"&&l.text.trim()&&o.push({kind:"assistant-text",id:`${a.id}-text-${o.length}`,text:l.text,arion:a.arion?{name:a.arion.name,emoji:a.arion.emoji||"\u{1F98B}",color:a.arion.color||"cyan"}:void 0,committed:c});break}case"thinking":{l.content?.trim()&&o.push({kind:"thinking",id:`${a.id}-thinking-${o.length}`,content:l.content,durationSec:l.durationMs!=null?l.durationMs/1e3:void 0,arion:a.arion?{name:a.arion.name,emoji:a.arion.emoji||"\u{1F98B}",color:a.arion.color||"cyan"}:void 0,committed:c});break}case"tool_use":{let d={kind:"tool-execution",id:`${a.id}-tool-${l.id}`,toolName:l.name,input:l.arguments,output:void 0,status:"pending",durationMs:void 0,usage:void 0,committed:c};s.set(l.id,d),o.push(d);break}case"tool_result":{let d=s.get(l.toolUseId);d&&(d.output=l.resultData??l.content,d.status=l.status==="error"?"error":"complete",l.status==="error"&&(d.error=typeof l.content=="string"?l.content:"Tool error"),l.durationMs!=null&&(d.durationMs=l.durationMs),l.usage&&(d.usage={inputTokens:l.usage.inputTokens??0,outputTokens:l.usage.outputTokens??0}),c||(d.committed=!1));break}case"handoff":{o.push({kind:"handoff",id:`${a.id}-handoff-${o.length}`,target:l.target,direction:l.direction==="from"?"incoming":"outgoing",committed:c});break}case"error":{o.push({kind:"error",id:`${a.id}-error-${o.length}`,message:l.content,suggestion:l.suggestion,committed:c});break}}}for(let a of e)i(a,!0);for(let a of t)i(a,!1);return o}import{DEFAULT_SAFETY_CONFIG as lM}from"@aria-cli/aria";import{useReducer as oM,useEffect as Xh,useRef as Qb}from"react";var Yb={kind:"idle"};function Jb(e,t){switch(t.type){case"STREAM_START":return{kind:"composing",verb:t.verb};case"THINKING_START":return e.kind!=="composing"&&e.kind!=="idle"?e:{kind:"thinking",verb:t.verb,startedAt:t.startedAt};case"THINKING_END":return e.kind!=="thinking"?e:{kind:"composing",verb:t.verb,thoughtForSeconds:t.durationSeconds};case"TOOL_START":{let r=new Map(e.kind==="tool_running"?e.tools:[]);return r.set(t.callId,t.displayName),{kind:"tool_running",tools:r}}case"TOOL_END":{if(e.kind!=="tool_running")return e;let r=new Map(e.tools);return r.delete(t.callId),r.size===0?{kind:"composing",verb:t.verb}:{kind:"tool_running",tools:r}}case"STREAM_END":return{kind:"idle"};default:return e}}function Zb(e,t){let[r,n]=oM(Jb,Yb),o=Qb(!1);Xh(()=>{t&&!o.current?n({type:"STREAM_START",verb:Nr()}):!t&&o.current&&n({type:"STREAM_END"}),o.current=t},[t]);let s=Qb(null);return Xh(()=>{e!==s.current&&(s.current!==null&&n({type:"STREAM_END"}),s.current=e)},[e]),Xh(()=>{if(!e)return;let i=()=>n({type:"THINKING_START",verb:Nr(),startedAt:Date.now()}),a=d=>n({type:"THINKING_END",verb:Nr(),durationSeconds:Math.round(d.durationMs/1e3)}),c=d=>n({type:"TOOL_START",callId:d.id,displayName:$y(d.name,!0)}),l=d=>n({type:"TOOL_END",callId:d.id,verb:Nr()});return e.on("thinking_start",i),e.on("thinking_end",a),e.on("tool_start",c),e.on("tool_result",l),()=>{e.off("thinking_start",i),e.off("thinking_end",a),e.off("tool_start",c),e.off("tool_result",l)}},[e]),r}function hm(e){let t=typeof e.nodeId=="string"?e.nodeId.trim():"",r=typeof e.transport=="string"?e.transport:"unknown";if(t)return`node:${t}`;let n=typeof e.principalFingerprint=="string"?e.principalFingerprint.trim():"";return n?`principal:${n}`:`endpoint:${r}:${e.host}:${e.port}:${e.displayNameSnapshot}`}function eT(e,t){let r=new Map;for(let n of[...e,...t]){let o=hm(n);r.has(o)||r.set(o,n)}return[...r.values()]}function zh({session:e,model:t,maxContextTokens:r,banner:n,messages:o=[],previewMessages:s=[],isStreaming:i=!1,queuedMessage:a,onCancelQueuedMessage:c,responseTime:l,commands:d=[],arions:f=[],models:u=[],memories:h=[],memoryBrowserMode:y="browse",isLoadingMemories:S=!1,userName:R,metrics:I,displayMode:v="standard",displayConfig:C,showThinking:T=!0,showCosts:E=!0,showTraces:_=!1,spans:P=[],pipelineTiming:Z,activeArion:nt,onSubmit:ze,onCommand:le,onSelectArion:N,onSelectModel:A,onSelectTheme:$,onSelectMemory:he,onOpenMemoryBrowser:ae,onToggleThinking:oe,onToggleCosts:_e,onToggleTraces:We,onCycleDisplayMode:dt,sessions:sr=[],onSelectSession:Y,onLoadSessions:se,onSearchSessions:$e,onLoadMoreSessions:z,staticRenderEpoch:je,openSessionOverlaySignal:Qe,openThemeOverlaySignal:fe,inputHistory:Be=[],onSaveInput:Ye,obsCtx:Xt,onCancel:Ke,approvalRequest:Zr,onApprovalChoice:zm,effortLevel:wi,showAutonomySelector:Km,autonomyLevel:Bl,onAutonomySelect:ac,onAutonomyCancel:Hl,onCycleAutonomy:yi,onCycleEffort:Dr,loginPickerProviders:xi,onLoginProviderSelect:Wl,onLoginPickerCancel:ql,copilotSourceOptions:cc,onCopilotSourceSelect:Gl,onCopilotSourceCancel:ao,oauthProvider:us,oauthAuthorizeUrl:lc,oauthExpectedState:_n,onOAuthComplete:en,onOAuthCodeSubmit:dc,onOAuthCancel:co,copilotDeviceProvider:uc,copilotDeviceProfileLabel:Vm,copilotDeviceVerificationUri:ms,copilotDeviceUserCode:Xl,onCopilotDeviceComplete:Si,onCopilotDeviceApprove:zl,onCopilotDeviceCancel:bi,anthropicMethodOptions:mc,onAnthropicMethodSelect:Ti,onAnthropicMethodCancel:Kl,anthropicKeyInputVisible:Ei,onAnthropicKeySubmit:Vl,onAnthropicKeyCancel:_i,anthropicSetupTokenVisible:Yl,onAnthropicSetupTokenSubmit:Ci,onAnthropicSetupTokenCancel:fc,openaiMethodOptions:fs,onOpenAIMethodSelect:Jl,onOpenAIMethodCancel:Ri,openaiKeyInputVisible:Ql,onOpenAIKeySubmit:Ai,onOpenAIKeyCancel:Zl,googleMethodOptions:ps,onGoogleMethodSelect:ed,onGoogleMethodCancel:Ii,googleKeyInputVisible:td,onGoogleKeySubmit:vi,onGoogleKeyCancel:rd,authInteractionOptions:hs,authInteractionTitle:Ym,onAuthInteractionSelect:ki,onAuthInteractionCancel:nd,authInteractionInput:lo,onAuthInteractionInputSubmit:od,onAuthInteractionInputCancel:Mi,nearbyPeers:Di=[],localClients:Li=[],onSelectPeer:Jm,onSelectClient:pc,onPeerCancel:sd,onClientsCancel:gs,openPeersOverlaySignal:id,openClientsOverlaySignal:hc,inviteShare:uo,onInviteShareClose:ad,openJoinInviteOverlaySignal:Cn,onJoinInviteSubmit:cd,onJoinInviteCancel:Qm,joinInviteError:Zm,incomingPairRequest:ws,onAcceptPairRequest:ef,onRejectPairRequest:tf,onCancelPairing:ld,openMessageEditOverlaySignal:dd,editableMessages:mo,onEditMessage:Ni,prefillInput:Oi,onPrefillConsumed:rf,meshMessageCount:nf=0,runtimeSocket:pw=null,clientId:gc=null,clientAuthToken:tn=null,resolveCredentials:ud}){let{exit:Rn}=aM(),{columns:wc,rows:yc}=ft(),[ji,ot]=os(""),[B,ce]=os("none"),[fo,Pi]=os(""),[$i,ys]=os(""),[xs,An]=os("become"),[of,Ss]=os("all"),[xc,sf]=os(!1),rn=!!(hs||mc||fs||ps),af=!!(lo||Ei||Yl||Ql||td),md=!!(us||uc||xi||cc);Jr(()=>{rn?ce("login-method"):af?ce("login-input"):md?ce("login"):(B==="login"||B==="login-method"||B==="login-input")&&ce("none")},[rn,af,md]);let Sc=eo(()=>{ce("session"),setTimeout(()=>se?.(),0)},[se]);Jr(()=>{Qe!==void 0&&Sc()},[Qe,Sc]),Jr(()=>{fe!==void 0&&ce("theme")},[fe]);let[bs,Ts]=os([]);Jr(()=>{id!==void 0&&(Ts([...Di]),ce("peers"))},[id]),Jr(()=>{hc!==void 0&&ce("clients")},[hc]),Jr(()=>{uo?ce("invite-share"):B==="invite-share"&&ce("none")},[uo,B]),Jr(()=>{Cn!==void 0&&ce("join-invite")},[Cn]),Jr(()=>{dd!==void 0&&mo&&mo.length>0&&ce("message-edit")},[dd]),Jr(()=>{Oi!==void 0&&(ot(Oi),rf?.())},[Oi]),Jr(()=>{B==="peers"&&Ts(L=>{let we=new Set(L.map(hm)),qe=Di.filter(ho=>!we.has(hm(ho)));return qe.length>0?[...L,...qe]:L})},[B,Di]),Jr(()=>{ws&&B==="none"&&!i?ce("pair-request"):!ws&&B==="pair-request"&&ce("none")},[ws,B,i]);let cf=process.stdin.isTTY??!1;cM((L,we)=>{if(L===""||we.ctrl&&L==="c"){if(i&&Ke){Ke();return}Rn()}if(de(L,we)){if(Zr)return;if(B!=="none"){xt();return}if(ld){ld();return}i&&a&&c?c():i&&Ke?Ke():ot("");return}if(we.upArrow&&i&&a&&c){c();return}if(we.ctrl&&L===""&&B==="none"){dt?.();return}if(we.ctrl&&L==="t"&&B==="none"){oe?.();return}if(we.ctrl&&L==="g"&&B==="none"){_e?.();return}if(we.ctrl&&L==="s"&&B==="none"){We?.();return}if(we.tab&&L!==" "&&B==="none"){yi?.();return}if(we.ctrl&&L===""&&B==="none"){Dr?.();return}if(we.ctrl&&L===""&&B==="none"){sf(qe=>!qe);return}},{isActive:cf});let In=e.getPrimary(),lf=In?.name||"ARIA",fr=In?.color||"cyan",df=In?.emoji||"\u{1F98B}",vn=Zb(Xt??null,i??!1),uf=(B==="none"&&!Zr?4:0)+(!C||C.showStatusBar?1:0),bc=Math.max(yc-uf,1),po=eo((L,we)=>{L==="command"?(ce("command"),Pi(we)):L==="mention"&&(ce("arion"),ys(we),An("mention"))},[]),mf=eo(L=>{ce("none"),ot("");let we=L.requiresArgs===!0||(L.args?.length??0)>0;if(L.name==="become")ce("arion"),An("become"),Ss("all");else if(L.name==="rest")ce("arion"),An("rest"),Ss("active");else if(L.name==="wake")ce("arion"),An("wake"),Ss("resting");else if(L.name==="model")ce("model");else if(L.name==="theme")ce("theme");else if(L.name==="memories")ae?.("browse"),ce("memory");else if(L.name==="forget")ae?.("forget"),ce("memory");else if(L.name==="resume")Sc();else if(L.name==="exit")Rn();else if(we){ot(`/${L.name} `);return}else le(L.name)},[le,ae,Rn]),fd=eo(L=>{if(ce("none"),xs==="mention"){let we=ji.replace(/@\w*$/,"");ot(we+"@"+L.name+" ")}else N?.(L.name,xs)},[xs,ji,N]),Tc=eo((L,we)=>{ce("none"),A?.(L.value??L.name,we)},[A]),Ec=eo(L=>{ce("none"),$?.(L)},[$]),yt=eo(L=>{ce("none"),he?.(L)},[he]),xt=eo(()=>{ce("none"),xs!=="mention"&&ot(""),Pi(""),ys("")},[xs]),nn=eo(L=>{ce("none"),ot(L),Pi("")},[]),ge=ss(()=>Vb(o,s,{userName:R}),[o,s,R]),Nt=ss(()=>Bp(ge,v),[ge,v]),Es=ss(()=>Nt.filter(L=>L.committed),[Nt]),_s=ss(()=>Nt.filter(L=>!L.committed),[Nt]),ir=i&&a?a:null,Fi=ir!==null,kn=vn.kind!=="idle",ff=Math.max(wc-4,20),hw=ss(()=>ir?Math.max(St(ir,{width:ff}).split(`
|
|
461
|
-
`).length,1):0,[ff,ir]),pd=(Fi?4+hw:0)+(kn?2:0),At=Math.max(bc-pd,1),H=ss(()=>{let L=new Map,we="";for(let qe of Nt){let ho=qe.kind==="user-message"||qe.kind==="user-image"?`user:${qe.userName}`:qe.kind==="assistant-text"?`assistant:${qe.arion?.name??"ARIA"}`:qe.kind==="thinking"?`assistant:${qe.arion?.name??"ARIA"}`:qe.kind==="tool-execution"?"tool":qe.kind,It=qe.kind==="user-message"||qe.kind==="user-image"||qe.kind==="assistant-text"||qe.kind==="thinking";L.set(qe.id,It&&ho!==we),It&&(we=ho)}return L},[Nt]),Ui=ss(()=>{let L=new Map;for(let we=0;we<Nt.length;we++){let qe=Nt[we],ho=we>0?Nt[we-1]:void 0,It=qe.kind==="tool-execution"&&ho?.kind==="tool-execution";L.set(qe.id,we>0&&!It)}return L},[Nt]),hd=ss(()=>{let L=[];n&&L.push({id:"header",_kind:"banner"});for(let we of Es)L.push({...we,_kind:"item"});return L},[n,Es]);return mi(sM,{children:[re(iM,{items:hd,children:L=>L._kind==="banner"?re(Tn,{width:"100%",justifyContent:"center",children:n},L.id):re(Tn,{flexDirection:"column",marginTop:Ui.get(L.id)?1:0,children:re(Bu,{item:L,displayMode:v,showPrefix:H.get(L.id)??!1})},L.id)},`static-${je}`),mi(Tn,{flexDirection:"column",width:"100%",children:[mi(Tn,{flexDirection:"column",maxHeight:bc,justifyContent:"flex-end",overflowY:"hidden",children:[_s.length>0&&re(Tn,{flexDirection:"column",maxHeight:At,overflowY:"hidden",children:_s.map(L=>re(Tn,{flexDirection:"column",marginTop:Ui.get(L.id)?1:0,children:re(Bu,{item:L,displayMode:v,showPrefix:H.get(L.id)??!1,previewTailLines:At})},L.id))}),Fi&&mi(Tn,{marginTop:1,flexDirection:"column",children:[re(Vd,{param:{type:"text",text:ir??""},userName:R??"User",columns:wc,showPrefix:!0,addMargin:!1}),re(to,{dimColor:!0,children:" \u2191 queued \u2014 press esc or \u2191 to cancel and edit"})]}),_&&P.length>0&&re(Vp,{spans:P}),C?.showPipelineTiming&&Z&&Z.phases.length>0&&re(Yp,{report:Z}),xc&&mi(Tn,{flexDirection:"column",borderStyle:"round",borderColor:"gray",paddingX:1,marginY:1,children:[re(to,{bold:!0,dimColor:!0,children:"Hotkeys"}),re(to,{dimColor:!0,children:" Ctrl+\\ \u2014 cycle display mode"}),re(to,{dimColor:!0,children:" Ctrl+t \u2014 toggle thinking blocks"}),re(to,{dimColor:!0,children:" Ctrl+g \u2014 toggle cost display"}),re(to,{dimColor:!0,children:" Ctrl+e \u2014 cycle effort level"}),re(to,{dimColor:!0,children:" Ctrl+s \u2014 toggle trace waterfall"}),re(to,{dimColor:!0,children:" Escape \u2014 cancel streaming / close overlay / clear input"}),re(to,{dimColor:!0,children:" Ctrl+/ \u2014 toggle this help"})]}),kn&&re(Qp,{state:vn.kind==="thinking"?"thinking":"composing",elapsedSeconds:Math.floor(I?.wallTimeSeconds??0),totalTokens:I?.totalTokens??0,thoughtForSeconds:vn.kind==="composing"?vn.thoughtForSeconds:void 0,currentVerb:vn.kind==="tool_running"?[...new Set(vn.tools.values())].join(" \xB7 "):vn.verb.present})]}),mi(Tn,{flexDirection:"column",flexShrink:0,children:[Km&&ac&&Hl&&re(zp,{currentLevel:Bl??lM.autonomy,onSelect:ac,onCancel:Hl}),xi&&Wl&&ql&&re(Gb,{providers:xi,onSelect:Wl,onCancel:ql}),cc&&Gl&&ao&&re(Gp,{options:cc,onSelect:Gl,onCancel:ao}),B==="login-method"&&hs&&ki&&nd&&re(Ya,{options:hs,onSelect:L=>ki(L.id),onCancel:nd,title:Ym??"Choose an option:",isActive:B==="login-method"}),B==="login-method"&&mc&&Ti&&Kl&&re(Kb,{options:mc,onSelect:Ti,onCancel:Kl,isActive:B==="login-method"}),B==="login-input"&&lo&&od&&Mi&&re(Qa,{title:lo.title,hint:lo.hint,onSubmit:od,onCancel:Mi,isActive:B==="login-input"}),B==="login-input"&&Ei&&Vl&&_i&&re(Qa,{title:"Enter Anthropic API key",hint:"Paste your sk-ant-api03-* key",onSubmit:Vl,onCancel:_i,isActive:B==="login-input"}),B==="login-input"&&Yl&&Ci&&fc&&re(Qa,{title:"Enter setup token",hint:"From `claude setup-token` or admin provisioning",onSubmit:Ci,onCancel:fc,isActive:B==="login-input"}),B==="login-method"&&fs&&Jl&&Ri&&re(Ya,{options:fs,onSelect:Jl,onCancel:Ri,title:"Select OpenAI login method:",isActive:B==="login-method"}),B==="login-input"&&Ql&&Ai&&Zl&&re(Qa,{title:"Enter OpenAI API key",hint:"Paste your sk-* key",onSubmit:Ai,onCancel:Zl,isActive:B==="login-input"}),B==="login-method"&&ps&&ed&&Ii&&re(Ya,{options:ps,onSelect:ed,onCancel:Ii,title:"Select Google login method:",isActive:B==="login-method"}),B==="login-input"&&td&&vi&&rd&&re(Qa,{title:"Enter Google API key",hint:"Paste your AIza* key",onSubmit:vi,onCancel:rd,isActive:B==="login-input"}),B==="login"&&us&&en&&co&&re(Xb,{provider:us,onCancel:co,...lc&&dc?{authorizeUrl:lc,expectedState:_n??void 0,onCodeSubmit:dc}:{onComplete:en},isActive:B==="login"}),B==="login"&&uc&&Si&&bi&&re(qp,{provider:uc,profileLabel:Vm??void 0,...ms&&Xl&&zl?{verificationUri:ms,userCode:Xl,onApprove:zl}:{onComplete:Si},onCancel:bi}),mi(Tn,{flexDirection:"column",children:[B==="command"&&re(Th,{commands:d,initialFilter:fo,onSelect:mf,onHandOffInput:nn,onCancel:xt}),B==="arion"&&re(Eh,{arions:f,initialFilter:$i,statusFilter:of,onSelect:fd,onCancel:xt}),B==="model"&&re(Ch,{models:u,effortLevel:wi,onSelect:Tc,onCancel:xt}),B==="theme"&&re(Lh,{onSelect:Ec,onCancel:xt}),B==="invite-share"&&uo&&re(Bh,{inviteToken:uo.inviteToken,inviteLabel:uo.inviteLabel,expiresAt:uo.expiresAt,onClose:()=>{ce("none"),ad?.()}}),B==="join-invite"&&re(Hh,{error:Zm,onSubmit:L=>{ce("none"),cd?.(L)},onCancel:()=>{ce("none"),Qm?.()}}),B==="memory"&&re(Ah,{memories:h,mode:y,isLoading:S,onSelect:yt,onCancel:xt}),B==="peers"&&re(jh,{peers:bs.length>0?bs:Di,sameHomeClientsAvailable:Li.length>0,onSelect:L=>{ce("none"),Jm?.(L)},onCancel:xt}),B==="clients"&&re(Uh,{clients:Li,onSelect:L=>{ce("none"),ot(`/send ${L.clientId} `),pc?.(L)},onCancel:()=>{ce("none"),gs?.()}}),B==="pair-request"&&ws&&re(Wh,{request:ws,onAccept:()=>{ce("none"),ef?.()},onReject:()=>{ce("none"),tf?.()}}),B==="session"&&re(vh,{sessions:sr,onSelect:L=>{ce("none"),Y?.(L)},onCancel:xt,onSearch:L=>$e?.(L),onPageChange:L=>z?.(L)}),B==="message-edit"&&mo&&re(Mh,{messages:mo,onSelect:(L,we)=>{ce("none"),Ni?.(L,we)},onCancel:xt}),B==="none"&&!Zr&&re(zf,{userName:R,value:ji,onChange:ot,onSubmit:ze,onTrigger:po,onExit:()=>Rn(),history:Be,onSaveInput:Ye,focus:B==="none",isStreaming:i,onDoubleEscape:()=>mo&&mo.length>0?(ce("message-edit"),!0):!1})]}),(!C||C.showStatusBar)&&re(Af,{arion:{name:lf,emoji:df,color:fr,traits:In?.personality?.traits?.slice(0,2)},model:t,maxContextTokens:r,responseTime:l,metrics:I,displayMode:v,showCosts:E,activeArion:nt,effortLevel:wi,autonomyLevel:Bl,meshMessageCount:nf})]})]})]})}function hM(e){let t=al[e.toLowerCase()];return{name:e,userFacingName(r){return t?t.displayName(r):e},renderToolUseMessage(r,n){return t?t.renderInput(r,n):JSON.stringify(r)},isReadOnly(){return!1},inputSchema:{parse(r){return r??{}}}}}var gM={message:{id:"aria-approval"}};function wM(e){switch(e){case"low":return .2;case"moderate":return .5;case"high":return .9}}function tT(e){let{stdout:t}=pM(),r=t?.columns??80,[n]=mM(!1),o=uM(()=>{if(!e.approvalRequest)return null;let{toolName:s,input:i,riskLevel:a,resolve:c}=e.approvalRequest;return{assistantMessage:gM,tool:hM(s),description:`${s} requires approval`,input:i??{},commandPrefix:null,riskScore:wM(a),onAbort(){c(!1)},onAllow(l){c(!0)},onReject(){c(!1)}}},[e.approvalRequest]);return o?dM(fM,{flexDirection:"column",width:"100%",children:[Kh(zh,{...e}),Kh(Sh,{toolUseConfirm:o,onDone:()=>{},verbose:n})]}):Kh(zh,{...e})}import{execFile as yM}from"node:child_process";import{existsSync as oT,readdirSync as sT}from"node:fs";import{dirname as xM,join as gm,resolve as SM}from"node:path";import{fileURLToPath as bM}from"node:url";var TM=xM(bM(import.meta.url));function EM(){let e=TM;for(let t=0;t<10;t++){let r=gm(e,".comms","sounds","wav");if(oT(r))return r;let n=SM(e,"..");if(n===e)break;e=n}return null}var Al=EM();function Xe(e){if(!Al)return[];try{return sT(Al).filter(t=>new RegExp(e).test(t)).map(t=>gm(Al,t))}catch{return[]}}function rT(e){if(!Al)return[];let t=gm(Al,"cloned");try{return sT(t).filter(r=>new RegExp(e).test(r)).map(r=>gm(t,r))}catch{return[]}}function ro(e){return e.length===0?null:e[Math.floor(Math.random()*e.length)]}var Vh=!0;function Yh(e){Vh=e}function iT(){return Vh}function no(e){!Vh||!e||!oT(e)||yM("afplay",[e],()=>{})}var oo={acknowledge:()=>Xe("^(peasant|orc|human|dwarf|elf|troll)_acknowledge"),annoyed:()=>Xe("^(peasant|orc|goblin_sapper|human|troll|ogre)_selected"),grumpy:()=>Xe("^(goblin_sapper|ogre|ogre_mage)_selected"),dark:()=>[...Xe("^ogre_mage_selected"),...Xe("^ogre_selected"),...Xe("^troll_selected")],defeat:()=>rT("^defeat_"),error:()=>rT("^error_"),readyToWork:()=>[...Xe("^peasant_selected"),...Xe("^orc_selected"),...Xe("^human_selected"),...Xe("^dwarf_selected")],fleetUp:()=>[...Xe("^orc_acknowledge"),...Xe("^troll_acknowledge"),...Xe("^ogre_acknowledge"),...Xe("^human_acknowledge"),...Xe("^knight_acknowledge")],fleetDown:()=>[...Xe("^ogre_mage_acknowledge"),...Xe("^ship_acknowledge"),...Xe("^horde_ship_acknowledge")],questDone:()=>[...Xe("^jobs_done"),...Xe("^orc_work_completed"),...Xe("^peasant_selected"),...Xe("^orc_selected"),...Xe("^human_selected"),...Xe("^peasant_acknowledge"),...Xe("^orc_acknowledge")]},nT=0,Rl=0,_M=15e3;function CM(){let e=Date.now();e-nT>_M?Rl=1:Rl++,nT=e,Rl<=1?no(ro(oo.acknowledge())):no(ro(Rl===2?oo.annoyed():Rl===3?oo.grumpy():oo.dark()))}function aT(){no(ro(oo.readyToWork()))}function cT(){no(ro(oo.fleetDown()))}function lT(){CM()}function dT(){no(ro(oo.questDone()))}function uT(e){switch(e.type){case"error":no(ro(oo.error()));break;case"guardrail_rejected":no(ro(oo.defeat()));break}}var Jh=[{name:"become",description:"Switch to another arion",usage:"/become <name>",args:["<name>"],requiresArgs:!0},{name:"arions",description:"List all arions",args:[]},{name:"hatch",description:"Create a new arion",usage:"/hatch <name> [description]",args:["<name>","[description]"],requiresArgs:!0},{name:"rest",description:"Put an arion to rest",usage:"/rest <name>",args:["<name>"],requiresArgs:!0},{name:"wake",description:"Wake a resting arion",usage:"/wake <name>",args:["<name>"],requiresArgs:!0},{name:"model",description:"Change or view current AI model",args:["[name]"]},{name:"autonomy",description:"Change permission approval policy",usage:"/autonomy [level]",args:["[level]"]},{name:"sound",description:"Toggle Warcraft sound notifications on/off",usage:"/sound [on|off]",args:["[on|off]"]},{name:"remember",description:"Store a memory",usage:"/remember <text>",args:["<text>"],requiresArgs:!0},{name:"recall",description:"Search memories",usage:"/recall <query>",args:["<query>"],requiresArgs:!0},{name:"recall_knowledge",description:"Search learned tools (skills, procedures, techniques)",usage:"/recall_knowledge <topic>",args:["<topic>"],requiresArgs:!0},{name:"send",description:"Send a peer or same-home client message through the runtime transport",usage:"/send <peer-name|node-id|client-id> <message>",args:["<peer-name|node-id|client-id>","<message>"],requiresArgs:!0},{name:"forget",description:"Delete a memory",usage:"/forget <id>",args:["<id>"],requiresArgs:!0},{name:"memories",description:"Browse all memories",args:[]},{name:"resume",description:"Resume a previous session",args:["[session-id]"]},{name:"fork",description:"Fork the current session into a new branch",usage:"/fork [session-id] [message-count] [--stay]",args:["[session-id]","[message-count]","[--stay]"]},{name:"clear",description:"Clear the screen",args:[]},{name:"login",description:"Authenticate with provider (bedrock, anthropic, openai, google, copilot)",usage:"/login [provider] [api-key|--profile <label>|--source <gh|device>]",args:["[provider]","[api-key|flags]"]},{name:"logout",description:"Disconnect a provider or clear all credentials",usage:"/logout [provider|all]",args:["[provider|all]"]},{name:"help",description:"Show available commands",args:[]},{name:"restart",description:"Restart ARIA",usage:"/restart [reason]",args:["[reason]"]},{name:"terminal-setup",description:"Install Shift+Enter newline key binding for supported terminals",usage:"/terminal-setup",args:[]},{name:"theme",description:"View or change the color theme",usage:"/theme [name]",args:["[name]"]},{name:"invite",description:"Create an internet invite token",usage:"/invite [label]",args:["[label]"]},{name:"join",description:"Accept an internet invite token",usage:"/join [token]",args:["[token]"]},{name:"peers",description:"Show nearby peers and connect",args:[]},{name:"clients",description:"Show same-home attached clients",args:[]},{name:"exit",description:"Exit ARIA",args:[]}];import{createRequire as AM}from"node:module";var IM=AM(import.meta.url),vM=IM("../package.json"),mT=vM.version,fT=["\u26A1 Search millions of lines instantly with native Rust-powered code search","\u{1F9E0} Jump to definitions & find references with real LSP intelligence","\u270F\uFE0F Press Esc\xD72 to edit and fork any previous message in-place","\u{1F50A} Get audio cues when tasks finish \u2014 try /sound to configure","\u{1F3A8} All 87 tools now render rich, beautiful output in the terminal"];import{autonomyToConfirmation as EN,AUTONOMY_LEVELS as Bm,DEFAULT_SAFETY_CONFIG as _N,isPrivateLanIP as CN}from"@aria-cli/aria";Zh();D();vl();_r();_d();import{parseMessage as RN,recoverCrashedSessions as AN,NoopOTELAdapter as IN,HttpOTELAdapter as vN,JsonlEventLogger as kN}from"@aria-cli/aria";import{resolveTrustedRuntimeErrorMessage as Yg}from"@aria-cli/tools";import{getCliModels as MN,getCliSelectableModels as Jg,getDefaultModelByTier as Qg,getModelByShortName as e0,MODEL_REGISTRY as DN,selectRunnableModelVariant as ic,toShortName as LN}from"@aria-cli/models";import{MemoriaPool as NN}from"@aria-cli/aria";import{getErrorMessage as Zg,log as Ee}from"@aria-cli/types";_r();import{NO_RELAUNCH_ENV as NM,RELAUNCH_EXIT_CODE as OM,RESUME_ARION_ENV as bT,RESUME_SESSION_ENV as og,RESTART_KIND_ENV as $V,clearRelaunchMarker as FV,readRelaunchMarker as UV,writeRelaunchMarker as jM}from"@aria-cli/types";import{NO_RELAUNCH_ENV as qV,RELAUNCH_EXIT_CODE as GV,RESUME_ARION_ENV as XV,RESUME_SESSION_ENV as zV,RESTART_KIND_ENV as KV}from"@aria-cli/types";function ig(e){jM(e)}function PM(e){if(!e||typeof e!="object")return!1;let t=e;return t.code==="EPIPE"||t.code==="EIO"||t.code==="ERR_STREAM_DESTROYED"}function ng(e){try{process.stderr.write(e)}catch(t){if(PM(t))return;throw t}}var TT=process.env[og]??null,sg=process.env[bT]||"ARIA";function kl(e){let t=e?.trim()||null;TT=t,t?process.env[og]=t:delete process.env[og]}function xm(){return TT}function ag(e){sg=e||"ARIA",process.env[bT]=sg}function $M(){return sg}function FM(){return process.env[NM]==="true"}async function ET(e,t){if(!FM())throw new Error("Restart requires RelaunchSupervisor; detached self-spawn has been removed.");let r=e||"Restart requested";t!==void 0&&kl(t);let n=xm(),o=$M();ng(`[aria] Relaunch requested: ${r} (session=${n?.slice(0,8)??"none"}, arion=${o})
|
|
462
|
-
`);let s=process.ppid||process.pid;ig({sessionId:n,arionName:o,pid:s,timestamp:new Date().toISOString()});try{let i=process.send;if(typeof i=="function"){let a=`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,c=await new Promise(l=>{let d=!1,f=setTimeout(()=>{d||(d=!0,process.off("message",u),l(!1))},120),u=h=>{if(!h||typeof h!="object")return;let y=h;y.type==="aria-relaunch-ack"&&y.nonce===a&&(d||(d=!0,clearTimeout(f),process.off("message",u),l(!0)))};process.on("message",u),i({type:"aria-relaunch",nonce:a,resumeSessionId:n,arionName:o},h=>{h&&!d&&(d=!0,clearTimeout(f),process.off("message",u),l(!1))})});ng(c?`[aria] IPC handoff acknowledged by supervisor
|
|
463
|
-
`:`[aria] IPC ack timeout \u2014 disk marker will be used as fallback
|
|
464
|
-
`)}}catch{}throw process.exit(OM),new Error("Unreachable")}ug();import{randomUUID as sc}from"crypto";function mg(e){return e.trim().toLowerCase()}function MT(e){let t=e.trim();if(!t.startsWith("/"))return null;let r=t.indexOf(" ");if(r===-1){let s=t.slice(1);return{command:kT(s)??mg(s),args:""}}let n=t.slice(1,r);return{command:kT(n)??mg(n),args:t.slice(r+1).trim()}}var aD=["help","arions","exit","hatch","remember","recall","recall_knowledge","send","model","become","rest","wake","memories","forget","clear","autonomy","resume","fork","restart","login","logout","terminal-setup","theme","invite","join"],cD=new Map(aD.map(e=>[e.toLowerCase(),e]));function kT(e){return cD.get(mg(e))??null}Um();Dm();_g();_r();D();import{ArionManager as fN,ArionStorage as pN,DEFAULT_SAFETY_CONFIG as hN}from"@aria-cli/aria";import{getDefaultModelByTier as gN}from"@aria-cli/models";import{existsSync as dN,readFileSync as yJ,readdirSync as uN}from"node:fs";jl();vl();import mN from"node:path";function Vg(e,t){let r=t.trim();if(!r)return"ARIA";let n=mN.join(e,"arions");if(!dN(n))return r;try{let o=r.toLowerCase();for(let s of uN(n,{withFileTypes:!0}))if(s.isDirectory()&&s.name.toLowerCase()===o)return s.name}catch{}return r}async function wN(e){let t=new pN(e.ariaDir),r=new fN(t,e.memoriaFactory);return r.setRouter(e.router),await r.initialize(),r}function zE(e,t){let r=t.trim().toLowerCase();return e.find(n=>n.shortName.toLowerCase()===r||typeof n.id=="string"&&n.id.toLowerCase()===r)}function KE(e){return gN(e??"balanced")}function VE(e){let t=e.cli,r=Vg(t.ariaDir,e.activeArionName??t.config.activeArion??"ARIA"),n,o=[...t.availableModels],s=null,i=new Map,a=async()=>(s??=wN(t),s),c=async()=>{let R=await(await a()).get(r);if(!R)throw new Error(`Unable to resolve active Arion ${r}`);return R},l=async()=>{let S=await c(),R=i.get(S.name);if(R)return R;let v=await(await a()).getMemoria(S);if(!v)throw new Error(`Memoria is unavailable for Arion ${S.name}`);return i.set(S.name,v),v},d={list:async()=>(await a()).list(),hatch:async S=>(await a()).hatch(S),get:async S=>(await a()).get(S),wake:async S=>{await(await a()).wake(S)},rest:async(S,R)=>{await(await a()).rest(S,R)}},f={async getTheme(){return ue().theme??x().name},async setTheme(S){let R=S.trim();if(!cn().includes(R))throw new Error(`Unknown theme: ${S}`);let I=ue();return I.theme=R,Le(I),an(R),{theme:R}},async getAutonomy(){return ue().autonomy??hN.autonomy},async setAutonomy(S){if(!["minimal","balanced","high","full"].includes(S))throw new Error(`Invalid autonomy level: ${S}`);let R=ue();return R.autonomy=S,Le(R),{autonomy:S}},async getActiveArion(){return r},async setActiveArion(S){let R=S.trim()||"ARIA",I=Vg(t.ariaDir,R);try{let T=await(await a()).get(R);T?.name&&(I=T.name)}catch{}let v=ue();v.activeArion=I,Le(v),r=I}},u={async listAvailable(){return o},async refresh(S){return o=[...await t.refreshAvailableModels(S)],o},async getCurrentModel(){if(n)return n;let S=ue();try{let R=await c();if(typeof R.preferredModel=="string"&&R.preferredModel.trim().length>0)return n=R.preferredModel.trim(),n}catch{}return n=KE(S.preferredTier??t.config.preferredTier)?.shortName,n},async setCurrentModel(S){let R=zE(o,S)??zE(await t.refreshAvailableModels(!0),S);if(!R)throw new Error(`Unknown model: ${S}`);n=R.shortName;let I=ue();I.preferredTier=R.tier,Le(I),o=[...await t.refreshAvailableModels(!1)];try{let v=await a(),C=await c();await v.setPreferredModel(C.name,R.shortName)}catch{}return{currentModel:R.shortName,tier:R.tier}},async getSessionModel(){return n}};(async()=>{try{let S=await c();if(typeof S.preferredModel=="string"&&S.preferredModel.trim().length>0){n=S.preferredModel.trim();return}}catch{}n=KE(ue().preferredTier??t.config.preferredTier)?.shortName})();let h={async status(){return{providers:pi()}},async login(S){let R=typeof S.args=="string"?S.args:"";return Mm(R)},async logout(S){let R=typeof S.args=="string"?S.args:"";return Lm(R)}},y=new Proxy({},{get(S,R){return async(...I)=>{let v=await l(),C=v[R];if(typeof C!="function")throw new Error(`Memoria method ${String(R)} is unavailable`);return C.apply(v,I)}}});return{arionManager:e.overrides?.arionManager??d,auth:e.overrides?.auth??h,config:e.overrides?.config??f,memoria:e.overrides?.memoria??y,modelDiscovery:e.overrides?.modelDiscovery??u}}qd();function YE(e){let t=e();if(!t)throw new Error("Late-bound service target is unavailable");return t}function JE(e){return new Proxy({},{get(t,r){if(r==="then")return;let o=YE(e)[r];if(typeof o!="function")throw new Error(`Late-bound service method ${String(r)} is unavailable`);return(...s)=>o.apply(YE(e),s)},has(t,r){return typeof e()?.[r]=="function"},ownKeys(){let t=e();return Reflect.ownKeys(t??{}).filter(r=>typeof t?.[r]=="function")},getOwnPropertyDescriptor(t,r){let n=e();if(typeof n?.[r]=="function")return{configurable:!0,enumerable:!0,writable:!1,value:n[r]}}})}import{useReducer as yN,useMemo as QE,useCallback as xN}from"react";function SN(e,t){switch(t.type){case"START_TURN":return{items:e.items,streamCursor:e.items.length};case"UPDATE_STREAM":return e.streamCursor===null?e:{items:[...e.items.slice(0,e.streamCursor),...t.snapshot],streamCursor:e.streamCursor};case"COMMIT_TURN":{let r=e.streamCursor??e.items.length,n=[...e.items.slice(0,r),...t.flushed];return{items:n,streamCursor:n.length}}case"END_TURN":return{items:e.items,streamCursor:null};case"APPEND_COMMITTED":{if(e.streamCursor!==null){let r=e.items.slice(0,e.streamCursor),n=e.items.slice(e.streamCursor);return{items:[...r,...t.items,...n],streamCursor:e.streamCursor+t.items.length}}return{items:[...e.items,...t.items],streamCursor:null}}case"RESET":return{items:t.items??[],streamCursor:null};case"DISCARD_STREAMING":return e.streamCursor===null?e:{items:e.items.slice(0,e.streamCursor),streamCursor:null};case"FUNCTIONAL_UPDATE":{if(e.streamCursor!==null){let r=e.items.slice(0,e.streamCursor),n=e.items.slice(e.streamCursor),o=t.updater(r);return{items:[...o,...n],streamCursor:o.length}}return{items:t.updater(e.items),streamCursor:null}}case"COMMIT_AND_END":{let r=e.streamCursor??e.items.length;return{items:[...e.items.slice(0,r),...t.flushed],streamCursor:null}}default:return e}}function ZE(e){let t=e?{items:e,streamCursor:null}:{items:[],streamCursor:null},r=SN,[n,o]=yN(r,t),s=QE(()=>n.streamCursor!==null?n.items.slice(0,n.streamCursor):n.items,[n.items,n.streamCursor]),i=QE(()=>n.streamCursor!==null?n.items.slice(n.streamCursor):[],[n.items,n.streamCursor]),a=n.streamCursor!==null,c=xN(l=>{o(typeof l=="function"?{type:"FUNCTIONAL_UPDATE",updater:l}:{type:"RESET",items:l})},[o]);return{items:n.items,committedItems:s,streamingItems:i,isStreaming:a,dispatch:o,setItems:c}}function ew(e){return e!=null&&typeof e=="object"&&"code"in e&&e.code==="ARIA_SESSION_EXPIRED"}function t0(e){try{let t=typeof e=="string"?e:JSON.stringify(e);return t?t.length>160?`${t.slice(0,160)}...`:t:""}catch{return""}}function ON(e){let t=Ew(),r=t?`phase="${t.label}" (active for ${t.ageMs.toFixed(0)}ms)`:"phase=unknown (no phase set)",n=`[InkREPL][WARN] Event loop stall detected: ${e.toFixed(0)}ms (threshold ${2e3}ms) ${r}
|
|
465
|
-
`,o=new Error("[InkREPL] Event loop watchdog detection stack").stack??"[stack unavailable]";try{process.stderr.write(n),process.stderr.write(`${o}
|
|
466
|
-
`)}catch{}}function jN(e){if(process.env.DEBUG)try{let t=(e/1e3).toFixed(1);process.stderr.write(`[InkREPL][DEBUG] System sleep/suspend detected: ${t}s
|
|
467
|
-
`)}catch{}}function PN(e){return e==="high"||e==="dangerous"?"high":e==="moderate"?"moderate":"low"}function $N(e){for(let t=e.length-1;t>=0;t--)if(e[t]?.role==="assistant")return e[t].content;return""}function FN(e){return`${e.provider}/${e.shortName}`}function UN(e,t,r){let n=e.trim().toLowerCase();if(!n)return;let o=[...t].sort((u,h)=>u.shortName.localeCompare(h.shortName)),s=o.find(u=>`${u.provider}/${u.shortName}`.toLowerCase()===n);if(s)return s;let i=o.find(u=>u.shortName.toLowerCase()===n);if(i)return ic(i,r);let a=o.find(u=>u.shortName.toLowerCase().startsWith(n));if(a)return ic(a,r);let c=o.find(u=>`${u.provider}/${u.shortName}`.toLowerCase().startsWith(n));if(c)return c;let l=o.find(u=>u.tier.toLowerCase()===n);if(l)return ic(l,r);let d=o.find(u=>u.displayName.toLowerCase().includes(n));if(d)return ic(d,r);let f=o.find(u=>u.provider.toLowerCase().includes(n));return f?ic(f,r):void 0}var Rt={sessionId:null,sessionHistory:null,memoriaSession:null,memoriaFactory:null,jsonlLogger:null};function r0(e,t,r){let n=r>1?`Run paused: answer question ${t+1} of ${r} to continue.`:"Run paused: answer the question below to continue.",o=Array.isArray(e.options)&&e.options.length>0?`
|
|
468
|
-
Options: ${e.options.join(" | ")}`:"";return`${n}
|
|
469
|
-
${e.question}${o}`}function BN({session:e,manager:t,router:r,aria:n,attachedLocalControl:o,cliContext:s,sessionHistory:i,initialModel:a="sonnet-4.5",inputHistory:c=[],onSaveInput:l,initialMessage:d,resumeSessionId:f,cachedUserName:u,initialAvailableModels:h=MN(),refreshAvailableModels:y,credentialHints:S,authResolver:R}){let{exit:I}=TN(),{committedItems:v,streamingItems:C,isStreaming:T,dispatch:E,setItems:_}=ZE(),P=ue(),Z=P.preferredTier||"balanced",ze=Qg(Z,S)?.shortName||a,[le,N]=U(ze),A=Ae(ze),[$,he]=U(P.effortLevel??"high"),ae=T,oe=Ae(!1),_e=Ae(!1),We=Ae(!1),dt=Ae(!1),sr=Ae(Promise.resolve()),Y=Ae(null),[se,$e]=U(null),[z,je]=U(),[Qe,fe]=U([]),[Be,Ye]=U(u??null),[Xt,Ke]=U(0),[Zr,zm]=U([]),[wi,Km]=U("browse"),[Bl,ac]=U(!1),[Hl,yi]=U([]),[Dr,xi]=U(h),[Wl,ql]=U(void 0),[cc,Gl]=U(void 0),ao=Ae(0),us=Ae(""),lc=Ae(0),_n=Ae(null),en=100,dc=P.autonomy??_N.autonomy,co=Ae(dc),[uc,Vm]=U(dc),ms=V(m=>{co.current=m,Vm(m),Le({...ue(),autonomy:m})},[]),[Xl,Si]=U(!1),[zl,bi]=U(null),[mc,Ti]=U(null),[Kl,Ei]=U(null),[Vl,_i]=U(null),[Yl,Ci]=U(null),[fc,fs]=U(null),[Jl,Ri]=U(null),[Ql,Ai]=U(null),[Zl,ps]=U(null),[ed,Ii]=U(null),[td,vi]=U(null),[rd,hs]=U(!1),[Ym,ki]=U(!1),[nd,lo]=U(null),[od,Mi]=U(!1),[Di,Li]=U(null),[Jm,pc]=U(!1),[sd,gs]=U(null),[id,hc]=U(null),[uo,ad]=U(null),[Cn,cd]=U(null),[Qm,Zm]=U([]),[ws,ef]=U([]),[tf,ld]=U(void 0),[dd,mo]=U(void 0),[Ni,Oi]=U(null),[rf,nf]=U(void 0),[pw,gc]=U(null),[tn,ud]=U(null),Rn=Ae(null),wc=Ae(0),[yc,ji]=U(null);lt(()=>{A.current=le},[le]),lt(()=>{po.current=e.getPrimary()?.name||P.activeArion||"ARIA"},[e,P.activeArion]);let[ot,B]=U(null),ce=V(m=>new Promise(w=>{wc.current+=1,ji({id:wc.current,toolName:m.toolName,input:m.input,riskLevel:m.riskLevel,...m.issues?{issues:m.issues}:{},resolve:w})}),[]),fo=V(m=>{e.addToHistory(m)},[e]),Pi=V(m=>{let w=Gi(m);i&&ge.current&&i.addConversationMessage(ge.current,w),Rt.jsonlLogger?.log({type:"user_message",content:m,id:w.id}),_e.current?_e.current=!1:_(p=>[...p,w]),fo({role:"user",content:m})},[fo,i]),$i=V(m=>{let w=m&&typeof m=="object"&&"diagnostic"in m?m.diagnostic:void 0;Rt.jsonlLogger?.log({type:"error",error:{message:Yg(Zg(m),w)??Zg(m),...w===void 0?{}:{diagnostic:w}}})},[]),ys=V((m,w)=>{let p=$N(m).trim();p&&fo({role:"assistant",content:p,...w?{arion:w}:{}})},[fo]),[xs,An]=U({turnCount:0,totalTokens:0,estimatedCost:0,wallTimeSeconds:0,contextTokens:0,contextStale:!1}),[of,Ss]=U(0),[xc,sf]=U(null);lt(()=>{let m=!1;return(async()=>{try{let w=process.env.ARIA_HOME??`${process.env.HOME}/.aria`,{resolveRuntimeRootDirectory:p,findRuntimeOwnerRecordByAriaHome:g}=await import("@aria-cli/server"),b=p(),M=g(b,w)?.runtimeSocket??null;m||sf(M)}catch{}})(),()=>{m=!0}},[]);let[rn]=U(()=>{let m=dg(),w=ue(),p=w.theme;if(!p&&m.display.theme){p=m.display.theme;try{Le({...w,theme:p})}catch(g){Ee.warn("[Theme] YAML\u2192JSON migration failed (non-fatal):",g.message)}}return p&&(cn().includes(p)?an(p):Ee.warn(`[Theme] Invalid theme "${p}" in config, using default`)),m}),af=Ae(rn.persistence.otelEndpoint?new vN(rn.persistence.otelEndpoint):new IN),[md,Sc]=U(rn.display.mode),[bs,Ts]=U(()=>{let{mode:m,syntaxHighlighting:w,maxToolOutputLines:p,maxThinkingPreview:g,...b}=rn.display;return b}),[cf,In]=U(void 0),[lf,fr]=U([]),[df,vn]=U(0),[uf,bc]=U(),po=Ae(e.getPrimary()?.name||P.activeArion||"ARIA"),[mf,fd]=U(null),Tc=Ae(0),Ec=Ae(0),yt=Ae(null),xt=Ae(null);lt(()=>{let m=ue().soundEnabled;return Yh(m!==!1),aT(),()=>{cT()}},[]),lt(()=>_w({thresholdMs:2e3,onStall:ON,onSleep:jN}),[]);let nn=Ae([]),ge=Ae(null),Nt=Ae(null),Es=Ae(null);if(!Es.current){let m=process.env.ARIA_HOME??`${process.env.HOME}/.aria`,w=new NN(m,r,()=>ge.current);Es.current=w.toFactory()}lt(()=>()=>{let m=ge.current;(async()=>{if(m&&i)try{i.markCompleted(m)}catch(p){Ee.warn("[InkREPL] SessionHistory completion mark failed:",p)}if(m&&Nt.current)try{await Nt.current.endSession(m)}catch(p){Ee.warn("[InkREPL] Memoria session end failed (non-critical):",p)}await Es.current?.closeAll()})().catch(p=>{Ee.warn("[InkREPL] MemoriaPool cleanup failed:",p?.message)})},[]);let _s=Ae(null),ir=Ae(null),Fi=Ae(null),kn=V(async m=>{let w=Date.now()+2e4;for(;Date.now()<w;){if(m?.aborted)return null;let g=(_s.current??await(Fi.current??Promise.resolve(null)))?.control??ir.current??null;if(g)return g;await new Promise(b=>setTimeout(b,250))}return ir.current??null},[]),ff=V(async()=>{if(ir.current)return ir.current;let m=await kn();return m||null},[kn]),hw=V(()=>ir.current,[]),pd=V(m=>{_s.current=m,ir.current=m.control,Fi.current=Promise.resolve(m),Ee.debug(`[InkREPL] Attached TUI local client to runtime ${m.runtimeId} on port ${m.port} (${m.ownership}, node ${m.nodeId})`);try{let w=`${process.env.ARIA_HOME??`${process.env.HOME}/.aria`}/run`,p=`${w}/agent-bridge.json`,g=`${p}.${process.pid}.tmp`,b=Tw("fs"),M=xc??(()=>{try{let O=Tw("@anthropic-ai/claude-code"),j=process.cwd(),W=`${process.env.ARIA_HOME??`${process.env.HOME}/.aria`}`;return O.findRuntimeOwnerRecordByAriaHome?.(j,W)?.runtimeSocket??null}catch{return null}})();b.mkdirSync(w,{recursive:!0}),b.writeFileSync(g,JSON.stringify({socketPath:M,clientId:m.attachedClientId??null,nodeId:m.nodeId,pid:process.pid,updatedAt:new Date().toISOString()},null,2)),b.renameSync(g,p),Ee.debug(`[InkREPL] Wrote agent-bridge.json (clientId=${m.attachedClientId}, socket=${M})`)}catch(w){Ee.debug(`[InkREPL] Failed to write agent-bridge.json: ${w instanceof Error?w.message:String(w)}`)}},[xc]);lt(()=>(pd(o),()=>{Fi.current=Promise.resolve(null),_s.current?.release(),_s.current=null,ir.current=null}),[o,pd]);let At=Fl(()=>{if(!i||!s)return null;let m=new Proxy({},{get(p,g){return async(...b)=>{let M=e.getPrimary(),j=(M&&typeof e.getArionMemoria=="function"?await e.getArionMemoria(M):null)??n.components.memoria,me=j[g];if(typeof me!="function")throw new Error(`Memoria method ${String(g)} is unavailable`);return me.apply(j,b)}}}),w=JE(()=>ir.current);return new oc({cli:s,localControl:w,sessionLedger:i,...VE({cli:s,activeArionName:e.getPrimary()?.name??s.config.activeArion??"ARIA",overrides:{memoria:m,arionManager:{list:()=>t.list(),hatch:p=>t.hatch(p),get:async p=>(await t.list()).find(b=>b.name.toLowerCase()===p.toLowerCase())??null,wake:p=>t.wake(p),rest:p=>e.dismiss(p)},config:{async getTheme(){return x()},async setTheme(p){if(!cn().includes(p))throw new Error(`Unknown theme: ${p}`);an(p);let b=ue();return b.theme=p,Le(b),{theme:p}},async getAutonomy(){return co.current},async setAutonomy(p){if(!Bm.includes(p))throw new Error(`Invalid autonomy level: ${p}`);return ms(p),{autonomy:p}},async getActiveArion(){return po.current??e.getPrimary()?.name??s.config.activeArion},async setActiveArion(p){po.current=p;let g=ue();g.activeArion=p,Le(g)}},modelDiscovery:{async listAvailable(){return Dr},async refresh(p){if(!y)return Dr;let g=await y(p);return xi(g),g},async getCurrentModel(){return le},async setCurrentModel(p){let g=UN(p,Dr,S);if(!g)throw new Error(`Unknown model: ${p}`);N(g.shortName),A.current=g.shortName;let b=e.getPrimary();b&&await t.setPreferredModel(b.name,g.shortName);let M=ue();return M.preferredTier=g.tier,Le(M),{currentModel:g.shortName,tier:g.tier}}}}}),system:{async restart(p){return{accepted:!0,reason:typeof p.reason=="string"&&p.reason.trim().length>0?p.reason.trim():"Restart requested"}},async terminalSetup(){return As()?{supported:!0,output:Wd().trim()}:{supported:!1,message:"terminal-setup is supported only in iTerm2 (macOS) and VSCode terminal."}}}})},[n,Dr,s,t,le,y,e,i,ms]),H=V(async(m,w)=>{if(!At)throw new Error(`Headless kernel unavailable for ${m}`);let p=null,g=null;for await(let b of At.dispatch({kind:"request",requestId:`${m}:${sc()}`,op:m,input:w}))b.kind==="interaction.required"?p=b:b.kind==="result"&&(g=b);return{interactionFrame:p,resultFrame:g}},[At]);lt(()=>{let m=!1,w=async()=>{try{let g=await H("client.inbox.list",{limit:100,unreadOnly:!0}).catch(()=>null),b=g?null:await H("message.inbox.list",{limit:100,unreadOnly:!0}),M=g??b,j=(M?.resultFrame?.ok&&Array.isArray(M.resultFrame.result.events)?M.resultFrame.result.events:[]).length;m||Ss(j)}catch(g){if(ew(g)){m=!0,clearInterval(p);return}m||Ss(0)}};w();let p=setInterval(()=>{m||w()},3e3);return()=>{m=!0,clearInterval(p)}},[H]),lt(()=>{let m=!1,w=o?.control;if(!w?.subscribeDirectClientInbox)return;let p=o?.nodeId,g=o?.attachedClientId,b=new Map,M=3e4;return(async()=>{for(;!m;){try{let j=w.subscribeDirectClientInbox({afterCreatedAt:Date.now()});for await(let W of j){if(m)break;if(W.senderNodeId===p||W.senderClientId&&g&&W.senderClientId===g||W.recipientClientId&&g&&W.recipientClientId!==g)continue;let me=`${W.senderNodeId}\0${W.content}`,Pe=Date.now(),ut=b.get(me);if(ut&&Pe-ut.ts<M){ut.count++,ut.ts=Pe;continue}if(b.set(me,{ts:Pe,count:1}),b.size>200)for(let[Cs,yo]of b)Pe-yo.ts>=M&&b.delete(Cs);let on=W.senderDisplayNameSnapshot?.trim()||W.senderNodeId||"Unknown",ye=W.senderClientId?.match(/^client-pid-(\d+)$/)?.[1],Dn=ye?`${on} (pid ${ye})`:on,Ie=typeof W.content=="string"?W.content:JSON.stringify(W.content),ke=Dn!=="Unknown"?Dn:W.senderNodeId||"unknown",[Ge,sn]=Rd(Dn,ke,Ie,W.id);i&&ge.current&&(i.addConversationMessage(ge.current,Ge),i.addConversationMessage(ge.current,sn)),_(Cs=>[...Cs,Ge,sn]),oe.current||(_e.current=!0,yw.current(`[Incoming message from "${Dn}" (${ke})]
|
|
470
|
-
|
|
471
|
-
${Ie}
|
|
472
|
-
|
|
473
|
-
[Reply using send_message with to="${ke}"]`))}}catch{}m||await new Promise(j=>setTimeout(j,2e3))}})(),()=>{m=!0}},[o]),lt(()=>()=>{yt.current&&clearInterval(yt.current)},[]),lt(()=>{Rt.sessionHistory=i??null,Rt.memoriaFactory=Es.current},[i]);let Ui=Ae(void 0),hd=Ae(null),L=Ae(void 0);lt(()=>{let m=!1;return(async()=>{try{let w=await n.recallUserName();if(m)return;Ye(w);let p=e.getPrimary(),g;p?(g=await e.getArionMemoria(p)??n.components.memoria,p.preferredModel&&N(p.preferredModel)):g=n.components.memoria;let b=await g.count();if(m)return;Ke(b)}catch{}})(),()=>{m=!0}},[n,e]),lt(()=>{let m=!1;return(async()=>{try{let{resultFrame:w}=await H("arion.list",{});if(!w)throw new Error("arion.list produced no result frame");if(!w.ok)throw new Error(w.error.message);let p=w.result.arions??[];if(m)return;fe(p.map(g=>({name:g.name,emoji:g.emoji,color:g.color,description:g.personality?.traits?.slice(0,2).join(", ")||"",isActive:e.isActive(g.name),isResting:g.status==="resting"})))}catch(w){if(m)return;_(p=>[...p,ee(`Failed to load arions: ${w.message}`)])}})(),()=>{m=!0}},[H,e]),lt(()=>{let m=!0,w=null,p=async(b,M)=>{if(!At)return null;let O=null;for await(let j of At.dispatch({kind:"request",requestId:`${b}:${sc()}`,op:b,input:M}))j.kind==="result"&&(O=j);return O};return(async()=>{let b=async()=>{try{let[M,O,j]=await Promise.all([p("peer.list",{}),p("peer.list_nearby",{}),p("client.list",{})]);if(!m||!M?.ok||!O?.ok||!j?.ok)return;let W=M.result.peers??[],me=O.result.peers??[],Pe=j.result.clients??[],ut=me.map(ye=>({displayNameSnapshot:ye.displayNameSnapshot,nodeId:ye.nodeId,host:ye.host,port:ye.port,principalFingerprint:ye.principalFingerprint,version:ye.version,tlsCaFingerprint:ye.tlsCaFingerprint,transport:ye.transport,status:ye.status})),on=W.filter(ye=>ye.transportState==="connected").map(ye=>({displayNameSnapshot:ye.displayNameSnapshot??ye.nodeId,nodeId:ye.nodeId,version:"runtime",transport:"wan",status:"connected"}));Zm(eT(ut,on)),ef(Pe.map(ye=>({clientId:ye.clientId,clientKind:ye.clientKind,displayLabel:ye.displayLabel,self:ye.self})))}catch(M){if(ew(M)){m=!1,w&&clearInterval(w),w=null;return}}};await b(),w=setInterval(b,3e4),!m&&w&&(clearInterval(w),w=null)})(),()=>{m=!1,w&&clearInterval(w)}},[At]),lt(()=>{let m=!0;if(y)return y(!0).then(w=>{m&&xi(w)}).catch(w=>{Ee.debug("[InkREPL] Background model refresh failed:",w.message)}),()=>{m=!1}},[y]);let we=Fl(()=>new Set(DN.map(m=>`${m.provider}:${m.id}`)),[]),qe=Fl(()=>Jg(Dr),[Dr]),ho=qe.map(m=>({name:m.shortName,value:FN(m),description:m.description||"",provider:m.provider,isCurrent:m.shortName===le,knownModel:we.has(`${m.provider}:${m.id}`)})),It=V(async()=>{try{let{resultFrame:m}=await H("arion.list",{});if(!m)throw new Error("arion.list produced no result frame");if(!m.ok)throw new Error(m.error.message);let w=m.result.arions??[];fe(w.map(p=>({name:p.name,emoji:p.emoji,color:p.color,description:p.personality?.traits?.slice(0,2).join(", ")||"",isActive:e.isActive(p.name),isResting:p.status==="resting"})))}catch(m){Ee.warn("Failed to refresh arions list:",m.message)}},[H,e]),ar=V(async()=>{let m=e.getPrimary();if(m){let w=await e.getArionMemoria(m);if(w)return w}return n.components.memoria},[e,n]),gd=V(async()=>{ac(!0);try{let m=await ar(),w=await m.list({limit:100});zm(w.map(g=>({id:g.id,content:g.content,network:g.network,createdAt:g.createdAt??new Date,importance:g.importance})));let p=await m.count();Ke(p)}catch(m){zm([]),_(w=>[...w,ee(`Failed to load memories: ${m.message}`)])}finally{ac(!1)}},[ar]),E0=V(()=>{if(i)try{let w=ao.current*en,p=i.listSessions(en,w);yi(p)}catch(m){Ee.warn("Failed to load sessions:",m)}},[i]),_0=V(m=>{if(i)try{let w=m.trim();if(us.current=w,ao.current=0,_n.current&&(clearTimeout(_n.current),_n.current=null),!w){yi(i.listSessions(en,0));return}let p=++lc.current;_n.current=setTimeout(()=>{try{let g=i.searchSessionsFts(w,en,0);if(p!==lc.current||us.current!==w)return;yi(g)}catch(g){Ee.warn("Failed to execute scheduled session search:",g)}},120)}catch(w){Ee.warn("Failed to search sessions:",w)}},[i]);lt(()=>()=>{_n.current&&(clearTimeout(_n.current),_n.current=null)},[]);let C0=V(m=>{if(i)try{let w=m==="next"?ao.current+1:Math.max(0,ao.current-1),p=w*en,g=us.current,b=g?i.searchSessionsFts(g,en,p):i.listSessions(en,p);if(m==="next"&&b.length===0)return;ao.current=w,yi(b)}catch(w){Ee.warn("Failed to paginate sessions:",w)}},[i]);lt(()=>{let m=new AbortController;return(async()=>{if(i)try{let p=await ar();if(m.signal.aborted)return;let g=await AN({sessionHistory:i,memoria:p,router:r,signal:m.signal});!m.signal.aborted&&g.recovered>0&&Ee.debug(`[InkREPL] Recovered learning from ${g.recovered} incomplete session${g.recovered===1?"":"s"}.`)}catch(p){Ee.warn("[InkREPL] Crash recovery failed:",p)}})(),()=>{m.abort()}},[i,ar,r]);let pf=V(async m=>{try{let w=await ar();"session"in w&&typeof w.session=="function"&&w.session(m),"endSession"in w&&typeof w.endSession=="function"&&(Nt.current=w,Rt.memoriaSession=Nt.current)}catch(w){Ee.warn("[InkREPL] Memoria session start failed (non-critical):",w)}},[ar]),hf=V(async m=>{if(!(!m||!Nt.current))try{await Nt.current.endSession(m)}catch(w){Ee.warn("[InkREPL] Memoria session end failed (non-critical):",w)}},[]),wd=V(m=>{nn.current=fi(Ad(m).filter(w=>w.role!=="system"))},[]),Bi=V(m=>{if(!i)return;let w=i.loadSessionMessages(m);w&&wd(w.messages)},[i,wd]),Hi=V(()=>{vn(m=>m+1)},[]),{columns:R0,rows:A0}=ft(),gw=Ae(!0);lt(()=>{if(gw.current){gw.current=!1;return}let m=setTimeout(()=>{process.stdout.write("\x1B[2J\x1B[H"),Hi()},100);return()=>clearTimeout(m)},[R0,A0,Hi]);let yd=V((m,w)=>{try{ig({sessionId:m,arionName:w,pid:process.ppid||process.pid,timestamp:new Date().toISOString()})}catch(p){Ee.debug(`[InkREPL] Failed to publish relaunch marker: ${p instanceof Error?p.message:String(p)}`)}},[]),go=V(async m=>{if(i&&!oe.current)try{cr("ink-repl:resume:session.load");let{resultFrame:w}=await H("session.load",{sessionId:m});if(Kt(),!w)throw new Error("session.load produced no result frame");if(!w.ok){_(j=>[...j,ee(w.error.message||`Session not found: ${m}`)]);return}let p=w.result,g=p.session;if(!g){_(j=>[...j,ee(`Session not found: ${m}`)]);return}let b=g.messages,M=i.getSessionRuntimeState(m);if(!M||M.stateStatus!=="completed"){cr("ink-repl:resume:jsonlCrashRecovery");let j=process.env.ARIA_HOME??`${process.env.HOME}/.aria`,W=g.arion||e.getPrimary()?.name||"ARIA",me=ym(j,W,m),{messages:Pe,backfillMessages:ut}=wm(g.messages,me);if(b=Pe,ut.length>0){for(let on of ut)i.addConversationMessage(m,on);Ee.debug(`[InkREPL] JSONL\u2192SQLite backfill: ${ut.length} messages recovered`)}Kt()}e.clearHistory(),ge.current=m,kl(m),ag(g.arion||e.getPrimary()?.name||"ARIA"),yd(m,g.arion||e.getPrimary()?.name||"ARIA"),Rt.sessionId=m,await new Promise(j=>setTimeout(j,0)),cr("ink-repl:resume:setSessionMessages"),wd(b),Kt(),Hi(),_([q(`Resumed session (${b.length} messages from ${g.arion})`),...b]),fr([]),In(void 0),cr("ink-repl:resume:appendSessionHistory");for(let j of b){if(j.role==="tool")continue;let W=j.content.filter(me=>me.type==="text").map(me=>me.text).join("");j.role==="assistant"&&!W||fo({role:j.role,content:W,arion:j.arion?.name})}Kt(),p.pendingInteraction&&await hd.current?.({pendingInteraction:{interactionId:p.pendingInteraction.interactionId,source:p.pendingInteraction.source,interaction:p.pendingInteraction.prompt},startedAt:Date.now(),abortSignal:new AbortController().signal})}catch(w){Kt(),_(p=>[...p,ee(`Error resuming session: ${Zg(w)}`)])}},[i,e,hf,pf,H,yd,fo,wd,Hi]),ww=V(async m=>{let w=Array.isArray(m.result.messages)?fi(structuredClone(m.result.messages.filter(M=>M.role!=="system"))):nn.current,p=nn.current.length,g=w.slice(p);if(g.length>0){let M=Xi(g,{arion:m.respondingArionName?{name:m.respondingArionName,emoji:"\u{1F98B}"}:void 0}),O=ge.current;i&&O&&i.addConversationMessages(O,M),_(j=>[...j,...M])}nn.current=w;let b=m.result.usage;if(An(M=>({...M,...typeof m.result.turnCount=="number"?{turnCount:m.result.turnCount}:{},...typeof b?.totalTokens=="number"?{totalTokens:b.totalTokens}:{},...typeof b?.estimatedCost=="number"?{estimatedCost:b.estimatedCost}:{}})),m.result.state)return m.result.state;if(!m.result.success)throw Object.assign(new Error(Yg(m.result.error??"Run resume failed",m.result.diagnostic)??m.result.error??"Run resume failed"),{...m.result.diagnostic===void 0?{}:{diagnostic:m.result.diagnostic}});ys(w,m.respondingArionName),je((Date.now()-m.startedAt)/1e3);try{let O=await(await ar()).count();Ke(O)}catch(M){Ee.warn("Memory finalization failed:",M)}return await It(),null},[ys,ar,It,i]),xd=V(async m=>{if(!At)throw new Error("Headless run kernel unavailable for REPL resume");if(!await kn(m.abortSignal))throw new Error("Local runtime control unavailable for REPL resume");let p=null,g=null;for await(let b of At.dispatch({kind:"interaction.respond",requestId:`${ge.current??"session"}:interaction:${sc()}`,interactionId:m.interactionId,response:m.response},{signal:m.abortSignal})){if(m.abortSignal?.aborted)break;b.kind==="interaction.required"?p={interactionId:b.interactionId,source:b.source,interaction:b.interaction}:b.kind==="result"&&(g=b)}if(m.abortSignal?.aborted)return p;if(!g)throw new Error("Headless run interaction produced no result frame");if(g.ok)return await ww({result:g.result,respondingArionName:m.respondingArionName,startedAt:m.startedAt}),null;if(g.error.code==="INTERACTION_REQUIRED")return p;throw Object.assign(new Error(g.error.message),{...g.error.details===void 0?{}:{diagnostic:g.error.details}})},[At,ww,kn]),Sd=V(async m=>{let w=m.pendingInteraction;for(;w?.interaction.kind==="tool_approval"&&!m.abortSignal.aborted;){let p=await ce({toolName:w.interaction.toolName,input:w.interaction.toolInput,riskLevel:PN(w.interaction.riskLevel),...w.interaction.issues?.length?{issues:w.interaction.issues}:{}});w=await xd({interactionId:w.interactionId,response:{kind:"confirm",approved:p},respondingArionName:m.respondingArionName,startedAt:m.startedAt,abortSignal:m.abortSignal})}if(!m.abortSignal.aborted){if(w?.interaction.kind==="questionnaire"){let p=w.interaction.questions;B({interactionId:w.interactionId,questions:p,answers:[],...m.respondingArionName?{respondingArionName:m.respondingArionName}:{},startedAt:m.startedAt}),_(g=>[...g,q(r0(p[0],0,p.length))]),fr([]),await It();return}if(w){let p=w.interaction.kind==="tool_approval"?`Run paused: approval required for ${w.interaction.toolName}${t0(w.interaction.toolInput)?` (${t0(w.interaction.toolInput)})`:""}.`:"Run paused and requires interaction to continue.";_(g=>[...g,q(p)]),fr([]),await It()}}},[It,ce,xd]);hd.current=Sd;let Mn=V(m=>{if(oe.current){Y.current=Y.current?Y.current+`
|
|
474
|
-
|
|
475
|
-
`+m:m,$e(Y.current);return}(async()=>{if(ot){Pi(m);let Ie=[...ot.answers,m];if(Ie.length<ot.questions.length){B({...ot,answers:Ie}),_(Ge=>[...Ge,q(r0(ot.questions[Ie.length],Ie.length,ot.questions.length))]);return}xt.current=new AbortController;let ke=xt.current.signal;oe.current=!0,E({type:"START_TURN"}),B(null);try{let Ge=await xd({interactionId:ot.interactionId,response:{kind:"questionnaire",answers:Ie},respondingArionName:ot.respondingArionName,startedAt:ot.startedAt,abortSignal:ke});await Sd({pendingInteraction:Ge,respondingArionName:ot.respondingArionName,startedAt:ot.startedAt,abortSignal:ke})}catch(Ge){$i(Ge),_(sn=>[...sn,ee(`Error: ${Ge.message}`)])}finally{xt.current=null,oe.current=!1,E({type:"DISCARD_STREAMING"}),fr([])}return}let w=MT(m);if(w&&Ui.current){await Ui.current(w.command,w.args);return}lT(),xt.current=new AbortController;let p=xt.current.signal;oe.current=!0,E({type:"START_TURN"});let g=RN(m);if(i&&!ge.current)try{let ke=e.getPrimary()?.name||"ARIA";ge.current=i.createSession(ke,le),kl(ge.current),ag(ke),yd(ge.current,ke),Rt.sessionId=ge.current;try{let Ge=process.send;typeof Ge=="function"&&Ge({type:"aria-relaunch",resumeSessionId:ge.current,arionName:ke})}catch{}await pf(ge.current)}catch(Ie){Ee.warn("[InkREPL] SQLite session creation failed (non-fatal):",Ie)}if(!Rt.jsonlLogger&&rn.persistence.jsonlEnabled){let Ie=e.getPrimary()?.name||"ARIA",Ge=`${process.env.ARIA_HOME??`${process.env.HOME}/.aria`}/arions/${Ie}/logs`;Rt.jsonlLogger=new kN({logDir:Ge,sessionId:ge.current||sc(),retentionDays:rn.persistence.jsonlRetentionDays,maxSizeMb:rn.persistence.jsonlMaxSizeMb}),Rt.jsonlLogger.rotate().catch(sn=>{Ee.warn("[InkREPL] JSONL log rotation failed:",sn)})}for(let Ie of g.mentions)if(!e.isActive(Ie))try{await e.activate(Ie)}catch(ke){let Ge=ke.message?.toLowerCase()||"";!Ge.includes("not found")&&!Ge.includes("unknown")&&Ee.warn(`Failed to activate @${Ie}:`,ke.message)}let b=[];for(let Ie of g.mentions){let ke=e.getActiveArions().find(Ge=>Ge.name.toLowerCase()===Ie.toLowerCase());ke&&b.push(ke)}if(b.length===0){let Ie=e.getPrimary();Ie&&b.push(Ie)}Pi(m),fr([]),In(void 0);let M=Date.now();Ss(0),Tc.current=M,An({turnCount:0,totalTokens:0,estimatedCost:0,wallTimeSeconds:0,contextTokens:0,contextStale:!1}),yt.current&&clearInterval(yt.current),Ec.current=0,yt.current=null;let O=new is,j=100,W=!1,me=setInterval(()=>{let Ie=Math.floor((Date.now()-Tc.current)/1e3);Ie!==Ec.current&&(Ec.current=Ie,ye={...ye??{},wallTimeSeconds:Ie}),ye&&(An(ke=>({...ke,...ye})),ye=null),W&&O.hasPendingContent()&&(E({type:"UPDATE_STREAM",snapshot:[...O.snapshot()]}),W=!1)},j),Pe,ut=[],on=Nr(),ye=null;try{Pe=(await e.getRespondingArions(m,b,[]))[0]?.arion||e.getPrimary(),bc(Pe?.name),po.current=Pe?.name,Pe&&O.setArion({name:Pe.name,emoji:Pe.emoji??"\u{1F98B}",color:Pe.color??void 0}),O.setVerb(on.present);let ke=ue();if(!At)throw new Error("Headless run kernel unavailable for REPL submit");let Ge=await kn(p);if(p.aborted)return;if(!Ge)throw new Error("Local runtime control unavailable for REPL submit");ut=fi([...nn.current]);let sn=ge.current,Cs=null,yo=null,z0=EN(co.current).length>0?"pause":"approve",K0={task:m,arion:po.current||Pe?.name||ke.activeArion||"ARIA",cwd:process.cwd(),...ut.length>0?{history:ut}:{},...A.current?{requestedModel:A.current}:{},...ke.preferredTier?{preferredTier:ke.preferredTier}:{},autonomy:co.current,approvalMode:z0};for await(let Se of At.dispatch({kind:"request",requestId:sn??sc(),op:"run.start",input:K0},{signal:p})){if(p.aborted)break;if(Se.kind==="interaction.required"){Cs={interactionId:Se.interactionId,source:Se.source,interaction:Se.interaction};continue}if(Se.kind==="result"){yo=Se;continue}let J=Se.event;if(Rt.jsonlLogger?.log(J),uT(J),(J.type==="handoff_start"||J.type==="handoff_result")&&J.type==="handoff_result"){let He=e.getActiveArions().find(Ot=>Ot.name.toLowerCase()===J.target.toLowerCase());He&&(Pe=He,O.setArion({name:He.name,emoji:He.emoji??"\u{1F98B}",color:He.color??void 0}))}if(J.type==="span_start"){let He="parentSpanId"in J&&typeof J.parentSpanId=="string"?J.parentSpanId:void 0;fr(Ot=>[...Ot,{spanId:J.spanId,spanType:J.spanType,name:J.name,startTime:Date.now(),...He?{parentSpanId:He}:{}}])}if(J.type==="span_end"&&fr(He=>He.map(Ot=>Ot.spanId===J.spanId?{...Ot,endTime:Date.now(),durationMs:J.durationMs}:Ot)),J.type==="pipeline_timing"&&In(J.report),J.type==="error")throw new Error(Yg(J.error.message,"diagnostic"in J.error?J.error.diagnostic:void 0)??J.error.message);if(J.type==="usage_update"){let He=J.usage;if(typeof He.inputTokens=="number"&&typeof He.outputTokens=="number"&&O.setTokenUsage({input:He.inputTokens,output:He.outputTokens}),ye={...ye??{},...typeof He.totalTokens=="number"?{totalTokens:He.totalTokens}:{},...typeof He.estimatedCost=="number"?{estimatedCost:He.estimatedCost}:{},...typeof He.inputTokens=="number"?{contextTokens:He.inputTokens}:{},contextStale:!1},"model"in J&&typeof J.model=="string"){let Ot=LN(J.model);Ot!==le&&(N(Ot),A.current=Ot)}}if(J.type==="turn_complete"&&(ye={...ye??{},turnCount:J.turnNumber}),J.type==="tool_result"&&(ye={...ye??{},contextStale:!0}),O.ingest(J)==="flush"){let He=O.flush(),Ot=ge.current;if(i&&Ot)for(let Ed of He)i.addConversationMessage(Ot,Ed);E({type:"COMMIT_TURN",flushed:He}),W=!1}else W=!0}if(fd(null),dT(),clearInterval(me),W&&O.hasPendingContent()&&(E({type:"UPDATE_STREAM",snapshot:[...O.snapshot()]}),W=!1),yt.current&&(clearInterval(yt.current),yt.current=null),An(Se=>({...Se,wallTimeSeconds:(Date.now()-Tc.current)/1e3})),O.hasPendingContent()){let Se=O.flush(),J=ge.current;if(i&&J)for(let zt of Se)i.addConversationMessage(J,zt);E({type:"COMMIT_AND_END",flushed:Se})}else E({type:"COMMIT_AND_END",flushed:[]});fr([]),je((Date.now()-M)/1e3),await new Promise(Se=>setTimeout(Se,0));let Td=O.getSnapshotMessages()?.filter(Se=>Se.role!=="system"),yf=!!(Td&&Td.length>0);if(yf){let Se=performance.now();cr("ink-repl:structuredClone");let J=structuredClone(Td),zt=performance.now();cr("ink-repl:repairToolCallPairing"),nn.current=fi(J);let He=performance.now();Kt();let Ot=zt-Se,Ed=He-zt;if(process.env.DEBUG&&Ot+Ed>100)try{process.stderr.write(`[InkREPL][DIAG] post-processing: structuredClone=${Ot.toFixed(0)}ms repairToolCallPairing=${Ed.toFixed(0)}ms (${Td.length} msgs)
|
|
476
|
-
`)}catch{}}else i&&ge.current&&(cr("ink-repl:refreshSessionMessagesFromStorage"),Bi(ge.current),Kt());if(p.aborted){if(O.hasPendingContent()){let Se=O.flush(),J=ge.current;if(i&&J)for(let zt of Se)i.addConversationMessage(J,zt);E({type:"COMMIT_AND_END",flushed:Se})}else E({type:"DISCARD_STREAMING"});i&&ge.current&&Bi(ge.current),fr([]),oe.current=!1,xt.current=null,yt.current&&(clearInterval(yt.current),yt.current=null)}if(!p.aborted){if(oe.current=!1,!yo)throw new Error("Headless run produced no result frame");if(Cs){if(O.hasPendingContent()){let Se=O.flush(),J=ge.current;if(i&&J)for(let zt of Se)i.addConversationMessage(J,zt);_(zt=>[...zt,...Se]),!yf&&J&&Bi(J)}await Sd({pendingInteraction:Cs,...Pe?.name?{respondingArionName:Pe.name}:{},startedAt:M,abortSignal:p})}else{if(!yo.ok)throw Object.assign(new Error(yo.error.message),{...yo.error.details===void 0?{}:{diagnostic:yo.error.details}});if(O.hasPendingContent()){let Se=O.flush(),J=ge.current;if(i&&J)for(let zt of Se)i.addConversationMessage(J,zt);_(zt=>[...zt,...Se]),!yf&&J&&Bi(J)}ys(nn.current,Pe?.name),ar().then(Se=>Se.count()).then(Se=>Ke(Se)).catch(Se=>Ee.warn("Memory finalization failed:",Se)),It().catch(Se=>Ee.warn("Arion list refresh failed:",Se))}}}catch(Ie){$i(Ie),clearInterval(me);try{if(O.hasPendingContent()){let ke=O.flush(),Ge=ge.current;if(i&&Ge){for(let sn of ke)i.addConversationMessage(Ge,sn);Bi(Ge)}E({type:"COMMIT_AND_END",flushed:ke})}else E({type:"DISCARD_STREAMING"})}catch(ke){Ee.warn("[InkREPL] Failed to persist messages on error path:",ke?.message)}fd(null),yt.current&&(clearInterval(yt.current),yt.current=null),oe.current=!1,fr([]),_(ke=>[...ke,ee(`Error: ${Ie.message}`)])}let Dn=Y.current;Dn&&(Y.current=null,$e(null),setTimeout(()=>Mn(Dn),0))})().catch(w=>{$i(w),oe.current=!1,E({type:"DISCARD_STREAMING"}),_(g=>[...g,ee(`Error: ${w.message}`)]);let p=Y.current;p&&(Y.current=null,$e(null),setTimeout(()=>Mn(p),0))})},[r,e,t,Be,It,n,ar,ys,pf,Sd,At,yd,$i,le,xd,i,Bi,R,kn]),yw=Ae(Mn);yw.current=Mn,lt(()=>{let m=f||xm();if(!m){sr.current=Promise.resolve();return}m&&!dt.current&&(dt.current=!0,sr.current=go(m))},[f,go]),lt(()=>{if(!d||We.current)return;let m=!1;return(async()=>((f||xm())&&await sr.current,!(m||We.current)&&(We.current=!0,await Mn(d))))(),()=>{m=!0}},[d,Mn,f]);let I0=V(()=>{xt.current&&(xt.current.abort(),xt.current=null,oe.current=!1,E({type:"DISCARD_STREAMING"}),yt.current&&(clearInterval(yt.current),yt.current=null))},[]),v0=V(()=>{let m=Y.current;m&&(Y.current=null,$e(null),wf(m))},[]),k0=V(()=>{Sc(m=>{let w=pT(m);return Ts(p=>{let g=hT(m,p);return gT(w,g)}),w})},[]),M0=V(()=>{Ts(m=>({...m,showThinking:!m.showThinking}))},[]),D0=V(()=>{Ts(m=>({...m,showCosts:!m.showCosts}))},[]),L0=V(()=>{Ts(m=>({...m,showTraces:!m.showTraces}))},[]),xw=V(async(m,w)=>{switch(m){case"help":{let p=Jh.map(g=>`/${g.name} - ${g.description}`).join(`
|
|
477
|
-
`);_(g=>[...g,q(p)]);break}case"arions":{try{let{resultFrame:p}=await H("arion.list",{});if(!p)throw new Error("arion.list produced no result frame");if(!p.ok)throw new Error(p.error.message);let b=(p.result.arions??[]).map(M=>`${M.emoji} ${M.name} (${M.status})`).join(`
|
|
478
|
-
`);_(M=>[...M,q(b||"No arions found")])}catch(p){_(g=>[...g,ee(`Failed to list arions: ${p.message}`)])}break}case"sound":{let p=w?.trim().toLowerCase();if(p==="on"||p==="off"){let g=p==="on";Yh(g);let b=ue();b.soundEnabled=g,Le(b),_(M=>[...M,q(`Sound notifications ${g?"enabled":"disabled"}.`)])}else{let g=iT()?"on":"off";_(b=>[...b,q(`Sound notifications: ${g}
|
|
479
|
-
Usage: /sound on | /sound off`)])}break}case"exit":{I();break}case"hatch":{let p=w?.trim();if(!p){_(g=>[...g,q(`Usage: /hatch <name> [description]
|
|
480
|
-
Example: /hatch Luna a dreamy, creative assistant
|
|
481
|
-
|
|
482
|
-
Describe the arion you want to create and ARIA will help design and hatch them.`)]);break}try{let g=p.split(/\s+/),b=g[0],M=g.slice(1).join(" "),{resultFrame:O}=await H("arion.hatch",{name:b,...M?{description:M}:{}});if(!O)throw new Error("arion.hatch produced no result frame");if(!O.ok)throw new Error(O.error.message);let j=O.result.prompt;if(!j)throw new Error("arion.hatch did not return a prompt");await Mn(j)}catch(g){_(b=>[...b,ee(`Error: ${g.message}`)])}break}case"remember":{try{let{resultFrame:p}=await H("memory.remember",{text:w??""});if(!p)throw new Error("memory.remember produced no result frame");if(!p.ok)throw new Error(p.error.message);let g=p.result;_(M=>[...M,q(String(g.message??"Memory saved."))]);let b=g.data?.count;typeof b=="number"&&Ke(b)}catch(p){_(g=>[...g,ee(`Error remembering: ${p.message}`)])}break}case"recall":{try{let{resultFrame:p}=await H("memory.recall",{query:w??""});if(!p)throw new Error("memory.recall produced no result frame");if(!p.ok)throw new Error(p.error.message);let g=p.result,b=g.memories,M=String(g.message??"No memories found.");if(Array.isArray(b)&&b.length>0){let O=b.map((j,W)=>{let me=j,Pe=typeof me.content=="string"?me.content:String(j),ut=Pe.length>80?Pe.slice(0,80)+"...":Pe,on=typeof me.confidence=="number"?`(${Math.round(me.confidence*100)}%) `:"",ye=me.createdAt instanceof Date?me.createdAt.toISOString().slice(0,10):String(me.createdAt??"").slice(0,10),Dn=typeof me.id=="string"?me.id.slice(0,8):"unknown",Ie=typeof me.network=="string"&&me.network.trim().length>0?me.network:"default";return`[${W+1}] ${on}${ut} [${Ie}] ${ye} (${Dn})`}).join(`
|
|
483
|
-
`);M=`Found ${b.length} memories:
|
|
484
|
-
${O}`}_(O=>[...O,q(M)])}catch(p){_(g=>[...g,ee(`Error recalling: ${p.message}`)])}break}case"recall_knowledge":{if(w?.trim())try{let{resultFrame:p}=await H("memory.recall_knowledge",{topic:w.trim(),limit:5});if(!p)throw new Error("memory.recall_knowledge produced no result frame");if(!p.ok)throw new Error(p.error.message);let g=p.result,b=Array.isArray(g.tools)?g.tools:[];if(b.length===0)_(M=>[...M,q(`No tools found for: "${w.trim()}"`)]);else{let M=b.map((O,j)=>{let W=O.description.length>80?O.description.slice(0,80)+"...":O.description;return`[${j+1}] ${O.name} - ${W}`}).join(`
|
|
485
|
-
`);_(O=>[...O,q(`Found ${b.length} tool items:
|
|
486
|
-
${M}`)])}}catch(p){_(g=>[...g,ee(`Error recalling tools: ${p.message}`)])}else _(p=>[...p,q(`Usage: /recall_knowledge <topic>
|
|
487
|
-
Searches stored tools (skills, procedures, techniques) by topic.`)]);break}case"send":{try{let p=e.getPrimary()?.name??"ARIA",{resultFrame:g}=await H("message.send",{args:w??"",senderName:p});if(!g)throw new Error("message.send produced no result frame");let b=g.ok?g.result:{message:g.error.message};_(M=>[...M,g.ok?q(b.message??"Message sent."):ee(b.message??"Failed to send message.")])}catch(p){_(g=>[...g,ee(`Failed to send peer message: ${p.message}`)])}break}case"clear":{if(oe.current)break;let p=ge.current;p&&await hf(p),e.clearHistory(),nn.current=[],ge.current=null,kl(null),Rt.sessionId=null,Rt.jsonlLogger&&(Rt.jsonlLogger.close().catch(g=>{Ee.warn("[InkREPL] JSONL logger close failed:",g?.message??g)}),Rt.jsonlLogger=null),fr([]),In(void 0),process.stdout.write("\x1B[2J\x1B[H"),Hi(),_([q("Conversation cleared.")]);break}case"resume":{w?.trim()?await go(w.trim()):ql(p=>(p??0)+1);break}case"fork":{if(oe.current)break;let p=w?.trim().split(/\s+/).filter(Boolean)??[],g=p.includes("--stay"),b=p.filter(j=>j!=="--stay"),M=ge.current,O;if(b.length===1&&/^\d+$/.test(b[0])?O=parseInt(b[0],10):b.length>=1&&b[0]&&(M=b[0],b[1]&&/^\d+$/.test(b[1])&&(O=parseInt(b[1],10))),!M){_(j=>[...j,q("No active session to fork. Start a conversation first or specify a session ID: /fork <session-id>")]);break}try{let{resultFrame:j}=await H("session.fork",{sessionId:M,...O!==void 0?{messageLimit:O}:{}});if(!j)throw new Error("session.fork produced no result frame");if(!j.ok)throw new Error(j.error.message);let W=j.result;g?_(me=>[...me,q(`\u{1F374} Forked \u2192 ${W.newSessionId.slice(0,8)} (${W.messagesCopied} msgs). Resume it later with /resume ${W.newSessionId.slice(0,8)}`)]):(_(me=>[...me,q(`\u{1F374} Forked ${W.sourceSessionId.slice(0,8)}\u2192${W.newSessionId.slice(0,8)} (${W.messagesCopied} msgs)`)]),await go(W.newSessionId))}catch(j){_(W=>[...W,ee(`Fork failed: ${j.message}`)])}break}case"rest":{let p=w?.trim();if(!p){_(g=>[...g,q("Usage: /rest <arion-name>")]);break}try{let{resultFrame:g}=await H("arion.rest",{name:p});if(!g)throw new Error("arion.rest produced no result frame");if(!g.ok)throw new Error(g.error.message);_(b=>[...b,q(`${p} is now resting.`)]),await It()}catch(g){_(b=>[...b,ee(`Cannot rest ${p}: ${g.message}`)])}break}case"wake":{let p=w?.trim();if(!p){_(g=>[...g,q("Usage: /wake <arion-name>")]);break}try{let{resultFrame:g}=await H("arion.wake",{name:p});if(!g)throw new Error("arion.wake produced no result frame");if(!g.ok)throw new Error(g.error.message);_(b=>[...b,q(`${p} is now awake.`)]),await It()}catch(g){_(b=>[...b,ee(`Cannot wake ${p}: ${g.message}`)])}break}case"become":{let p=w?.trim();if(!p){_(g=>[...g,q("Usage: /become <arion-name>")]);break}try{let{resultFrame:g}=await H("arion.become",{name:p});if(!g)throw new Error("arion.become produced no result frame");if(!g.ok)throw new Error(g.error.message);let b=g.result.arion;if(!b)throw new Error(`Arion ${p} not found`);let O=ue().preferredTier||"balanced",j=Qg(O,S),W=b.preferredModel||j?.shortName||a;po.current=b.name,bc(b.name),N(W),A.current=W,_(ut=>[...ut,q(`Switched to ${b.name} (model: ${W})`)]);let Pe=await(await ar()).count();Ke(Pe),await It()}catch(g){_(b=>[...b,ee(`Cannot become ${p}: ${g.message}`)])}break}case"model":{let p=w?.trim()||"",g=p.toLowerCase();if(g==="refresh"){_(b=>[...b,q("Discovering models from all providers...")]);try{let{resultFrame:b}=await H("model.refresh",{});if(!b)throw new Error("model.refresh produced no result frame");if(!b.ok)throw new Error(b.error.message);let M=b.result.models??Dr,O=Jg(M);_(j=>[...j,q(`Updated model catalog (${O.length} selectable models)`)])}catch(b){_(M=>[...M,ee(`Discovery failed: ${b.message}`)])}break}if(!g||g==="list")try{let{resultFrame:b}=await H("model.list",{});if(!b)throw new Error("model.list produced no result frame");if(!b.ok)throw new Error(b.error.message);let M=b.result.models??Dr,O=b.result.currentModel??le,W=Jg(M).map(me=>` ${me.shortName.toLowerCase()===O.toLowerCase()?"\u2192 ":" "}${me.provider}/${me.shortName} (${me.tier})`).join(`
|
|
488
|
-
`);_(me=>[...me,q(`Current model: ${O}
|
|
489
|
-
|
|
490
|
-
Available models:
|
|
491
|
-
${W}
|
|
492
|
-
|
|
493
|
-
Use /model <name> or /model <provider>/<name> to switch.`)])}catch(b){_(M=>[...M,ee(`Model listing failed: ${b.message}`)])}else try{let{resultFrame:b}=await H("model.set",{model:p});if(!b)throw new Error("model.set produced no result frame");if(!b.ok)throw new Error(b.error.message);let M=b.result.currentModel??p;_(O=>[...O,q(`Switched model to ${M}`)])}catch(b){_(M=>[...M,ee(`Unknown model: ${p}. Use /model list to see available models. ${b.message}`)])}break}case"autonomy":{if(w&&w.trim())try{let p=w.trim().toLowerCase(),{resultFrame:g}=await H("config.autonomy.set",{autonomy:p});if(!g)throw new Error("config.autonomy.set produced no result frame");if(!g.ok)throw new Error(g.error.message);_(b=>[...b,q(`Autonomy level set to: ${p}`)])}catch(p){_(g=>[...g,ee(`Invalid autonomy level: ${w.trim().toLowerCase()}. ${p.message}`)])}else Si(!0);break}case"memories":{try{let{resultFrame:p}=await H("memory.list",{limit:20});if(!p)throw new Error("memory.list produced no result frame");if(!p.ok)throw new Error(p.error.message);let g=p.result,b=typeof g.count=="number"?g.count:0;if(b===0)_(M=>[...M,q("No memories stored. Use /remember to store memories.")]);else{let O=(Array.isArray(g.memories)?g.memories:[]).map(j=>` [${j.id.slice(0,8)}] ${j.content.slice(0,80)}${j.content.length>80?"...":""}`).join(`
|
|
494
|
-
`);_(j=>[...j,q(`Memories (${b} total):
|
|
495
|
-
${O}`)])}}catch(p){_(g=>[...g,ee(`Failed to list memories: ${p.message}`)])}break}case"forget":{try{let{resultFrame:p}=await H("memory.forget",{id:w??""});if(!p)throw new Error("memory.forget produced no result frame");if(!p.ok)throw new Error(p.error.message);let g=p.result;_(b=>[...b,q(String(g.message??"Memory deleted."))]),typeof g.count=="number"&&Ke(g.count)}catch(p){_(g=>[...g,ee(`Failed to delete memory: ${p.message}`)])}break}case"restart":{let p=w?.trim()||"User requested /restart";_(g=>[...g,q("Restarting ARIA...")]),setTimeout(()=>{(async()=>{try{let{resultFrame:g}=await H("system.restart",{reason:p});if(!g)throw new Error("system.restart produced no result frame");if(!g.ok)throw new Error(g.error.message)}catch(g){_(b=>[...b,ee(`Restart preparation failed: ${g.message}`)])}try{await ET(p,ge.current)}catch(g){_(b=>[...b,ee(`Restart failed: ${g.message}`)])}})()},100);break}case"terminal-setup":{try{let{resultFrame:p}=await H("system.terminal_setup",{});if(!p)throw new Error("system.terminal_setup produced no result frame");if(!p.ok)throw new Error(p.error.message);let g=p.result;_(b=>[...b,q(g.supported===!1?g.message??"terminal-setup is unavailable.":g.output??"")])}catch(p){_(g=>[...g,ee(`terminal-setup failed: ${p.message}`)])}break}case"login":{try{await Lr("auth.login",w??"")}catch(p){_(g=>[...g,ee(`Login failed: ${p.message}`)])}break}case"logout":{try{await Lr("auth.logout",w??"")}catch(p){_(g=>[...g,ee(`Logout failed: ${p.message}`)])}break}case"theme":{let p=(w??"").trim().toLowerCase();if(!p){Gl(g=>(g??0)+1);break}try{let{resultFrame:g}=await H("config.theme.set",{theme:p});if(!g)throw new Error("config.theme.set produced no result frame");if(!g.ok)throw new Error(g.error.message);_(b=>[...b,q(`Theme changed to ${Dd(p)?.displayName??p} (${p})`)])}catch(g){let b=cn();_(M=>[...M,ee(`Unknown theme "${p}". Available: ${b.join(", ")}. ${g.message}`)])}break}case"invite":{await F0(w?.trim());break}case"join":{let p=w?.trim();p?await bw(p):(gc(null),nf(g=>(g??0)+1));break}case"peers":{ld(p=>(p??0)+1);break}case"clients":{mo(p=>(p??0)+1);break}default:{_(p=>[...p,q(`Unknown command: /${m}. Type /help for available commands.`)]);break}}},[t,r,n,le,Dr,qe,S,H,I,ar,Mn,go,hf,a,y,It,e,Hi]);Ui.current=xw;let N0=V(async(m,w)=>{if(w!=="mention")try{if(w==="become"){let{resultFrame:p}=await H("arion.become",{name:m});if(!p)throw new Error("arion.become produced no result frame");if(!p.ok)throw new Error(p.error.message);let g=p.result.arion;if(!g)throw new Error(`Arion ${m} not found`);let M=ue().preferredTier||"balanced",O=Qg(M,S),j=g.preferredModel?e0(g.preferredModel):void 0,W=(j?ic(j,S).shortName:void 0)||O?.shortName||a;N(W),A.current=W,_(ut=>[...ut,q(`Switched to ${g.name} (model: ${W})`)]);let Pe=await(await ar()).count();Ke(Pe)}else if(w==="rest"){let{resultFrame:p}=await H("arion.rest",{name:m});if(!p)throw new Error("arion.rest produced no result frame");if(!p.ok)throw new Error(p.error.message);_(g=>[...g,q(`${m} is now resting`)])}else if(w==="wake"){let{resultFrame:p}=await H("arion.wake",{name:m});if(!p)throw new Error("arion.wake produced no result frame");if(!p.ok)throw new Error(p.error.message);_(g=>[...g,q(`${m} is now awake`)])}await It()}catch(p){_(g=>[...g,ee(`Error: ${p.message}`)])}},[S,H,ar,a,It]),Sw=V(async(m,w)=>{let{resultFrame:p}=await H("model.set",{model:m});if(!p)throw new Error("model.set produced no result frame");if(!p.ok)throw new Error(p.error.message);let g=p.result.currentModel??m;if(w){he(w);let b=ue();b.effortLevel=w,Le(b)}_(b=>[...b,q(`Switched to ${g}`)])},[H]);L.current=Sw;let gf=V(async m=>{try{let{resultFrame:w}=await H("config.theme.set",{theme:m.name});if(!w)throw new Error("config.theme.set produced no result frame");if(!w.ok)throw new Error(w.error.message);_(p=>[...p,q(`Theme changed to ${m.displayName} (${m.name})`)])}catch(w){_(p=>[...p,ee(`Theme change failed: ${w.message}`)])}},[H]),O0=Ae(gf);O0.current=gf;let j0=V(async m=>{if(m.status==="connected"){_(g=>[...g,q(`\u2713 Already connected to ${m.displayNameSnapshot} (same identity, shared server on port ${m.port}).`)]);return}let w=m.host&&CN(m.host);if(!(m.transport==="wan")&&m.host&&!w){_(g=>[...g,ee(`Rejected: ${m.host} is not a private LAN address.`)]);return}try{if(!m.principalFingerprint)throw new Error(`${m.displayNameSnapshot} did not advertise a principal fingerprint`);if(!m.tlsCaFingerprint)throw new Error(`${m.displayNameSnapshot} did not advertise a TLS fingerprint`);if(!m.host||!m.port)throw new Error(`${m.displayNameSnapshot} did not advertise a control endpoint`);let{resultFrame:g}=await H("peer.connect",{nodeId:m.nodeId,displayName:m.displayNameSnapshot,principalFingerprint:m.principalFingerprint,controlEndpoint:{host:m.host,port:m.port,tlsCaFingerprint:m.tlsCaFingerprint,tlsServerIdentity:m.principalFingerprint,protocolVersion:1},transport:m.transport});if(!g)throw new Error("peer.connect produced no result frame");if(!g.ok)throw new Error(g.error.message);let b=g.result.invite;if(!b)throw new Error("peer.connect returned no invite payload");_(M=>[...M,q(b.mode==="wan_pair"?`Paired with ${b.displayNameSnapshot??b.nodeId}. Awaiting verified ingress before the runtime marks the peer active.`:`Paired with ${b.displayNameSnapshot??b.nodeId}. WG tunnel will connect when accepted.`)])}catch(g){_(b=>[...b,ee(`Failed to connect to ${m.displayNameSnapshot}: ${g.message}`)])}},[H]),P0=V(async()=>{if(!tn)return;let{id:m,nodeId:w,displayNameSnapshot:p}=tn,g=p??w;ud(null),_(b=>[...b,q(`Accepting connection from ${g}...`)]);try{let{resultFrame:b}=await H("peer.pending.respond",{requestId:m,accepted:!0});if(!b)throw new Error("peer.pending.respond produced no result frame");if(!b.ok)throw new Error(b.error.message);let M=b.result.response??{};if(M.error)throw new Error(M.error);M.accepted&&_(O=>[...O,q(`Connected to ${g}. Tunnel established.`)])}catch(b){_(M=>[...M,ee(`Failed to accept connection: ${b.message}`)])}},[H,tn]),$0=V(()=>{if(!tn)return;let{id:m,nodeId:w,displayNameSnapshot:p}=tn,g=p??w;ud(null),_(b=>[...b,q(`Rejected connection from ${g}.`)]),H("peer.pending.respond",{requestId:m,accepted:!1}).catch(()=>{})},[H,tn]),F0=V(async m=>{try{let{resultFrame:w}=await H("peer.invite",{...m?.trim()?{inviteLabel:m.trim()}:{}});if(!w)throw new Error("peer.invite produced no result frame");if(!w.ok)throw new Error(w.error.message);let p=w.result.invite;if(!p)throw new Error("peer.invite returned no invite payload");Oi(p)}catch(w){_(p=>[...p,ee(`Failed to create invite: ${w.message}`)])}},[H]),bw=V(async m=>{try{let{resultFrame:w}=await H("peer.accept_invite",{inviteToken:m});if(!w)throw new Error("peer.accept_invite produced no result frame");if(!w.ok)throw new Error(w.error.message);let p=w.result.accepted;if(!p)throw new Error("peer.accept_invite returned no accepted payload");gc(null),_(g=>[...g,q(`Paired with ${p.displayNameSnapshot??p.nodeId}.`)])}catch(w){let p=`Failed to accept invite: ${w.message}`;gc(p),_(g=>[...g,ee(p)])}},[H]);lt(()=>{let m=!0,w=null;return(async()=>(w=setInterval(async()=>{try{let{resultFrame:b}=await H("peer.pending.list",{});if(!m||!b?.ok)return;let M=b.result.requests??[];M.length&&!tn&&ud(M[0])}catch(b){if(ew(b)){w&&clearInterval(w),Rn.current=null;return}}},5e3),Rn.current=w,m||(clearInterval(w),w=null,Rn.current=null)))(),()=>{m=!1,w&&clearInterval(w),Rn.current=null}},[H,tn]);let U0=V(async m=>{Km(m),await gd()},[gd]),B0=V(async m=>{if(wi==="forget")try{let{resultFrame:w}=await H("memory.forget",{id:m.id});if(!w)throw new Error("memory.forget produced no result frame");if(!w.ok)throw new Error(w.error.message);let p=m.content.length>50?m.content.slice(0,50)+"...":m.content;_(g=>[...g,q(`Forgot: "${p}"`)]),await gd()}catch(w){_(p=>[...p,ee(`Error forgetting: ${w.message}`)])}},[H,wi,gd]),Wi=V(()=>{bi(null),Ti(null),Ei(null),_i(null),Ci(null),fs(null),Ri(null),Ai(null),ps(null),Ii(null),vi(null),hs(!1),ki(!1),lo(null),Mi(!1),Li(null),pc(!1),gs(null),hc(null),ad(null),cd(null)},[]),_c=V(m=>{let w=m,p=w.success!==!1,g=w.message??(p?"Authentication updated.":"Auth failed.");_(b=>[...b,p?q(g):ee(g)])},[]),bd=V(async m=>{if(Wi(),m.interaction.kind==="selection"){gs({interactionId:m.interactionId,interaction:m.interaction}),ad(m.interaction.prompt),hc(m.interaction.options.map(w=>({id:w.id,label:w.label,description:w.description,method:w.id,status:w.description?.includes("connected")?"connected":w.description?.includes("available")?"available":"none"})));return}if(m.interaction.kind==="credential_input"){let w=m.interaction.fields[0];if(!w)throw new Error("Auth interaction requires at least one credential field");if(m.interaction.mode==="oauth_authorization_code"&&m.interaction.authorizeUrl&&m.interaction.provider){gs({interactionId:m.interactionId,interaction:m.interaction}),Ei(m.interaction.provider),_i(m.interaction.authorizeUrl),Ci(m.interaction.expectedState??null),fs(w.key);return}gs({interactionId:m.interactionId,interaction:m.interaction}),cd({title:w.label,hint:m.interaction.prompt,fieldKey:w.key});return}if(m.interaction.kind==="oauth_device"){gs({interactionId:m.interactionId,interaction:m.interaction}),Ri(m.interaction.provider??"github-copilot"),Ai(m.interaction.profileLabel??null),ps(m.interaction.verificationUri),Ii(m.interaction.userCode);return}},[_c,Wi,At]),Lr=V(async(m,w)=>{Wi();let{interactionFrame:p,resultFrame:g}=await H(m,{args:w});if(p&&p.source==="auth"){await bd(p);return}if(!g)throw new Error(`${m} produced no result frame`);if(g.ok){_c(g.result);return}throw new Error(g.error.message)},[_c,Wi,H,bd]),wo=V(async m=>{if(!sd)throw new Error("No pending auth interaction to respond to");let{interactionId:w}=sd,p=null,g=null;for await(let b of At.dispatch({kind:"interaction.respond",requestId:`auth:${sc()}`,interactionId:w,response:m}))b.kind==="interaction.required"&&b.source==="auth"?p=b:b.kind==="result"&&(g=b);if(p){await bd(p);return}if(Wi(),!g)throw new Error("auth interaction produced no result frame");if(g.ok){_c(g.result);return}g.error.code!=="INTERACTION_REQUIRED"&&_(b=>[...b,ee(`Login failed: ${g.error.message}`)])},[_c,Wi,At,sd,bd]),H0=Fl(()=>e0(le)?.maxContextTokens,[le]),W0=Fl(()=>v.map((m,w)=>{let g=(Array.isArray(m.content)?m.content:[m.content]).filter(b=>typeof b=="object"&&b!==null&&"type"in b&&b.type==="text").map(b=>b.text).join("").trim();return!g||m.role==="system"?null:{index:w,role:m.role,text:g,arion:m.arion?.name,createdAt:m.createdAt}}).filter(m=>m!==null),[v]),[q0,HO]=U(void 0),[G0,wf]=U(void 0),X0=V(async(m,w)=>{if(!ge.current||oe.current)return;let p=0;for(let b=0;b<m;b++){let M=v[b];M&&M.role!=="system"&&p++}let g=p;try{let{resultFrame:b}=await H("session.fork",{sessionId:ge.current,messageLimit:g});if(!b?.ok){let O=b?.error?.message??"Fork failed";_(j=>[...j,ee(`Edit failed: ${O}`)]);return}let M=b.result;await go(M.newSessionId),wf(w)}catch(b){_(M=>[...M,ee(`Edit failed: ${b.message}`)])}},[v,H,go]);return tw(tT,{staticRenderEpoch:df,session:e,model:le,maxContextTokens:H0,banner:tw(Xp,{onComplete:()=>{},skipAnimation:!0,version:mT,whatsNew:fT}),messages:v,previewMessages:C,isStreaming:ae,queuedMessage:se,onCancelQueuedMessage:v0,responseTime:z,commands:Jh,arions:Qe,models:ho,memories:Zr,memoryBrowserMode:wi,isLoadingMemories:Bl,userName:Be,memoryCount:Xt,metrics:xs,displayMode:md,displayConfig:bs,showThinking:bs.showThinking,showCosts:bs.showCosts,showTraces:bs.showTraces,pipelineTiming:cf,spans:lf,activeArion:uf,onSubmit:Mn,onCommand:xw,onSelectArion:N0,onSelectModel:Sw,onSelectMemory:B0,onOpenMemoryBrowser:U0,onToggleThinking:M0,onToggleCosts:D0,onToggleTraces:L0,onCycleDisplayMode:k0,sessions:Hl,onSelectSession:go,onLoadSessions:E0,onSearchSessions:_0,onLoadMoreSessions:C0,openSessionOverlaySignal:Wl,openThemeOverlaySignal:cc,inviteShare:Ni?{inviteToken:Ni.inviteToken,inviteLabel:Ni.pendingInvite.inviteLabel,expiresAt:Ni.pendingInvite.expiresAt??null}:null,onInviteShareClose:()=>{Oi(null)},openJoinInviteOverlaySignal:rf,onJoinInviteSubmit:bw,onJoinInviteCancel:()=>{gc(null)},joinInviteError:pw,onSelectTheme:gf,inputHistory:c,onSaveInput:l,openMessageEditOverlaySignal:q0,editableMessages:W0,onEditMessage:X0,prefillInput:G0,onPrefillConsumed:()=>wf(void 0),obsCtx:mf,onCancel:I0,approvalRequest:yc,onApprovalChoice:m=>{yc&&(yc.resolve(m),ji(null))},effortLevel:$,showAutonomySelector:Xl,autonomyLevel:uc,onAutonomySelect:m=>{ms(m),Si(!1),_(w=>[...w,q(`Autonomy level set to: ${m}`)])},onCycleAutonomy:()=>{let m=Bm.indexOf(co.current),w=Bm[(m+1)%Bm.length];ms(w)},onCycleEffort:()=>{let m=["low","medium","high","max"],w=m.indexOf($),p=m[(w+1)%m.length];he(p);let g=ue();g.effortLevel=p,Le(g)},onAutonomyCancel:()=>{Si(!1)},authInteractionOptions:id,authInteractionTitle:uo,onAuthInteractionSelect:async m=>{await wo({kind:"selection",selected:m})},onAuthInteractionCancel:async()=>{await wo({kind:"cancel"})},authInteractionInput:Cn?{title:Cn.title,...Cn.hint?{hint:Cn.hint}:{}}:null,onAuthInteractionInputSubmit:async m=>{Cn&&await wo({kind:"credential_input",values:{[Cn.fieldKey]:m}})},onAuthInteractionInputCancel:async()=>{await wo({kind:"cancel"})},loginPickerProviders:zl,onLoginProviderSelect:async m=>{bi(null),await Lr("auth.login",m.id)},onLoginPickerCancel:()=>{bi(null)},anthropicMethodOptions:td,onAnthropicMethodSelect:async m=>{vi(null),await Lr("auth.login",`anthropic --method ${m.id}`)},onAnthropicMethodCancel:()=>vi(null),anthropicKeyInputVisible:rd,onAnthropicKeySubmit:async m=>{hs(!1),await Lr("auth.login",`anthropic ${m}`)},onAnthropicKeyCancel:()=>hs(!1),anthropicSetupTokenVisible:Ym,onAnthropicSetupTokenSubmit:async m=>{ki(!1),await Lr("auth.login",`anthropic --setup-token ${m}`)},onAnthropicSetupTokenCancel:()=>ki(!1),openaiMethodOptions:nd,onOpenAIMethodSelect:async m=>{lo(null),await Lr("auth.login",`openai --method ${m.id}`)},onOpenAIMethodCancel:()=>lo(null),openaiKeyInputVisible:od,onOpenAIKeySubmit:async m=>{Mi(!1),await Lr("auth.login",`openai ${m}`)},onOpenAIKeyCancel:()=>Mi(!1),googleMethodOptions:Di,onGoogleMethodSelect:async m=>{Li(null),await Lr("auth.login",`google --method ${m.id}`)},onGoogleMethodCancel:()=>Li(null),googleKeyInputVisible:Jm,onGoogleKeySubmit:async m=>{pc(!1),await Lr("auth.login",`google ${m}`)},onGoogleKeyCancel:()=>pc(!1),copilotSourceOptions:mc,onCopilotSourceSelect:async m=>{Ti(null),await Lr("auth.login",`github-copilot --from ${m.id}`)},onCopilotSourceCancel:()=>Ti(null),oauthProvider:Kl,oauthAuthorizeUrl:Vl,oauthExpectedState:Yl,onOAuthComplete:m=>{Ei(null),_i(null),Ci(null),fs(null),_(w=>[...w,m.success?q(m.message):ee(m.message)])},onOAuthCodeSubmit:async m=>{if(!fc)throw new Error("No pending OAuth field key");await wo({kind:"credential_input",values:{[fc]:m}})},onOAuthCancel:async()=>{await wo({kind:"cancel"})},copilotDeviceProvider:Jl,copilotDeviceProfileLabel:Ql,copilotDeviceVerificationUri:Zl,copilotDeviceUserCode:ed,onCopilotDeviceComplete:m=>{Ri(null),Ai(null),ps(null),Ii(null),_(w=>[...w,m.success?q(m.message):ee(m.message)])},onCopilotDeviceApprove:async()=>{await wo({kind:"oauth_device",acknowledged:!0})},onCopilotDeviceCancel:async()=>{await wo({kind:"cancel"})},nearbyPeers:Qm,localClients:ws,onSelectPeer:j0,onSelectClient:()=>{},onPeerCancel:()=>{},onClientsCancel:()=>{},openPeersOverlaySignal:tf,openClientsOverlaySignal:dd,incomingPairRequest:tn,onAcceptPairRequest:P0,onRejectPairRequest:$0,onCancelPairing:void 0,meshMessageCount:of,runtimeSocket:xc,clientId:o.attachedClientId??null,clientAuthToken:o.attachedClientAuthToken??null,resolveCredentials:async()=>{try{let{createResilientAttachedClient:m}=await Promise.resolve().then(()=>(Nl(),Rm)),{resolveRuntimeRootDirectory:w,findRuntimeOwnerRecordByAriaHome:p}=await import("@aria-cli/server"),g=w(),b=process.env.ARIA_HOME??`${process.env.HOME}/.aria`,M=p(g,b);if(!M?.runtimeSocket)return null;let O=await m({runtimeSocket:M.runtimeSocket,clientKind:"local-api"});return{clientId:O.getClientId(),clientAuthToken:O.getClientAuthToken()}}catch{return null}}})}async function o0(e,t,r,n,o,s,i=[],a,c,l,d,f,u,h,y,S){let{waitUntilExit:R,unmount:I}=bN(tw(BN,{session:e,manager:t,router:r,aria:n,attachedLocalControl:o,cliContext:s,sessionHistory:c,inputHistory:i,onSaveInput:a,initialMessage:l,resumeSessionId:f,cachedUserName:d,initialAvailableModels:u,refreshAvailableModels:h,credentialHints:y,authResolver:S}),{exitOnCtrlC:!1,patchConsole:!0}),v,C,T=!1,E=()=>{v||(v=()=>{process.exit(0)},process.on("SIGINT",v)),C||(C=setTimeout(()=>{Ee.debug("[InkREPL] Graceful shutdown timed out after 5s \u2014 forcing exit"),process.exit(0)},5e3),C.unref?.())},_=()=>{T||(T=!0,process.removeListener("SIGINT",_),E(),o?.release().catch(P=>{Ee.warn("[InkREPL] Local-control release during SIGINT failed:",P?.message??P)}),I())};process.on("SIGINT",_);try{await R(),E();try{let{sessionId:P,sessionHistory:Z,memoriaSession:nt,memoriaFactory:ze}=Rt;if(Z&&P)try{Z.markCompleted(P)}catch(le){Ee.warn("[InkREPL] Failed to mark session completed:",le?.message??le)}if(nt&&P)try{await nt.endSession(P)}catch(le){Ee.warn("[InkREPL] Failed to end Memoria session:",le?.message??le)}if(ze)try{await ze.closeAll()}catch(le){Ee.warn("[InkREPL] Failed to close Memoria factory:",le?.message??le)}if(Rt.jsonlLogger){try{await Rt.jsonlLogger.close()}catch(le){Ee.warn("[InkREPL] Failed to close JSONL logger:",le?.message??le)}Rt.jsonlLogger=null}}finally{C&&(clearTimeout(C),C=void 0)}}finally{process.removeListener("SIGINT",_),v&&process.removeListener("SIGINT",v)}try{await n.shutdown()}catch(P){Ee.warn("[InkREPL] Shutdown failed:",P?.message)}}import{Command as BO}from"commander";_r();import{Command as HN}from"commander";import{ArionManager as WN,ArionStorage as qN,MemoriaPool as GN}from"@aria-cli/aria";async function Hm(){let e=lr(),t=new qN(e),n=new GN(e).toFactory(),o=new WN(t,n);return await o.initialize(),o}function Wm(){let e=new HN("arions").description("Manage Arion personas");return e.command("list").description("List all Arions with status").option("--status <status>","Filter by status (active, resting, retired)").action(async t=>{try{let n=await(await Hm()).list(),o=t.status?n.filter(s=>s.status===t.status):n;if(o.length===0){console.log("No Arions found.");return}console.log(`
|
|
496
|
-
Arions:`),console.log("\u2500".repeat(60));for(let s of o){let i=s.status==="active"?"\u25CF":s.status==="resting"?"\u25CB":"\xD7";console.log(`${i} ${s.name} [${s.status}]`),console.log(` Style: ${s.personality.style}`),console.log(` Traits: ${s.personality.traits.join(", ")}`),s.skills.length>0&&console.log(` Skills: ${s.skills.map(a=>a.name).join(", ")}`),console.log()}}catch(r){console.error("Error listing Arions:",r.message),process.exit(1)}}),e.command("hatch").description("Create a new Arion").argument("<name>","Name for the new Arion").option("-t, --traits <traits>","Comma-separated personality traits").option("-s, --style <style>","Communication style (formal, casual, technical, friendly)").option("--skills <skills>","Comma-separated skills").action(async(t,r)=>{try{let n=await Hm(),o=r.traits?r.traits.split(",").map(c=>c.trim()):["helpful","curious"],s=r.style||"friendly",i=r.skills?r.skills.split(",").map(c=>({name:c.trim(),level:"intermediate"})):[],a=await n.hatch({name:t,personality:{traits:o,style:s},skills:i,createdBy:"cli"});console.log(`
|
|
497
|
-
Hatched new Arion: ${a.name}`),console.log(` ID: ${a.id}`),console.log(` Status: ${a.status}`),console.log(` Style: ${a.personality.style}`),console.log(` Traits: ${a.personality.traits.join(", ")}`),a.skills.length>0&&console.log(` Skills: ${a.skills.map(c=>c.name).join(", ")}`)}catch(n){console.error("Error hatching Arion:",n.message),process.exit(1)}}),e.command("become").description("Switch to an Arion").argument("<name>","Name of the Arion to switch to").action(async t=>{try{let r=await Hm(),n=await r.get(t);n||(console.error(`Arion not found: ${t}`),process.exit(1)),n.status==="retired"&&(console.error(`Cannot become retired Arion: ${t}`),process.exit(1)),n.status==="resting"&&await r.wake(t);let o=ue();o.activeArion=n.name,Le(o),console.log(`
|
|
498
|
-
Switched to Arion: ${n.name}`),console.log(` Style: ${n.personality.style}`),console.log(` Traits: ${n.personality.traits.join(", ")}`)}catch(r){console.error("Error switching Arion:",r.message),process.exit(1)}}),e.command("retire").description("Retire an Arion (permanent)").argument("<name>","Name of the Arion to retire").option("--confirm","Confirm retirement (required)").action(async(t,r)=>{try{r.confirm||(console.error("Retirement is permanent. Use --confirm to proceed."),process.exit(1)),await(await Hm()).retire(t,{confirm:!0});let o=ue();o.activeArion?.toLowerCase()===t.toLowerCase()&&(delete o.activeArion,Le(o)),console.log(`
|
|
499
|
-
Retired Arion: ${t}`),console.log("The Arion can no longer be used but its memories are preserved.")}catch(n){console.error("Error retiring Arion:",n.message),process.exit(1)}}),e}import{Command as XN}from"commander";import{createInterface as zN}from"node:readline";import{ensureAuthProfileStore as KN,syncExternalCliCredentials as VN,isProfileInCooldown as YN,upsertAuthProfile as JN,updateAuthProfileStoreWithLockSync as s0}from"@aria-cli/auth";var QN=["COPILOT_GITHUB_TOKEN","GH_TOKEN","GITHUB_TOKEN"];function ZN(e=process.env){for(let t of QN){let r=e[t];if(r&&r.length>8)return t}return null}async function eO(){let e=s0({updater:r=>VN(r)})??KN(),t=Object.entries(e.profiles);if(t.length===0){console.log("No auth profiles configured."),console.log("Add one with: aria auth add --provider <name>");return}for(let[r,n]of t){let s=YN(e,r)?"cooldown":"active",i=n.type.padEnd(7);if(console.log(` ${r.padEnd(30)} [${i}] ${s}`),n.email&&console.log(` email: ${n.email}`),(n.type==="oauth"||n.type==="token")&&"expires"in n){let a=n.expires;if(a){let c=a-Date.now(),l=c>0?`expires in ${Math.round(c/6e4)}min`:"EXPIRED";console.log(` ${l}`)}}if(n.provider==="github-copilot"){let a=ZN();a&&console.log(` env override: ${a}`)}}}async function tO(e){let t=e.provider.toLowerCase().trim(),r=`${t}:manual`,n=zN({input:process.stdin,output:process.stdout}),o=await new Promise(s=>{n.question(`Paste API key for ${t}: `,i=>{n.close(),s(i.trim())})});(!o||o.length<8)&&(console.error("API key too short (minimum 8 characters)."),process.exit(1)),JN({profileId:r,credential:{type:"api_key",provider:t,key:o}}),console.log(`Saved auth profile: ${r}`)}async function rO(e){let t=!1,r=s0({updater:n=>n.profiles[e]?(delete n.profiles[e],t=!0,!0):!1});(!t||!r)&&(console.error(`Profile not found: ${e}`),process.exit(1)),console.log(`Removed auth profile: ${e}`)}function qm(){let e=new XN("auth").description("Manage auth profiles");return e.command("status").description("Show all auth profiles and their health").action(eO),e.command("add").description("Add an API key for a provider").requiredOption("--provider <name>","Provider name (anthropic, openai, google)").action(tO),e.command("remove").description("Remove an auth profile").argument("<profile-id>","Profile ID to remove").action(rO),e}Tm();_r();Om();function nw(e,t,r){if(e===void 0||e.trim()==="")return r;let n=Number.parseInt(e,10);if(!Number.isFinite(n)||n<=0)throw new Error(`${t} must be a positive integer`);return n}function l0(e){if(!e)return;let t=e.split(",").map(r=>r.trim()).filter(r=>r.length>0);return t.length>0?t:void 0}function sO(e,t){if(e===void 0||e.trim()==="")return t;let r=Number.parseInt(e,10);if(!Number.isFinite(r)||r<0)throw new Error("port must be a non-negative integer (0 = OS-assigned)");return r}function iO(e){return{arion:e.arion,port:sO(e.port,0),intervalMs:nw(e.intervalMs,"intervalMs",6e4),allowedToolCategories:l0(e.allowedToolCategories),allowedShellCommands:l0(e.allowedShellCommands),maxWriteOpsPerMinute:e.maxWriteOpsPerMinute!==void 0?nw(e.maxWriteOpsPerMinute,"maxWriteOpsPerMinute",30):void 0,maxGitPushesPerHour:e.maxGitPushesPerHour!==void 0?nw(e.maxGitPushesPerHour,"maxGitPushesPerHour",5):void 0}}function aO(e){return e.aborted?Promise.resolve():new Promise(t=>{e.addEventListener("abort",()=>t(),{once:!0})})}function d0(e){return{...e.arion?{arion:e.arion}:{},...e.port>=0?{port:e.port}:{},intervalMs:e.intervalMs,...e.allowedToolCategories?{allowedToolCategories:e.allowedToolCategories}:{},...e.allowedShellCommands?{allowedShellCommands:e.allowedShellCommands}:{},...typeof e.maxWriteOpsPerMinute=="number"?{maxWriteOpsPerMinute:e.maxWriteOpsPerMinute}:{},...typeof e.maxGitPushesPerHour=="number"?{maxGitPushesPerHour:e.maxGitPushesPerHour}:{}}}async function ow(e={}){let t=iO(e);await cO(t)}async function sw(){let{resolveRuntimeRootDirectory:e,findRuntimeOwnerRecordByAriaHome:t,removeRuntimeOwnerRecord:r}=await import("@aria-cli/server"),{getAriaDir:n}=await Promise.resolve().then(()=>(_r(),My)),o=n(),s=e(),i=t(s,o);if(!i){console.log("[daemon] no running daemon found");return}try{process.kill(i.runtimePid,"SIGINT"),console.log(`[daemon] sent SIGINT to pid ${i.runtimePid}`);let a=Date.now()+5e3;for(;Date.now()<a;)try{process.kill(i.runtimePid,0),await new Promise(c=>setTimeout(c,200))}catch{break}try{process.kill(i.runtimePid,0),process.kill(i.runtimePid,"SIGKILL"),console.log(`[daemon] force-killed pid ${i.runtimePid}`)}catch{}}catch{}r(s,i.nodeId),console.log("[daemon] stopped")}async function u0(e={}){await sw(),await new Promise(s=>setTimeout(s,500));let{ensureDaemon:t}=await Promise.resolve().then(()=>(rw(),c0)),r=await cs(),o=await(await t(r)).control.listPeers();console.log(`[daemon] restarted (${o.length} peers connected)`),await r.pool?.closeAll?.()}async function cO(e){let t=new AbortController,r=()=>t.abort(),n=()=>t.abort(),o=()=>{};process.on("SIGINT",r),process.on("SIGTERM",n),process.on("SIGHUP",o);let s=ue(),i=e.arion?.trim()||s.activeArion?.trim()||"ARIA",a=await cs({startupMode:"daemon"}),c=Pl({cli:a,cwd:process.cwd(),arionName:i}),l=null;try{let d=await c.start(d0(e));console.log(`[daemon] runtime node ${String(d.nodeId??"unknown")}`),console.log(`[daemon] runtime ${String(d.runtimeId??"unknown")} listening on port ${String(d.port??"unknown")}`),console.log(`[daemon] running arion "${i}" (interval ${e.intervalMs}ms)`),l=setInterval(()=>{c.status({}).catch(()=>{})},Math.min(Math.max(e.intervalMs,1e3),5e3)),await aO(t.signal)}catch(d){console.error(`[daemon] Runtime startup failed: ${d instanceof Error?d.message:String(d)}`),process.exitCode=1}finally{l&&(clearInterval(l),l=null);try{t.signal.aborted&&c.shouldStopOnShutdown?.()&&await c.stop?.(d0(e))}catch{}await c.releaseAll?.(),await a.pool.closeAll().catch(()=>{}),process.removeListener("SIGINT",r),process.removeListener("SIGTERM",n),process.removeListener("SIGHUP",o),console.log("[daemon] stopped")}}import{Command as lO}from"commander";import{existsSync as dO,readFileSync as iw}from"node:fs";import{homedir as uO}from"node:os";import m0 from"node:path";function mO(e){if(!e||e==="-"){let t=iw(0,"utf8").trim();return t?JSON.parse(t):{}}return JSON.parse(iw(e,"utf8"))}function fO(e,t){return e==="interaction.respond"?{kind:"interaction.respond",requestId:"call-1",...t}:{kind:"request",requestId:"call-1",op:e,input:t}}function f0(){return process.env.ARIA_HOME?process.env.ARIA_HOME:m0.join(process.env.HOME||uO(),".aria")}function pO(e){if(typeof e.arion=="string"&&e.arion.trim().length>0)return e.arion.trim();let t=m0.join(f0(),"config.json");if(!dO(t))return"ARIA";try{let r=JSON.parse(iw(t,"utf8"));if(typeof r.activeArion=="string"&&r.activeArion.trim().length>0)return r.activeArion.trim()}catch{}return"ARIA"}function p0(e){return{kind:"result",requestId:"call-1",op:e,ok:!1,error:{code:"NO_RESULT",message:`Operation ${e} produced no result frame`}}}async function hO(e,t,r){let[{SessionHistory:n},{createSessionOperationHandlers:o}]=await Promise.all([Promise.resolve().then(()=>(vl(),ST)),Promise.resolve().then(()=>(jl(),pE))]),s=new n(n.resolvePerArionPath(f0(),pO(r)));try{let i=o({sessionLedger:s}),a=null;for await(let c of i[e]("call-1",t))c.kind==="result"&&(a=c);return a??p0(e)}finally{s.close()}}async function gO(e,t,r){switch(e){case"session.list":case"session.read":case"session.load":return hO(e,t,r);default:return null}}async function wO(e,t){try{let r=mO(t.inputJson),n=await gO(e,r,t);if(n)return process.stdout.write(`${JSON.stringify(n)}
|
|
500
|
-
`),n.ok?0:1;let{createHeadlessKernelRuntime:o}=await Promise.resolve().then(()=>(Um(),XE)),s=await o({cwd:process.cwd(),arionName:t.arion});try{let i=null;for await(let a of s.kernel.dispatch(fO(e,r)))a.kind==="result"&&(i=a);return i?(process.stdout.write(`${JSON.stringify(i)}
|
|
501
|
-
`),i.ok?0:1):(process.stdout.write(`${JSON.stringify(p0(e))}
|
|
502
|
-
`),1)}finally{await s.release()}}catch(r){return process.stderr.write(`${r instanceof Error?r.message:String(r)}
|
|
503
|
-
`),2}}function aw(){return new lO("call").description("Execute one headless operation and print exactly one JSON result").argument("<operation>","Headless operation name").option("--input-json <path|->","Read JSON input from a file path or stdin","-").option("--arion <name>","Arion name for per-Arion session context").action(async(e,t)=>{process.exitCode=await wO(e,t)})}Tm();rw();import{Command as yO}from"commander";function xO(e){let t=Number.parseInt(e,10);if(!Number.isFinite(t)||t<0)throw new Error(`Invalid --duration-ms value: ${e}`);return t}function cw(){let e=new yO("pairing").description("Invite and join peers over the internet");return e.command("invite").description("Create an end-user internet pairing invite").argument("[label]","Optional local label for the invite").option("--duration-ms <ms>","Invite lifetime in milliseconds",xO).action(async(t,r)=>{let n=await cs();try{let{control:o}=await Gm(n),s=await o.createInvite({...t?.trim()?{inviteLabel:t.trim()}:{},...typeof r?.durationMs=="number"?{durationMs:r.durationMs}:{}});console.log("Invite token:"),console.log(s.inviteToken),console.log(""),console.log(`Join with: aria pairing join ${s.inviteToken}`)}catch(o){console.error(`Failed to create invite: ${o.message}`),process.exit(1)}finally{await n.pool?.closeAll?.()}}),e.command("join").description("Accept an internet pairing invite token").argument("<token>","Invite token to accept").action(async t=>{let r=await cs();try{let{control:n}=await Gm(r),o=await n.acceptInviteToken({inviteToken:t.trim()});console.log(`Paired with ${o.displayNameSnapshot??o.nodeId}`)}catch(n){console.error(`Failed to accept invite: ${n.message}`),process.exit(1)}finally{await r.pool?.closeAll?.()}}),e}import{Command as OO}from"commander";function uw(){return new OO("runtime-cutover-reset").description("Destructively clear stale runtime state while preserving local node identity by default").option("--full-reset","Also remove local node identity material").option("--json","Emit the reset report as JSON").action(async e=>{let{runtimeCutoverResetCommand:t}=await Promise.resolve().then(()=>(dw(),S0));await t(e)})}Um();import{HEADLESS_OPERATION_SCHEMAS as b0,HeadlessInteractionResponseSchema as jO,HeadlessRequestIdSchema as T0}from"@aria-cli/tools";var PO=200,$O=500;function FO(e=process.stdout){let t=!1,r=()=>{t=!0};e.on?.("error",r);let n=(o=>{if(t)return!1;try{return e.write(`${JSON.stringify(o)}
|
|
504
|
-
`),!0}catch{return t=!0,!1}});return n.close=()=>{e.off?.("error",r)},n}function UO(e,t,r){let n;try{n=JSON.parse(e)}catch{return r({kind:"result",requestId:`parse-error-${t}`,op:"unknown",ok:!1,error:{code:"PARSE_ERROR",message:"Malformed JSON input"}}),null}if(!n||typeof n!="object")return r({kind:"result",requestId:`parse-error-${t}`,op:"unknown",ok:!1,error:{code:"PARSE_ERROR",message:"Input must be a JSON object"}}),null;let o=n;return o.kind==="interaction.respond"&&T0.safeParse(o.requestId).success&&typeof o.interactionId=="string"||o.kind==="request"&&T0.safeParse(o.requestId).success&&typeof o.op=="string"?o:(r({kind:"result",requestId:`parse-error-${t}`,op:"unknown",ok:!1,error:{code:"PARSE_ERROR",message:"Missing required kind/requestId/op fields"}}),null)}async function mw(e){let t=FO(),r=null,n=null,o=null,s=new Set,i=new Set,a=new Set,c=new Map,l=0,d=null,f="",u=!1,h=!1,y=null,S=new Promise(A=>{y=()=>{h||(h=!0,A())}}),R=()=>(r??=Kg(e).then(A=>(n=A,A)),r),I=()=>(o??=(async()=>{if(n){await n.release();return}if(r)try{let A=await r;n=A,await A.release()}catch{}})(),o),v=A=>Object.prototype.hasOwnProperty.call(b0,A),C=async(A,$)=>A.aborted?{kind:"aborted"}:new Promise((he,ae)=>{let oe=!1,_e=()=>{oe||(oe=!0,A.removeEventListener("abort",_e),he({kind:"aborted"}))};A.addEventListener("abort",_e),$.then(We=>{oe||(oe=!0,A.removeEventListener("abort",_e),he({kind:"value",value:We}))},We=>{oe||(oe=!0,A.removeEventListener("abort",_e),ae(We))})}),T=async A=>{if(typeof A.return!="function")return!0;try{let he=A.return().then(()=>{},()=>{}).finally(()=>{a.delete(he)}),ae=await Promise.race([he.then(()=>!0),new Promise(oe=>setTimeout(()=>oe(!1),PO))]);return ae||a.add(he),ae}catch{return!1}},E=(A,$)=>t({kind:"result",requestId:A,op:$,ok:!1,error:{code:"CONNECTION_CLOSED",message:"Connection closed before request completed"}}),_=()=>(d??=(async()=>{for(let[A,$]of c)$.controller.abort(),!($.completed||$.connectionClosedEmitted)&&($.connectionClosedEmitted=!0,E(A,$.op));await Promise.allSettled([...c.values()].map(A=>A.promise)),a.size>0&&await Promise.race([Promise.allSettled([...a]),new Promise(A=>setTimeout(()=>A(),$O))]),await I(),t.close(),process.stdin.removeListener("data",ze),process.stdin.removeListener("end",le),process.stdin.removeListener("close",le),process.removeListener("SIGTERM",P)})(),d),P=()=>{process.stdin.pause(),_().finally(()=>y?.())};process.once("SIGTERM",P);let Z=A=>{l+=1;let $=UO(A,l,t);$&&N($)},nt=()=>{for(;;){let A=f.indexOf(`
|
|
505
|
-
`);if(A<0)return;let $=f.slice(0,A);$.endsWith("\r")&&($=$.slice(0,-1)),f=f.slice(A+1),Z($)}},ze=A=>{f+=typeof A=="string"?A:A.toString("utf8"),nt()},le=()=>{if(u)return;u=!0;let A=f;A.endsWith("\r")&&(A=A.slice(0,-1)),f="",A.trim().length>0&&Z(A),_().finally(()=>y?.())},N=A=>{let $=A.kind==="request"?A.op:"interaction.respond",he=[...c.values()].some(_e=>_e.op==="arion.become");if(A.kind==="request"&&(A.op==="arion.become"&&s.size>0||A.op!=="arion.become"&&he)){t({kind:"result",requestId:A.requestId,op:$,ok:!1,error:{code:"ARION_SCOPE_BUSY",message:A.op==="arion.become"?"arion.become requires an idle headless connection":"Headless scope is switching arions; wait for arion.become to finish"}}),i.add(A.requestId);return}if(s.has(A.requestId)){t({kind:"result",requestId:A.requestId,op:$,ok:!1,error:{code:"DUPLICATE_REQUEST_ID",message:`Request ${A.requestId} is already in flight`}});return}if(i.has(A.requestId)){t({kind:"result",requestId:A.requestId,op:A.kind==="request"?A.op:"interaction.respond",ok:!1,error:{code:"DUPLICATE_REQUEST_ID",message:`Request ${A.requestId} has already been used on this connection`}});return}if(A.kind==="request"){if(!v(A.op)){t({kind:"result",requestId:A.requestId,op:A.op,ok:!1,error:{code:"UNKNOWN_OPERATION",message:`Unknown operation ${A.op}`}}),i.add(A.requestId);return}if(!b0[A.op].input.safeParse(A.input).success){t({kind:"result",requestId:A.requestId,op:A.op,ok:!1,error:{code:"INVALID_INPUT",message:`Invalid input for ${A.op}`}}),i.add(A.requestId);return}}else if(!jO.safeParse(A).success){t({kind:"result",requestId:A.requestId,op:"interaction.respond",ok:!1,error:{code:"INVALID_INPUT",message:"Invalid input for interaction.respond"}}),i.add(A.requestId);return}s.add(A.requestId),i.add(A.requestId);let ae=new AbortController,oe=null;oe=(async()=>{try{let _e=await C(ae.signal,R().then(dt=>({runtime:dt})));if(_e.kind!=="value")return;let We=_e.value.runtime.kernel.dispatch(A,{signal:ae.signal})[Symbol.asyncIterator]();for(;;){let dt=await C(ae.signal,We.next().then(se=>({result:se})));if(dt.kind==="aborted"){await T(We);return}if(dt.value.result.done)return;let sr=dt.value.result.value,Y=c.get(A.requestId);ae.signal.aborted||Y?.connectionClosedEmitted||(t(sr),sr.kind==="result"&&Y&&(Y.completed=!0))}}catch(_e){let We=c.get(A.requestId);if(ae.signal.aborted||We?.connectionClosedEmitted)return;t({kind:"result",requestId:A.requestId,op:$,ok:!1,error:{code:"INTERNAL_ERROR",message:_e instanceof Error?_e.message:String(_e)}}),We&&(We.completed=!0)}finally{s.delete(A.requestId),c.delete(A.requestId)}})(),c.set(A.requestId,{op:$,controller:ae,completed:!1,connectionClosedEmitted:!1,promise:oe})};process.stdin.setEncoding("utf8"),process.stdin.on("data",ze),process.stdin.once("end",le),process.stdin.once("close",le),await S}dw();var io=new BO;io.name("aria").description("ARIA - Adaptive Reasoning Intelligence Agent").version("1.0.0");io.addCommand(Wm());io.addCommand(qm());io.addCommand(cw());io.command("headless").description("Run the persistent headless stdio control server").option("--arion <name>","Arion name for per-Arion session context").action(async e=>{await mw({cwd:process.cwd(),arionName:e.arion})});io.addCommand(aw());var fw=io.command("daemon").description("Manage the ARIA daemon");fw.command("start",{isDefault:!0}).description("Start the daemon (default)").option("--arion <name>","Run daemon for a specific Arion").option("--port <port>","Server port (default: 0 = OS-assigned)").option("--interval-ms <ms>","Wake loop interval in milliseconds (default: 60000)").option("--allowed-tool-categories <list>","Comma-separated tool category allowlist").option("--allowed-shell-commands <list>","Comma-separated shell command prefix allowlist").option("--max-write-ops-per-minute <count>","Rate limit for write operations per minute").option("--max-git-pushes-per-hour <count>","Rate limit for git pushes per hour").action(async e=>{await ow(e)});fw.command("stop").description("Stop the running daemon").action(async()=>{await sw()});fw.command("restart").description("Stop the daemon and start a fresh one").action(async()=>{await u0()});io.addCommand(uw());export{Nn as SessionHistory,Wm as createArionsCommand,qm as createAuthCommand,io as program,o0 as startInkRepl,o0 as startRepl};
|
|
1
|
+
import{a as e,b as a,h as o}from"./index-718zvjhe.js";import"./index-y2vy5jks.js";import"./index-j035n0mr.js";import{m as r}from"./index-92syx5hd.js";import"./index-00jaxgt2.js";import"./index-wbm34jf5.js";import{W as t}from"./index-76vaj0sr.js";import"./index-5v7br509.js";import"./index-xjwfqz7t.js";import"./index-sxga6d5s.js";import"./index-g5devafm.js";import"./index-sx36201d.js";import"./index-nnqfqvqh.js";import"./index-9j6r3gr8.js";export{r as startRepl,r as startInkRepl,o as program,a as createAuthCommand,e as createArionsCommand,t as SessionHistory};
|