agy-bar 1.0.1 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/README.md +148 -54
- package/README.zh-CN.md +144 -50
- package/bin/agy-bar.mjs +603 -6
- package/llms.txt +47 -0
- package/package.json +3 -2
- package/skills/agy-bar/SKILL.md +11 -4
- package/src/account-import.mjs +435 -0
- package/src/account-quota.mjs +466 -0
- package/src/account-store.mjs +1140 -0
- package/src/agent-state.mjs +2 -1
- package/src/ansi.mjs +7 -0
- package/src/config.mjs +24 -0
- package/src/fs-atomic.mjs +16 -5
- package/src/handoff.mjs +424 -0
- package/src/installer.mjs +16 -0
- package/src/keyring.mjs +604 -0
- package/src/proxy.mjs +189 -48
- package/src/quota-sync.mjs +100 -20
- package/src/render.mjs +11 -3
- package/src/statusline.mjs +55 -8
- package/src/step-timing.mjs +52 -3
- package/src/telemetry.mjs +4 -0
- package/src/title.mjs +18 -3
package/src/agent-state.mjs
CHANGED
|
@@ -74,7 +74,8 @@ export function classifyAgentActivity(payload = {}) {
|
|
|
74
74
|
});
|
|
75
75
|
}
|
|
76
76
|
|
|
77
|
-
|
|
77
|
+
const waitingForInput = payload?.waiting_for_input === true;
|
|
78
|
+
if (rawState === 'reviewing' || (waitingForInput && MAIN_BUSY_STATES.has(rawState))) {
|
|
78
79
|
return Object.freeze({
|
|
79
80
|
kind: 'input',
|
|
80
81
|
rawState,
|
package/src/ansi.mjs
CHANGED
|
@@ -199,3 +199,10 @@ export function clipAnsi(text, maxWidth) {
|
|
|
199
199
|
|
|
200
200
|
return hasAnsi && !out.endsWith('\x1b[0m') ? `${out}\x1b[0m` : out;
|
|
201
201
|
}
|
|
202
|
+
|
|
203
|
+
export function padDisplayEnd(text, targetWidth) {
|
|
204
|
+
const str = String(text ?? '');
|
|
205
|
+
const w = visibleWidth(str);
|
|
206
|
+
if (w >= targetWidth) return str;
|
|
207
|
+
return str + ' '.repeat(targetWidth - w);
|
|
208
|
+
}
|
package/src/config.mjs
CHANGED
|
@@ -146,6 +146,9 @@ export const DEFAULT_CONFIG = Object.freeze({
|
|
|
146
146
|
tabTitle: true,
|
|
147
147
|
tabTitleSource: 'auto',
|
|
148
148
|
tabTitleMaxLen: 26,
|
|
149
|
+
swapHint: true,
|
|
150
|
+
autoSwitchOnLimit: false,
|
|
151
|
+
autoHandoff: false,
|
|
149
152
|
contextWarn: 70,
|
|
150
153
|
contextDanger: 88,
|
|
151
154
|
quotaWarn: 25,
|
|
@@ -349,6 +352,9 @@ export function normalizeConfig(raw) {
|
|
|
349
352
|
const tabTitle = typeof input.tabTitle === 'boolean' ? input.tabTitle : DEFAULT_CONFIG.tabTitle;
|
|
350
353
|
const tabTitleSource = TAB_TITLE_SOURCES.includes(input.tabTitleSource) ? input.tabTitleSource : DEFAULT_CONFIG.tabTitleSource;
|
|
351
354
|
const tabTitleMaxLen = clampInt(input.tabTitleMaxLen, 10, 60, DEFAULT_CONFIG.tabTitleMaxLen);
|
|
355
|
+
const swapHint = typeof input.swapHint === 'boolean' ? input.swapHint : DEFAULT_CONFIG.swapHint;
|
|
356
|
+
const autoSwitchOnLimit = typeof input.autoSwitchOnLimit === 'boolean' ? input.autoSwitchOnLimit : DEFAULT_CONFIG.autoSwitchOnLimit;
|
|
357
|
+
const autoHandoff = typeof input.autoHandoff === 'boolean' ? input.autoHandoff : DEFAULT_CONFIG.autoHandoff;
|
|
352
358
|
const contextWarn = clampInt(input.contextWarn, 10, 95, DEFAULT_CONFIG.contextWarn);
|
|
353
359
|
const contextDanger = clampInt(input.contextDanger, contextWarn, 99, DEFAULT_CONFIG.contextDanger);
|
|
354
360
|
const quotaDanger = clampInt(input.quotaDanger, 1, 50, DEFAULT_CONFIG.quotaDanger);
|
|
@@ -382,6 +388,9 @@ export function normalizeConfig(raw) {
|
|
|
382
388
|
tabTitle,
|
|
383
389
|
tabTitleSource,
|
|
384
390
|
tabTitleMaxLen,
|
|
391
|
+
swapHint,
|
|
392
|
+
autoSwitchOnLimit,
|
|
393
|
+
autoHandoff,
|
|
385
394
|
contextWarn,
|
|
386
395
|
contextDanger,
|
|
387
396
|
quotaWarn,
|
|
@@ -421,6 +430,9 @@ export function serializeConfig(cfg) {
|
|
|
421
430
|
if (normalized.tabTitle !== DEFAULT_CONFIG.tabTitle) out.tabTitle = normalized.tabTitle;
|
|
422
431
|
if (normalized.tabTitleSource !== DEFAULT_CONFIG.tabTitleSource) out.tabTitleSource = normalized.tabTitleSource;
|
|
423
432
|
if (normalized.tabTitleMaxLen !== DEFAULT_CONFIG.tabTitleMaxLen) out.tabTitleMaxLen = normalized.tabTitleMaxLen;
|
|
433
|
+
if (normalized.swapHint !== DEFAULT_CONFIG.swapHint) out.swapHint = normalized.swapHint;
|
|
434
|
+
if (normalized.autoSwitchOnLimit !== DEFAULT_CONFIG.autoSwitchOnLimit) out.autoSwitchOnLimit = normalized.autoSwitchOnLimit;
|
|
435
|
+
if (normalized.autoHandoff !== DEFAULT_CONFIG.autoHandoff) out.autoHandoff = normalized.autoHandoff;
|
|
424
436
|
if (normalized.contextWarn !== DEFAULT_CONFIG.contextWarn) out.contextWarn = normalized.contextWarn;
|
|
425
437
|
if (normalized.contextDanger !== DEFAULT_CONFIG.contextDanger) out.contextDanger = normalized.contextDanger;
|
|
426
438
|
if (normalized.quotaWarn !== DEFAULT_CONFIG.quotaWarn) out.quotaWarn = normalized.quotaWarn;
|
|
@@ -571,6 +583,18 @@ export function applyConfigCommand(args = [], path = configPath()) {
|
|
|
571
583
|
throw new Error('tabTitleMaxLen must be an integer between 10 and 60.');
|
|
572
584
|
}
|
|
573
585
|
next.tabTitleMaxLen = n;
|
|
586
|
+
} else if (['swaphint', 'swap-hint', 'swap_hint'].includes(lower)) {
|
|
587
|
+
const parsed = parseToggle(value);
|
|
588
|
+
if (parsed === null) throw new Error('swapHint must be on/off (or true/false).');
|
|
589
|
+
next.swapHint = parsed;
|
|
590
|
+
} else if (['autoswitchonlimit', 'auto-switch-on-limit', 'auto_switch_on_limit', 'autoswitch'].includes(lower)) {
|
|
591
|
+
const parsed = parseToggle(value);
|
|
592
|
+
if (parsed === null) throw new Error('autoSwitchOnLimit must be on/off (or true/false).');
|
|
593
|
+
next.autoSwitchOnLimit = parsed;
|
|
594
|
+
} else if (['autohandoff', 'auto-handoff', 'auto_handoff'].includes(lower)) {
|
|
595
|
+
const parsed = parseToggle(value);
|
|
596
|
+
if (parsed === null) throw new Error('autoHandoff must be on/off (or true/false).');
|
|
597
|
+
next.autoHandoff = parsed;
|
|
574
598
|
} else if (['contextwarn', 'context-warn'].includes(lower)) {
|
|
575
599
|
next.contextWarn = Number(value);
|
|
576
600
|
} else if (['contextdanger', 'context-danger'].includes(lower)) {
|
package/src/fs-atomic.mjs
CHANGED
|
@@ -1,11 +1,15 @@
|
|
|
1
|
-
import { mkdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
1
|
+
import { chmodSync, mkdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
2
2
|
import { dirname } from 'node:path';
|
|
3
3
|
|
|
4
|
-
export function writeFileAtomic(targetPath, content) {
|
|
5
|
-
mkdirSync(dirname(targetPath), { recursive: true });
|
|
4
|
+
export function writeFileAtomic(targetPath, content, { mode = null, dirMode = null } = {}) {
|
|
5
|
+
mkdirSync(dirname(targetPath), dirMode ? { recursive: true, mode: dirMode } : { recursive: true });
|
|
6
|
+
const writeOpts = mode ? { encoding: 'utf8', mode } : 'utf8';
|
|
6
7
|
const tmpPath = `${targetPath}.${process.pid}.${Math.random().toString(36).slice(2, 8)}.tmp`;
|
|
7
8
|
try {
|
|
8
|
-
writeFileSync(tmpPath, content,
|
|
9
|
+
writeFileSync(tmpPath, content, writeOpts);
|
|
10
|
+
if (mode && process.platform !== 'win32') {
|
|
11
|
+
chmodSync(tmpPath, mode);
|
|
12
|
+
}
|
|
9
13
|
renameSync(tmpPath, targetPath);
|
|
10
14
|
} catch {
|
|
11
15
|
try {
|
|
@@ -13,6 +17,13 @@ export function writeFileAtomic(targetPath, content) {
|
|
|
13
17
|
} catch {
|
|
14
18
|
// Ignore cleanup errors.
|
|
15
19
|
}
|
|
16
|
-
writeFileSync(targetPath, content,
|
|
20
|
+
writeFileSync(targetPath, content, writeOpts);
|
|
21
|
+
if (mode && process.platform !== 'win32') {
|
|
22
|
+
try {
|
|
23
|
+
chmodSync(targetPath, mode);
|
|
24
|
+
} catch {
|
|
25
|
+
// Ignore chmod errors on non-POSIX filesystems.
|
|
26
|
+
}
|
|
27
|
+
}
|
|
17
28
|
}
|
|
18
29
|
}
|
package/src/handoff.mjs
ADDED
|
@@ -0,0 +1,424 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { closeSync, existsSync, openSync, readdirSync, readFileSync, readSync, statSync } from 'node:fs';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { basename, join, resolve } from 'node:path';
|
|
5
|
+
import { sanitizeText } from './ansi.mjs';
|
|
6
|
+
import { configDir } from './config.mjs';
|
|
7
|
+
import { writeFileAtomic } from './fs-atomic.mjs';
|
|
8
|
+
import { listSessions } from './telemetry.mjs';
|
|
9
|
+
|
|
10
|
+
const MAX_TRANSCRIPT_TAIL_BYTES = 256 * 1024;
|
|
11
|
+
const MAX_DIGEST_CHARS = 3600;
|
|
12
|
+
const MAX_TURN_SNIPPET_CHARS = 520;
|
|
13
|
+
const MAX_ARTIFACTS_TOTAL_CHARS = 2200;
|
|
14
|
+
const MAX_SINGLE_ARTIFACT_CHARS = 780;
|
|
15
|
+
|
|
16
|
+
const ARTIFACT_PRIORITY = Object.freeze([
|
|
17
|
+
'task.md',
|
|
18
|
+
'todo.md',
|
|
19
|
+
'checklist.md',
|
|
20
|
+
'implementation_plan.md',
|
|
21
|
+
'plan.md',
|
|
22
|
+
'walkthrough.md',
|
|
23
|
+
]);
|
|
24
|
+
|
|
25
|
+
function normalizePathForCompare(p, platform = process.platform) {
|
|
26
|
+
const raw = String(p ?? '').trim();
|
|
27
|
+
if (!raw) return '';
|
|
28
|
+
const resolved = resolve(raw).replace(/[\\/]+$/, '');
|
|
29
|
+
return platform === 'win32' ? resolved.toLowerCase() : resolved;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function redactInlineSecrets(text) {
|
|
33
|
+
return String(text ?? '')
|
|
34
|
+
.replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi, '***@***')
|
|
35
|
+
.replace(/\b(?:ya29\.[A-Za-z0-9._-]+|sk-[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9]{20,})\b/g, '[REDACTED]')
|
|
36
|
+
.replace(/\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g, '[JWT_REDACTED]');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function agyCacheLastConversationsPath(home = homedir()) {
|
|
40
|
+
return join(home, '.gemini', 'antigravity-cli', 'cache', 'last_conversations.json');
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function agyBrainDir(conversationId, home = homedir()) {
|
|
44
|
+
return join(home, '.gemini', 'antigravity-cli', 'brain', conversationId);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function agyBrainTranscriptPath(conversationId, home = homedir()) {
|
|
48
|
+
return join(agyBrainDir(conversationId, home), '.system_generated', 'logs', 'transcript.jsonl');
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function extractBrainArtifactsSummary(
|
|
52
|
+
conversationId,
|
|
53
|
+
{ home = homedir(), maxFiles = 3, maxChars = MAX_ARTIFACTS_TOTAL_CHARS } = {},
|
|
54
|
+
) {
|
|
55
|
+
if (!conversationId) return [];
|
|
56
|
+
const dir = agyBrainDir(conversationId, home);
|
|
57
|
+
if (!existsSync(dir)) return [];
|
|
58
|
+
|
|
59
|
+
let entries;
|
|
60
|
+
try {
|
|
61
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
62
|
+
} catch {
|
|
63
|
+
return [];
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const mdFiles = [];
|
|
67
|
+
for (const ent of entries) {
|
|
68
|
+
if (!ent.isFile()) continue;
|
|
69
|
+
if (ent.name.startsWith('.') || !ent.name.toLowerCase().endsWith('.md')) continue;
|
|
70
|
+
const fullPath = join(dir, ent.name);
|
|
71
|
+
try {
|
|
72
|
+
const st = statSync(fullPath);
|
|
73
|
+
if (st.size <= 0) continue;
|
|
74
|
+
const lower = ent.name.toLowerCase();
|
|
75
|
+
const prioIdx = ARTIFACT_PRIORITY.indexOf(lower);
|
|
76
|
+
mdFiles.push({
|
|
77
|
+
name: ent.name,
|
|
78
|
+
path: fullPath,
|
|
79
|
+
priority: prioIdx >= 0 ? prioIdx : ARTIFACT_PRIORITY.length,
|
|
80
|
+
mtimeMs: st.mtimeMs,
|
|
81
|
+
});
|
|
82
|
+
} catch {
|
|
83
|
+
// Ignore unreadable artifacts.
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
if (mdFiles.length === 0) return [];
|
|
88
|
+
mdFiles.sort((a, b) => (a.priority !== b.priority ? a.priority - b.priority : b.mtimeMs - a.mtimeMs));
|
|
89
|
+
|
|
90
|
+
const out = [];
|
|
91
|
+
let remaining = maxChars;
|
|
92
|
+
for (const file of mdFiles.slice(0, maxFiles)) {
|
|
93
|
+
if (remaining < 120) break;
|
|
94
|
+
try {
|
|
95
|
+
const raw = readFileSync(file.path, 'utf8');
|
|
96
|
+
const cleaned = redactInlineSecrets(raw.replace(/\r\n/g, '\n').replace(/\n{3,}/g, '\n\n').trim());
|
|
97
|
+
if (!cleaned) continue;
|
|
98
|
+
const budget = Math.min(MAX_SINGLE_ARTIFACT_CHARS, remaining);
|
|
99
|
+
const excerpt = cleaned.length > budget ? `${cleaned.slice(0, budget - 1).trimEnd()}…` : cleaned;
|
|
100
|
+
out.push({
|
|
101
|
+
name: file.name,
|
|
102
|
+
path: file.path,
|
|
103
|
+
excerpt,
|
|
104
|
+
truncated: cleaned.length > budget,
|
|
105
|
+
});
|
|
106
|
+
remaining -= excerpt.length + 60;
|
|
107
|
+
} catch {
|
|
108
|
+
// Skip unreadable file.
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return out;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function latestHandoffFilePath(baseDir = configDir(homedir())) {
|
|
115
|
+
return join(baseDir, 'handoffs', 'latest.md');
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function findLatestConversationForCwd(
|
|
119
|
+
cwd = process.cwd(),
|
|
120
|
+
{ home = homedir(), baseDir = configDir(homedir()), platform = process.platform } = {},
|
|
121
|
+
) {
|
|
122
|
+
const normCwd = normalizePathForCompare(cwd, platform);
|
|
123
|
+
const sessions = listSessions({ baseDir });
|
|
124
|
+
|
|
125
|
+
// Check agy-bar's own active session telemetry first for matching cwd (gives title + exact ID).
|
|
126
|
+
const matchingSessions = sessions.filter((s) => s?.cwd && normalizePathForCompare(s.cwd, platform) === normCwd);
|
|
127
|
+
const telemetryMatch = matchingSessions[0] || null;
|
|
128
|
+
|
|
129
|
+
// Check AGY's cache/last_conversations.json as authoritative fallback/primary source.
|
|
130
|
+
const cachePath = agyCacheLastConversationsPath(home);
|
|
131
|
+
let cacheId = null;
|
|
132
|
+
if (existsSync(cachePath)) {
|
|
133
|
+
try {
|
|
134
|
+
const parsed = JSON.parse(readFileSync(cachePath, 'utf8'));
|
|
135
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
136
|
+
// Shape A: { "/path/to/repo": "conv-id" | { conversation_id, id } }
|
|
137
|
+
for (const [key, val] of Object.entries(parsed)) {
|
|
138
|
+
if (normalizePathForCompare(key, platform) === normCwd) {
|
|
139
|
+
if (typeof val === 'string' && val.trim()) cacheId = val.trim();
|
|
140
|
+
else if (val && typeof val === 'object') {
|
|
141
|
+
cacheId = String(val.conversation_id || val.conversationId || val.id || '').trim() || null;
|
|
142
|
+
}
|
|
143
|
+
if (cacheId) break;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
// Shape B: { conversations: [...] } or { entries: [...] }
|
|
147
|
+
const list = Array.isArray(parsed.conversations)
|
|
148
|
+
? parsed.conversations
|
|
149
|
+
: Array.isArray(parsed.entries)
|
|
150
|
+
? parsed.entries
|
|
151
|
+
: null;
|
|
152
|
+
if (!cacheId && list) {
|
|
153
|
+
for (const item of list) {
|
|
154
|
+
const itemCwd = item?.cwd || item?.workspace || item?.dir || '';
|
|
155
|
+
if (itemCwd && normalizePathForCompare(itemCwd, platform) === normCwd) {
|
|
156
|
+
cacheId = String(item.conversation_id || item.conversationId || item.id || '').trim() || null;
|
|
157
|
+
if (cacheId) break;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
} else if (Array.isArray(parsed)) {
|
|
162
|
+
for (const item of parsed) {
|
|
163
|
+
const itemCwd = item?.cwd || item?.workspace || item?.dir || '';
|
|
164
|
+
if (itemCwd && normalizePathForCompare(itemCwd, platform) === normCwd) {
|
|
165
|
+
cacheId = String(item.conversation_id || item.conversationId || item.id || '').trim() || null;
|
|
166
|
+
if (cacheId) break;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
} catch {
|
|
171
|
+
// Ignore malformed cache file.
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const telemetryId = telemetryMatch?.sessionId && !telemetryMatch.sessionId.startsWith('local-') ? telemetryMatch.sessionId : null;
|
|
176
|
+
const conversationId = cacheId || telemetryId || null;
|
|
177
|
+
|
|
178
|
+
return {
|
|
179
|
+
conversationId,
|
|
180
|
+
title: telemetryMatch?.customTitle || telemetryMatch?.conversationTitle || null,
|
|
181
|
+
branch: telemetryMatch?.branch || null,
|
|
182
|
+
source: cacheId ? 'agy-cache' : telemetryId ? 'agy-bar-session' : 'none',
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function extractTextFromEntry(entry) {
|
|
187
|
+
if (!entry || typeof entry !== 'object') return null;
|
|
188
|
+
|
|
189
|
+
const msg = entry.message && typeof entry.message === 'object' ? entry.message : entry;
|
|
190
|
+
const rawRole = String(msg.role || entry.role || entry.type || entry.author || '').toLowerCase();
|
|
191
|
+
let role = null;
|
|
192
|
+
if (rawRole.includes('user') || rawRole === 'human') role = 'User';
|
|
193
|
+
else if (rawRole.includes('assistant') || rawRole.includes('model') || rawRole === 'agent') role = 'Assistant';
|
|
194
|
+
else return null;
|
|
195
|
+
|
|
196
|
+
let text = '';
|
|
197
|
+
const content = msg.content ?? msg.text ?? msg.parts ?? entry.text ?? entry.content;
|
|
198
|
+
if (typeof content === 'string') {
|
|
199
|
+
text = content;
|
|
200
|
+
} else if (Array.isArray(content)) {
|
|
201
|
+
const parts = [];
|
|
202
|
+
for (const block of content) {
|
|
203
|
+
if (typeof block === 'string') parts.push(block);
|
|
204
|
+
else if (block && typeof block === 'object' && typeof block.text === 'string') {
|
|
205
|
+
if (!block.type || block.type === 'text' || block.type === 'output_text' || block.type === 'input_text') {
|
|
206
|
+
parts.push(block.text);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
text = parts.join(' ');
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const cleaned = redactInlineSecrets(sanitizeText(text).replace(/\s+/g, ' ').trim());
|
|
214
|
+
if (!cleaned) return null;
|
|
215
|
+
return {
|
|
216
|
+
role,
|
|
217
|
+
text: cleaned.length > MAX_TURN_SNIPPET_CHARS ? `${cleaned.slice(0, MAX_TURN_SNIPPET_CHARS - 1)}…` : cleaned,
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
export function extractTranscriptDigest(
|
|
222
|
+
conversationId,
|
|
223
|
+
{ home = homedir(), maxTailBytes = MAX_TRANSCRIPT_TAIL_BYTES, maxTurns = 8, maxChars = MAX_DIGEST_CHARS } = {},
|
|
224
|
+
) {
|
|
225
|
+
if (!conversationId) return null;
|
|
226
|
+
const transcriptPath = agyBrainTranscriptPath(conversationId, home);
|
|
227
|
+
if (!existsSync(transcriptPath)) return null;
|
|
228
|
+
|
|
229
|
+
let tailText = '';
|
|
230
|
+
try {
|
|
231
|
+
const st = statSync(transcriptPath);
|
|
232
|
+
if (st.size <= 0) return null;
|
|
233
|
+
const start = Math.max(0, st.size - maxTailBytes);
|
|
234
|
+
const len = st.size - start;
|
|
235
|
+
const buf = Buffer.alloc(len);
|
|
236
|
+
const fd = openSync(transcriptPath, 'r');
|
|
237
|
+
try {
|
|
238
|
+
readSync(fd, buf, 0, len, start);
|
|
239
|
+
} finally {
|
|
240
|
+
closeSync(fd);
|
|
241
|
+
}
|
|
242
|
+
tailText = buf.toString('utf8');
|
|
243
|
+
if (start > 0) {
|
|
244
|
+
const firstNl = tailText.indexOf('\n');
|
|
245
|
+
tailText = firstNl >= 0 ? tailText.slice(firstNl + 1) : '';
|
|
246
|
+
}
|
|
247
|
+
} catch {
|
|
248
|
+
return null;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
const turns = [];
|
|
252
|
+
for (const line of tailText.split(/\r?\n/)) {
|
|
253
|
+
const trimmed = line.trim();
|
|
254
|
+
if (!trimmed.startsWith('{')) continue;
|
|
255
|
+
try {
|
|
256
|
+
const parsed = JSON.parse(trimmed);
|
|
257
|
+
const item = extractTextFromEntry(parsed);
|
|
258
|
+
if (item) turns.push(item);
|
|
259
|
+
} catch {
|
|
260
|
+
// Skip malformed/truncated lines.
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
if (turns.length === 0) return null;
|
|
265
|
+
|
|
266
|
+
// Keep the earliest user goal if we have many turns + the most recent turns.
|
|
267
|
+
const selected = [];
|
|
268
|
+
if (turns.length > maxTurns) {
|
|
269
|
+
const firstUser = turns.find((t) => t.role === 'User');
|
|
270
|
+
if (firstUser) selected.push(firstUser);
|
|
271
|
+
for (const t of turns.slice(-(maxTurns - selected.length))) {
|
|
272
|
+
if (t !== firstUser) selected.push(t);
|
|
273
|
+
}
|
|
274
|
+
} else {
|
|
275
|
+
selected.push(...turns);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
const lines = [];
|
|
279
|
+
let totalChars = 0;
|
|
280
|
+
for (const t of selected) {
|
|
281
|
+
const bullet = `- **${t.role}**: ${t.text}`;
|
|
282
|
+
if (totalChars + bullet.length > maxChars && lines.length > 0) break;
|
|
283
|
+
lines.push(bullet);
|
|
284
|
+
totalChars += bullet.length + 1;
|
|
285
|
+
}
|
|
286
|
+
return lines.join('\n');
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
export function collectGitHandoffSnapshot(cwd = process.cwd(), { execFile = execFileSync } = {}) {
|
|
290
|
+
const runGit = (args, { preserveLeading = false } = {}) => {
|
|
291
|
+
try {
|
|
292
|
+
const out = execFile('git', args, {
|
|
293
|
+
cwd,
|
|
294
|
+
encoding: 'utf8',
|
|
295
|
+
windowsHide: true,
|
|
296
|
+
timeout: 1500,
|
|
297
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
298
|
+
});
|
|
299
|
+
return preserveLeading ? out.replace(/[\r\n]+$/, '') : out.trim();
|
|
300
|
+
} catch {
|
|
301
|
+
return '';
|
|
302
|
+
}
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
const branch = runGit(['rev-parse', '--abbrev-ref', 'HEAD']);
|
|
306
|
+
if (!branch) return null;
|
|
307
|
+
const statusLines = runGit(['status', '--short'], { preserveLeading: true })
|
|
308
|
+
.split(/\r?\n/)
|
|
309
|
+
.filter((line) => line.trim())
|
|
310
|
+
.slice(0, 20);
|
|
311
|
+
const diffStat = runGit(['diff', '--stat']).split(/\r?\n/).filter(Boolean).slice(0, 15);
|
|
312
|
+
const recentCommits = runGit(['log', '-n', '3', '--oneline']).split(/\r?\n/).filter(Boolean).slice(0, 3);
|
|
313
|
+
const changedFiles = statusLines
|
|
314
|
+
.map((line) => line.replace(/^[ MARCUD?!]{1,2}\s+/, '').trim().replace(/^.* -> /, ''))
|
|
315
|
+
.filter(Boolean)
|
|
316
|
+
.slice(0, 15);
|
|
317
|
+
|
|
318
|
+
return {
|
|
319
|
+
branch,
|
|
320
|
+
status: statusLines.join('\n'),
|
|
321
|
+
diffStat: diffStat.join('\n'),
|
|
322
|
+
recentCommits,
|
|
323
|
+
changedFiles,
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
export function buildHandoffPrompt({
|
|
328
|
+
cwd = process.cwd(),
|
|
329
|
+
conversationId = null,
|
|
330
|
+
title = null,
|
|
331
|
+
transcriptDigest = null,
|
|
332
|
+
artifacts = [],
|
|
333
|
+
gitSnapshot = null,
|
|
334
|
+
fromAlias = null,
|
|
335
|
+
targetAlias = null,
|
|
336
|
+
} = {}) {
|
|
337
|
+
const projectName = basename(cwd) || cwd;
|
|
338
|
+
const sections = [
|
|
339
|
+
`Continue the ongoing task in workspace \`${projectName}\` after a seamless multi-account switch${fromAlias && targetAlias ? ` (${fromAlias} -> ${targetAlias})` : targetAlias ? ` (now on ${targetAlias})` : ''}.`,
|
|
340
|
+
];
|
|
341
|
+
|
|
342
|
+
if (title) {
|
|
343
|
+
sections.push(`## Topic\n${sanitizeText(title)}`);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
if (gitSnapshot) {
|
|
347
|
+
const gitParts = [`Branch: \`${gitSnapshot.branch}\``];
|
|
348
|
+
if (Array.isArray(gitSnapshot.recentCommits) && gitSnapshot.recentCommits.length > 0) {
|
|
349
|
+
gitParts.push(`Recent commits:\n\`\`\`\n${gitSnapshot.recentCommits.join('\n')}\n\`\`\``);
|
|
350
|
+
}
|
|
351
|
+
if (gitSnapshot.status) {
|
|
352
|
+
gitParts.push(`Working tree:\n\`\`\`\n${gitSnapshot.status}\n\`\`\``);
|
|
353
|
+
} else {
|
|
354
|
+
gitParts.push('Working tree: clean');
|
|
355
|
+
}
|
|
356
|
+
if (gitSnapshot.diffStat) {
|
|
357
|
+
gitParts.push(`Diff stat:\n\`\`\`\n${gitSnapshot.diffStat}\n\`\`\``);
|
|
358
|
+
}
|
|
359
|
+
if (Array.isArray(gitSnapshot.changedFiles) && gitSnapshot.changedFiles.length > 0) {
|
|
360
|
+
gitParts.push(`In-flight files: ${gitSnapshot.changedFiles.map((f) => `\`${f}\``).join(', ')}`);
|
|
361
|
+
}
|
|
362
|
+
sections.push(`## Git State\n${gitParts.join('\n')}`);
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
if (Array.isArray(artifacts) && artifacts.length > 0) {
|
|
366
|
+
const artBlocks = artifacts.map(
|
|
367
|
+
(a) => `### ${a.name} (\`${a.path}\`)\n${a.excerpt}${a.truncated ? '\n_(truncated — read file above if full detail is needed)_' : ''}`,
|
|
368
|
+
);
|
|
369
|
+
sections.push(`## Active Plan & Artifacts\n${artBlocks.join('\n\n')}`);
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
if (transcriptDigest) {
|
|
373
|
+
sections.push(`## Recent Conversation Progress\n${transcriptDigest}`);
|
|
374
|
+
} else if (conversationId) {
|
|
375
|
+
sections.push(`## Previous Conversation\nPrevious conversation ID: \`${conversationId.slice(0, 12)}\` (no local transcript log found; inspect git state and workspace files first).`);
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
sections.push(
|
|
379
|
+
'## Instructions\nReview the current workspace/git state, active artifacts, and recent progress above. Briefly confirm what is already done vs remaining, and continue immediately without repeating completed edits.',
|
|
380
|
+
);
|
|
381
|
+
|
|
382
|
+
return sections.join('\n\n');
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
export function prepareHandoff({
|
|
386
|
+
cwd = process.cwd(),
|
|
387
|
+
home = homedir(),
|
|
388
|
+
baseDir = configDir(homedir()),
|
|
389
|
+
fromAlias = null,
|
|
390
|
+
targetAlias = null,
|
|
391
|
+
execFile = execFileSync,
|
|
392
|
+
} = {}) {
|
|
393
|
+
const conv = findLatestConversationForCwd(cwd, { home, baseDir });
|
|
394
|
+
const transcriptDigest = conv.conversationId ? extractTranscriptDigest(conv.conversationId, { home }) : null;
|
|
395
|
+
const artifacts = conv.conversationId ? extractBrainArtifactsSummary(conv.conversationId, { home }) : [];
|
|
396
|
+
const gitSnapshot = collectGitHandoffSnapshot(cwd, { execFile });
|
|
397
|
+
const prompt = buildHandoffPrompt({
|
|
398
|
+
cwd,
|
|
399
|
+
conversationId: conv.conversationId,
|
|
400
|
+
title: conv.title,
|
|
401
|
+
transcriptDigest,
|
|
402
|
+
artifacts,
|
|
403
|
+
gitSnapshot,
|
|
404
|
+
fromAlias,
|
|
405
|
+
targetAlias,
|
|
406
|
+
});
|
|
407
|
+
|
|
408
|
+
const savedPath = latestHandoffFilePath(baseDir);
|
|
409
|
+
try {
|
|
410
|
+
writeFileAtomic(savedPath, `${prompt}\n`, { mode: 0o600, dirMode: 0o700 });
|
|
411
|
+
} catch {
|
|
412
|
+
// Non-fatal if handoff cache cannot be saved.
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
return {
|
|
416
|
+
prompt,
|
|
417
|
+
savedPath,
|
|
418
|
+
conversationId: conv.conversationId,
|
|
419
|
+
title: conv.title,
|
|
420
|
+
hasTranscript: Boolean(transcriptDigest),
|
|
421
|
+
artifactCount: artifacts.length,
|
|
422
|
+
hasGit: Boolean(gitSnapshot),
|
|
423
|
+
};
|
|
424
|
+
}
|
package/src/installer.mjs
CHANGED
|
@@ -2,6 +2,7 @@ import { chmodSync, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSy
|
|
|
2
2
|
import { homedir } from 'node:os';
|
|
3
3
|
import { dirname, join, resolve } from 'node:path';
|
|
4
4
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
5
|
+
import { readAccountIndex, readActiveAccountState } from './account-store.mjs';
|
|
5
6
|
import { configDir, configPath, DEFAULT_CONFIG, loadConfig, PRESETS, saveConfig } from './config.mjs';
|
|
6
7
|
import { SAMPLE_PAYLOADS } from './preview.mjs';
|
|
7
8
|
import { redactProxyUrl } from './proxy.mjs';
|
|
@@ -530,6 +531,21 @@ export function runDoctor({ home = homedir(), platform = process.platform, env =
|
|
|
530
531
|
detail: proxyDetail,
|
|
531
532
|
});
|
|
532
533
|
|
|
534
|
+
const acctIndex = readAccountIndex({ baseDir: configDir(home) });
|
|
535
|
+
const acctState = readActiveAccountState({ baseDir: configDir(home) });
|
|
536
|
+
const activeAcct = acctState?.activeAccountId
|
|
537
|
+
? acctIndex.accounts.find((a) => a.id === acctState.activeAccountId)
|
|
538
|
+
: null;
|
|
539
|
+
checks.push({
|
|
540
|
+
name: 'Multi-account vault',
|
|
541
|
+
ok: true,
|
|
542
|
+
optional: true,
|
|
543
|
+
detail:
|
|
544
|
+
acctIndex.accounts.length > 0
|
|
545
|
+
? `${acctIndex.accounts.length} saved${activeAcct ? ` (active: ${activeAcct.alias})` : ''} · run "agy-bar account ls"`
|
|
546
|
+
: 'not configured (optional — run "agy-bar account save <alias>" to enable)',
|
|
547
|
+
});
|
|
548
|
+
|
|
533
549
|
const sampleOutput = renderStatusline(SAMPLE_PAYLOADS.normal, {
|
|
534
550
|
config: cfg,
|
|
535
551
|
color: false,
|