@ethlete/agent-rules 0.1.0-next.51 → 0.1.0-next.52
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 +25 -0
- package/README.md +16 -53
- package/content/hooks/away-mode.py +90 -7
- package/content/hooks/{background-design-commands.py → background-commands.py} +14 -65
- package/content/hooks/builder-idle-check.py +90 -11
- package/content/mods/plugins/codex-runs/.claude-plugin/plugin.json +1 -1
- package/content/mods/plugins/codex-runs/hooks/agent-runs.ts +310 -0
- package/content/mods/plugins/codex-runs/hooks/register.tsx +171 -12
- package/content/mods/plugins/codex-runs/types/index.d.ts +18 -0
- package/content/mods/plugins/e2e-progress/.claude-plugin/plugin.json +1 -1
- package/content/mods/plugins/status-line/.claude-plugin/plugin.json +1 -1
- package/content/mods/plugins/usage-line/.claude-plugin/plugin.json +1 -1
- package/content/mods/plugins/usage-line/hooks/rate-limits.ts +23 -0
- package/content/mods/plugins/usage-line/hooks/register.tsx +16 -0
- package/content/skills/agent-sessions/SKILL.md +1 -1
- package/content/skills/codex-subagent/SKILL.md +8 -2
- package/content/skills/codex-subagent/codex-agent.mjs +33 -2
- package/content/skills/design-exploration/SKILL.md +22 -104
- package/content/skills/design-exploration/reference-shots.md +1 -11
- package/migrations/studio-claude-plugin.md +27 -0
- package/migrations.json +8 -0
- package/package.json +1 -1
- package/src/index.js +0 -6
- package/src/index.js.map +1 -1
- package/src/lib/config.d.ts +4 -7
- package/src/lib/config.js +12 -9
- package/src/lib/config.js.map +1 -1
- package/src/lib/filter.d.ts +1 -0
- package/src/lib/filter.js +3 -1
- package/src/lib/filter.js.map +1 -1
- package/src/lib/plan.js +6 -3
- package/src/lib/plan.js.map +1 -1
- package/src/lib/report-command.js +8 -2
- package/src/lib/report-command.js.map +1 -1
- package/src/lib/targets/hooks-shared.d.ts +5 -0
- package/src/lib/targets/hooks-shared.js +12 -10
- package/src/lib/targets/hooks-shared.js.map +1 -1
- package/src/lib/targets/mcp.d.ts +10 -1
- package/src/lib/targets/mcp.js +43 -1
- package/src/lib/targets/mcp.js.map +1 -1
- package/src/lib/timetrack.d.ts +0 -591
- package/src/lib/timetrack.js +3 -139
- package/src/lib/timetrack.js.map +1 -1
- package/content/hooks/design-live-check.py +0 -136
- package/content/skills/design-exploration/reference-check-and-notes.md +0 -101
- package/content/skills/design-exploration/reference-flows.md +0 -38
- package/content/skills/design-exploration/reference-inbox-and-mcp.md +0 -54
- package/content/skills/design-exploration/reference-order-and-design-system.md +0 -120
- package/content/skills/design-exploration/reference-products-and-sketches.md +0 -250
- package/content/skills/timetrack/SKILL.md +0 -324
- package/src/lib/peer-path.d.ts +0 -12
- package/src/lib/peer-path.js +0 -39
- package/src/lib/peer-path.js.map +0 -1
- package/src/lib/timetrack-command.d.ts +0 -11
- package/src/lib/timetrack-command.js +0 -1262
- package/src/lib/timetrack-command.js.map +0 -1
- package/src/lib/timetrack-snapshot.d.ts +0 -66
- package/src/lib/timetrack-snapshot.js +0 -146
- package/src/lib/timetrack-snapshot.js.map +0 -1
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
export type TraceLine = { kind: 'command' | 'files' | 'message' | 'error'; text: string };
|
|
2
|
+
|
|
3
|
+
export type Trace = {
|
|
4
|
+
thread: string;
|
|
5
|
+
commands: number;
|
|
6
|
+
lastCommand: string;
|
|
7
|
+
files: string[];
|
|
8
|
+
lastMessage: string;
|
|
9
|
+
lines: TraceLine[];
|
|
10
|
+
errors: string[];
|
|
11
|
+
outputTokens: number | null;
|
|
12
|
+
isCompleted: boolean;
|
|
13
|
+
isFailed: boolean;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export type TraceReader = { trace: Trace; rest: string };
|
|
17
|
+
|
|
18
|
+
export type RunIndex = {
|
|
19
|
+
pid: number;
|
|
20
|
+
session: string;
|
|
21
|
+
cwd: string;
|
|
22
|
+
model: string;
|
|
23
|
+
effort: string;
|
|
24
|
+
sandbox: string;
|
|
25
|
+
prompt: string;
|
|
26
|
+
startedAt: number;
|
|
27
|
+
log: string;
|
|
28
|
+
endedAt?: number;
|
|
29
|
+
exitCode?: number | null;
|
|
30
|
+
failed?: boolean;
|
|
31
|
+
error?: string;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
export type AgentRunState = 'running' | 'done' | 'failed';
|
|
35
|
+
|
|
36
|
+
export type AgentRun = {
|
|
37
|
+
id: string;
|
|
38
|
+
log: string;
|
|
39
|
+
session: string;
|
|
40
|
+
cwd: string;
|
|
41
|
+
label: string;
|
|
42
|
+
prompt: string;
|
|
43
|
+
startedAt: number;
|
|
44
|
+
endedAt: number | null;
|
|
45
|
+
state: AgentRunState;
|
|
46
|
+
error: string;
|
|
47
|
+
progress: string;
|
|
48
|
+
trace: TraceLine[];
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
const KEEP_LINES = 40;
|
|
52
|
+
const SHELL_WRAPPER = /^\S*\/(?:ba|z)?sh -l?c (["'])([\s\S]*)\1$/;
|
|
53
|
+
|
|
54
|
+
const clip = (text: string, max: number) => {
|
|
55
|
+
const line = text.replace(/\s+/g, ' ').trim();
|
|
56
|
+
return line.length > max ? `${line.slice(0, max - 1)}…` : line;
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
export const commandOf = (command: string) => {
|
|
60
|
+
const inner = SHELL_WRAPPER.exec(command.trim())?.[2] ?? command;
|
|
61
|
+
return clip(inner.replace(/\\"/g, '"'), 160);
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
export const emptyTrace = (): Trace => ({
|
|
65
|
+
thread: '',
|
|
66
|
+
commands: 0,
|
|
67
|
+
lastCommand: '',
|
|
68
|
+
files: [],
|
|
69
|
+
lastMessage: '',
|
|
70
|
+
lines: [],
|
|
71
|
+
errors: [],
|
|
72
|
+
outputTokens: null,
|
|
73
|
+
isCompleted: false,
|
|
74
|
+
isFailed: false,
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
type Item = { type?: string; command?: string; text?: string; message?: string; changes?: unknown };
|
|
78
|
+
type TraceEvent = {
|
|
79
|
+
type?: string;
|
|
80
|
+
thread_id?: string;
|
|
81
|
+
item?: Item;
|
|
82
|
+
usage?: { output_tokens?: number };
|
|
83
|
+
error?: { message?: string };
|
|
84
|
+
message?: string;
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
function addLine(trace: Trace, line: TraceLine): Trace {
|
|
88
|
+
return { ...trace, lines: [...trace.lines, line].slice(-KEEP_LINES) };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function applyItem(trace: Trace, item: Item, isStarted: boolean): Trace {
|
|
92
|
+
if (item.type === 'command_execution') {
|
|
93
|
+
const command = commandOf(String(item.command ?? ''));
|
|
94
|
+
if (isStarted) return { ...trace, lastCommand: command };
|
|
95
|
+
return addLine(
|
|
96
|
+
{ ...trace, commands: trace.commands + 1, lastCommand: command },
|
|
97
|
+
{ kind: 'command', text: command },
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
if (isStarted) return trace;
|
|
101
|
+
if (item.type === 'agent_message' && item.text) {
|
|
102
|
+
return addLine({ ...trace, lastMessage: clip(item.text, 400) }, { kind: 'message', text: clip(item.text, 400) });
|
|
103
|
+
}
|
|
104
|
+
if (item.type === 'file_change' && Array.isArray(item.changes)) {
|
|
105
|
+
const paths = item.changes.map((change: { path?: string }) => String(change?.path ?? '')).filter(Boolean);
|
|
106
|
+
const files = [...trace.files.filter((file) => !paths.includes(file)), ...paths];
|
|
107
|
+
return addLine({ ...trace, files }, { kind: 'files', text: paths.join(', ') });
|
|
108
|
+
}
|
|
109
|
+
if (item.type === 'error') {
|
|
110
|
+
const message = clip(item.message ?? 'unknown error', 300);
|
|
111
|
+
return addLine({ ...trace, errors: [...trace.errors, message] }, { kind: 'error', text: message });
|
|
112
|
+
}
|
|
113
|
+
return trace;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function applyEvent(trace: Trace, event: TraceEvent): Trace {
|
|
117
|
+
switch (event.type) {
|
|
118
|
+
case 'thread.started':
|
|
119
|
+
return { ...trace, thread: event.thread_id ?? '' };
|
|
120
|
+
case 'item.started':
|
|
121
|
+
return event.item ? applyItem(trace, event.item, true) : trace;
|
|
122
|
+
case 'item.completed':
|
|
123
|
+
return event.item ? applyItem(trace, event.item, false) : trace;
|
|
124
|
+
case 'turn.completed':
|
|
125
|
+
return { ...trace, isCompleted: true, outputTokens: event.usage?.output_tokens ?? null };
|
|
126
|
+
case 'turn.failed': {
|
|
127
|
+
const message = clip(event.error?.message ?? 'the turn failed', 300);
|
|
128
|
+
return addLine(
|
|
129
|
+
{ ...trace, isFailed: true, errors: [...trace.errors, message] },
|
|
130
|
+
{ kind: 'error', text: message },
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
case 'error':
|
|
134
|
+
return addLine(trace, { kind: 'error', text: clip(event.message ?? 'unknown error', 300) });
|
|
135
|
+
default:
|
|
136
|
+
return trace;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export function feedTrace(reader: TraceReader, chunk: string): TraceReader {
|
|
141
|
+
const lines = `${reader.rest}${chunk}`.split('\n');
|
|
142
|
+
const rest = lines.pop() ?? '';
|
|
143
|
+
let trace = reader.trace;
|
|
144
|
+
for (const line of lines) {
|
|
145
|
+
if (!line.trim()) continue;
|
|
146
|
+
try {
|
|
147
|
+
trace = applyEvent(trace, JSON.parse(line) as TraceEvent);
|
|
148
|
+
} catch {
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return { trace, rest };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export const parseTrace = (text: string) => feedTrace({ trace: emptyTrace(), rest: '' }, `${text}\n`).trace;
|
|
156
|
+
|
|
157
|
+
export function parseRunIndex(text: string): RunIndex | null {
|
|
158
|
+
try {
|
|
159
|
+
const value = JSON.parse(text) as Partial<RunIndex>;
|
|
160
|
+
if (typeof value.startedAt !== 'number' || typeof value.log !== 'string') return null;
|
|
161
|
+
return {
|
|
162
|
+
pid: Number(value.pid) || 0,
|
|
163
|
+
session: String(value.session ?? ''),
|
|
164
|
+
cwd: String(value.cwd ?? ''),
|
|
165
|
+
model: String(value.model ?? ''),
|
|
166
|
+
effort: String(value.effort ?? ''),
|
|
167
|
+
sandbox: String(value.sandbox ?? ''),
|
|
168
|
+
prompt: String(value.prompt ?? ''),
|
|
169
|
+
startedAt: value.startedAt,
|
|
170
|
+
log: value.log,
|
|
171
|
+
endedAt: typeof value.endedAt === 'number' ? value.endedAt : undefined,
|
|
172
|
+
exitCode: value.exitCode ?? null,
|
|
173
|
+
failed: value.failed === true,
|
|
174
|
+
error: String(value.error ?? ''),
|
|
175
|
+
};
|
|
176
|
+
} catch {
|
|
177
|
+
return null;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export function stampTime(stamp: string) {
|
|
182
|
+
const match = /^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})-(\d{3})Z$/.exec(stamp);
|
|
183
|
+
return match ? Date.parse(`${match[1]}T${match[2]}:${match[3]}:${match[4]}.${match[5]}Z`) : NaN;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export function progressOf(trace: Trace) {
|
|
187
|
+
const parts = [`${trace.commands} cmd`];
|
|
188
|
+
if (trace.files.length > 0) parts.push(`${trace.files.length} files changed`);
|
|
189
|
+
const latest = trace.lines[trace.lines.length - 1];
|
|
190
|
+
if (latest?.kind === 'message') parts.push(`“${clip(latest.text, 100)}”`);
|
|
191
|
+
else if (trace.lastCommand) parts.push(`$ ${clip(trace.lastCommand, 100)}`);
|
|
192
|
+
return parts.join(' · ');
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** `isAlive` is `null` when the wrapper's liveness is unknown. */
|
|
196
|
+
export function agentRunOf({
|
|
197
|
+
id,
|
|
198
|
+
log,
|
|
199
|
+
index,
|
|
200
|
+
trace,
|
|
201
|
+
logChangedAt,
|
|
202
|
+
isAlive,
|
|
203
|
+
now,
|
|
204
|
+
}: {
|
|
205
|
+
id: string;
|
|
206
|
+
log: string;
|
|
207
|
+
index: RunIndex | null;
|
|
208
|
+
trace: Trace;
|
|
209
|
+
logChangedAt: number;
|
|
210
|
+
isAlive: boolean | null;
|
|
211
|
+
now: number;
|
|
212
|
+
}): AgentRun {
|
|
213
|
+
const ended = index?.endedAt ?? null;
|
|
214
|
+
const lost = ended === null && (index ? isAlive === false : now - logChangedAt > 10 * 60_000);
|
|
215
|
+
const state: AgentRunState =
|
|
216
|
+
ended !== null
|
|
217
|
+
? index?.failed || trace.isFailed
|
|
218
|
+
? 'failed'
|
|
219
|
+
: 'done'
|
|
220
|
+
: trace.isFailed || lost
|
|
221
|
+
? 'failed'
|
|
222
|
+
: !index && trace.isCompleted
|
|
223
|
+
? 'done'
|
|
224
|
+
: 'running';
|
|
225
|
+
const error =
|
|
226
|
+
state !== 'failed'
|
|
227
|
+
? ''
|
|
228
|
+
: index?.error ||
|
|
229
|
+
trace.errors[trace.errors.length - 1] ||
|
|
230
|
+
(lost ? 'the wrapper stopped without an end mark' : 'failed');
|
|
231
|
+
const label = index
|
|
232
|
+
? [index.model, index.effort, index.sandbox === 'workspace-write' ? 'write' : ''].filter(Boolean).join(' ')
|
|
233
|
+
: 'codex';
|
|
234
|
+
return {
|
|
235
|
+
id,
|
|
236
|
+
log,
|
|
237
|
+
session: index?.session ?? '',
|
|
238
|
+
cwd: index?.cwd ?? '',
|
|
239
|
+
label,
|
|
240
|
+
prompt: index?.prompt ?? '',
|
|
241
|
+
startedAt: index?.startedAt ?? stampTime(id),
|
|
242
|
+
endedAt: ended ?? (state === 'running' ? null : logChangedAt),
|
|
243
|
+
state,
|
|
244
|
+
error,
|
|
245
|
+
progress: progressOf(trace),
|
|
246
|
+
trace: trace.lines,
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
export function shortIdOf(id: string) {
|
|
251
|
+
const at = stampTime(id);
|
|
252
|
+
if (Number.isNaN(at)) return id.slice(11, 19).replace(/-/g, ':');
|
|
253
|
+
const date = new Date(at);
|
|
254
|
+
return [date.getHours(), date.getMinutes(), date.getSeconds()].map((part) => String(part).padStart(2, '0')).join(':');
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
export const isRunNamed = (run: { id: string }, name: string) =>
|
|
258
|
+
run.id === name || shortIdOf(run.id) === name.replace(/-/g, ':');
|
|
259
|
+
|
|
260
|
+
export function durationOf(run: { startedAt: number; endedAt: number | null }, now: number) {
|
|
261
|
+
const seconds = Math.max(0, Math.floor(((run.endedAt ?? now) - run.startedAt) / 1000));
|
|
262
|
+
const minutes = Math.floor(seconds / 60);
|
|
263
|
+
return minutes ? `${minutes}m${String(seconds % 60).padStart(2, '0')}s` : `${seconds}s`;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
export function statusOf(runs: AgentRun[], now: number) {
|
|
267
|
+
const running = runs.filter((run) => run.state === 'running');
|
|
268
|
+
if (running.length === 0) return undefined;
|
|
269
|
+
const oldest = Math.min(...running.map((run) => run.startedAt));
|
|
270
|
+
return `Codex: ${running.length} running, ${Math.max(0, Math.floor((now - oldest) / 60_000))}m`;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
export function finishNotices(previous: AgentRun[], next: AgentRun[], session: string, now: number) {
|
|
274
|
+
const wasRunning = new Set(previous.filter((run) => run.state === 'running').map((run) => run.id));
|
|
275
|
+
return next
|
|
276
|
+
.filter((run) => run.state !== 'running' && wasRunning.has(run.id) && run.session === session)
|
|
277
|
+
.map((run) =>
|
|
278
|
+
run.state === 'failed'
|
|
279
|
+
? `Codex run failed after ${durationOf(run, now)}: ${clip(run.error, 120)}`
|
|
280
|
+
: `Codex run done in ${durationOf(run, now)}: ${clip(run.prompt || run.progress, 80)}`,
|
|
281
|
+
);
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
export const isCodexAgentCommand = (command: unknown) =>
|
|
285
|
+
typeof command === 'string' && /codex-agent\.mjs\b/.test(command) && !/(?:^|\s)(?:-h|--help)\b/.test(command);
|
|
286
|
+
|
|
287
|
+
export function claimRuns(
|
|
288
|
+
waiting: { toolUseId: string; at: number }[],
|
|
289
|
+
claimed: Record<string, string>,
|
|
290
|
+
runs: AgentRun[],
|
|
291
|
+
session: string,
|
|
292
|
+
) {
|
|
293
|
+
const taken = new Set(Object.values(claimed));
|
|
294
|
+
const next = { ...claimed };
|
|
295
|
+
const free = runs
|
|
296
|
+
.filter((run) => run.session === session && !taken.has(run.id))
|
|
297
|
+
.sort((a, b) => a.startedAt - b.startedAt);
|
|
298
|
+
const still: typeof waiting = [];
|
|
299
|
+
for (const call of [...waiting].sort((a, b) => a.at - b.at)) {
|
|
300
|
+
const index = free.findIndex((run) => run.startedAt >= call.at - 5_000 && run.startedAt <= call.at + 120_000);
|
|
301
|
+
const run = free[index];
|
|
302
|
+
if (!run) {
|
|
303
|
+
still.push(call);
|
|
304
|
+
continue;
|
|
305
|
+
}
|
|
306
|
+
next[call.toolUseId] = run.id;
|
|
307
|
+
free.splice(index, 1);
|
|
308
|
+
}
|
|
309
|
+
return { claimed: next, waiting: still };
|
|
310
|
+
}
|
|
@@ -1,16 +1,106 @@
|
|
|
1
1
|
import { atom, read, update } from 'claude-code';
|
|
2
2
|
import type { EngineInterface, Register, Timer } from 'claude-code';
|
|
3
3
|
|
|
4
|
+
import {
|
|
5
|
+
agentRunOf,
|
|
6
|
+
claimRuns,
|
|
7
|
+
durationOf as agentDurationOf,
|
|
8
|
+
finishNotices,
|
|
9
|
+
isCodexAgentCommand,
|
|
10
|
+
isRunNamed,
|
|
11
|
+
parseRunIndex,
|
|
12
|
+
parseTrace,
|
|
13
|
+
shortIdOf,
|
|
14
|
+
statusOf,
|
|
15
|
+
} from './agent-runs';
|
|
16
|
+
import type { AgentRun, Trace } from './agent-runs';
|
|
4
17
|
import { discoverRuns, durationOf } from './progress';
|
|
5
18
|
|
|
6
19
|
const PANE = 'codex-runs';
|
|
7
|
-
const POLL_MS =
|
|
20
|
+
const POLL_MS = 3000;
|
|
8
21
|
const PROCESS_TIMEOUT_MS = 2000;
|
|
22
|
+
const KEEP_AGENT_RUNS_MS = 6 * 60 * 60_000;
|
|
23
|
+
const MAX_AGENT_RUNS = 20;
|
|
24
|
+
const MAX_TRACE_BYTES = 4 * 1024 * 1024;
|
|
9
25
|
const runs = atom({ plugin: 'codex-runs', key: 'runs' } as const, []);
|
|
10
26
|
const selected = atom({ plugin: 'codex-runs', key: 'selected' } as const, null);
|
|
27
|
+
const agentRuns = atom({ plugin: 'codex-runs', key: 'agentRuns' } as const, []);
|
|
28
|
+
const toolRuns = atom({ plugin: 'codex-runs', key: 'toolRuns' } as const, {});
|
|
29
|
+
const waitingCalls = atom({ plugin: 'codex-runs', key: 'waitingCalls' } as const, []);
|
|
11
30
|
|
|
12
31
|
let timer: Timer | undefined;
|
|
13
32
|
let pending: Promise<void> | undefined;
|
|
33
|
+
let shownStatus: string | undefined | null = null;
|
|
34
|
+
const traces = new Map<string, { size: number; mtimeMs: number; trace: Trace }>();
|
|
35
|
+
|
|
36
|
+
async function logDirs($: EngineInterface) {
|
|
37
|
+
const tmp = (await $.env.get('TMPDIR'))?.replace(/\/$/, '');
|
|
38
|
+
return [...new Set([tmp ? `${tmp}/codex-agent` : '', '/tmp/codex-agent'].filter(Boolean))];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function traceOf($: EngineInterface, path: string, size: number, mtimeMs: number) {
|
|
42
|
+
const cached = traces.get(path);
|
|
43
|
+
if (cached && cached.size === size && cached.mtimeMs === mtimeMs) return cached.trace;
|
|
44
|
+
const offset = Math.max(0, size - MAX_TRACE_BYTES);
|
|
45
|
+
const text = await $.fs.read(path, { offset, length: size - offset }).catch(() => '');
|
|
46
|
+
const trace = parseTrace(offset > 0 ? text.slice(text.indexOf('\n') + 1) : text);
|
|
47
|
+
traces.set(path, { size, mtimeMs, trace });
|
|
48
|
+
return trace;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function isAlive($: EngineInterface, pid: number) {
|
|
52
|
+
if (!pid) return null;
|
|
53
|
+
const result = await $.process.run(['kill', '-0', String(pid)], { timeoutMs: PROCESS_TIMEOUT_MS }).catch(() => null);
|
|
54
|
+
return result ? result.exitCode === 0 : null;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async function scanAgentRuns($: EngineInterface, now: number) {
|
|
58
|
+
const found: AgentRun[] = [];
|
|
59
|
+
for (const dir of await logDirs($)) {
|
|
60
|
+
const entries = await $.fs.list(dir).catch(() => []);
|
|
61
|
+
const indexes = new Set(entries.filter((entry) => entry.name.endsWith('.run.json')).map((entry) => entry.name));
|
|
62
|
+
for (const entry of entries) {
|
|
63
|
+
if (entry.kind !== 'file' || !entry.name.endsWith('.jsonl')) continue;
|
|
64
|
+
const id = entry.name.slice(0, -'.jsonl'.length);
|
|
65
|
+
const hasIndex = indexes.has(`${id}.run.json`);
|
|
66
|
+
if (!hasIndex && now - entry.mtimeMs > KEEP_AGENT_RUNS_MS) continue;
|
|
67
|
+
const index = hasIndex ? parseRunIndex(await $.fs.read(`${dir}/${id}.run.json`).catch(() => '')) : null;
|
|
68
|
+
if (index?.endedAt && now - index.endedAt > KEEP_AGENT_RUNS_MS) continue;
|
|
69
|
+
const log = `${dir}/${entry.name}`;
|
|
70
|
+
const trace = await traceOf($, log, entry.size, entry.mtimeMs);
|
|
71
|
+
const alive = index && index.endedAt === undefined ? await isAlive($, index.pid) : null;
|
|
72
|
+
found.push(agentRunOf({ id, log, index, trace, logChangedAt: entry.mtimeMs, isAlive: alive, now }));
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return found
|
|
76
|
+
.filter((run) => run.state === 'running' || now - (run.endedAt ?? now) <= KEEP_AGENT_RUNS_MS)
|
|
77
|
+
.sort((a, b) => b.startedAt - a.startedAt)
|
|
78
|
+
.slice(0, MAX_AGENT_RUNS);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function setStatus($: EngineInterface, text: string | undefined) {
|
|
82
|
+
if (text === shownStatus) return;
|
|
83
|
+
shownStatus = text;
|
|
84
|
+
$.ui.status(text);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async function refreshAgentRuns($: EngineInterface, sessionId: string, now: number) {
|
|
88
|
+
const [previous, claimed, waiting] = await Promise.all([
|
|
89
|
+
read($, agentRuns),
|
|
90
|
+
read($, toolRuns),
|
|
91
|
+
read($, waitingCalls),
|
|
92
|
+
]);
|
|
93
|
+
const next = await scanAgentRuns($, now);
|
|
94
|
+
if (JSON.stringify(next) !== JSON.stringify(previous)) await update($, agentRuns, () => next);
|
|
95
|
+
for (const text of finishNotices(previous, next, sessionId, now)) $.ui.toast(text);
|
|
96
|
+
if (waiting.length > 0) {
|
|
97
|
+
const paired = claimRuns(waiting, claimed, next, sessionId);
|
|
98
|
+
const open = paired.waiting.filter((call) => now - call.at < 60_000);
|
|
99
|
+
await update($, toolRuns, () => paired.claimed);
|
|
100
|
+
await update($, waitingCalls, () => open);
|
|
101
|
+
}
|
|
102
|
+
setStatus($, statusOf(next, now));
|
|
103
|
+
}
|
|
14
104
|
|
|
15
105
|
async function refresh($: EngineInterface) {
|
|
16
106
|
const [sessionId, root, now, previous] = await Promise.all([
|
|
@@ -31,7 +121,9 @@ async function refresh($: EngineInterface) {
|
|
|
31
121
|
previous,
|
|
32
122
|
now,
|
|
33
123
|
});
|
|
34
|
-
if ((await $.session.id())
|
|
124
|
+
if ((await $.session.id()) !== sessionId) return;
|
|
125
|
+
await update($, runs, () => next);
|
|
126
|
+
await refreshAgentRuns($, sessionId, now);
|
|
35
127
|
}
|
|
36
128
|
|
|
37
129
|
function poll($: EngineInterface) {
|
|
@@ -60,32 +152,99 @@ export const register: Register = (on) => {
|
|
|
60
152
|
return next(e);
|
|
61
153
|
});
|
|
62
154
|
|
|
155
|
+
on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
|
|
156
|
+
if (isCodexAgentCommand(e.command)) {
|
|
157
|
+
const at = await $.clock.now();
|
|
158
|
+
await update($, waitingCalls, (calls) => [...calls, { toolUseId: e.tool_use_id, at }]);
|
|
159
|
+
}
|
|
160
|
+
return next(e);
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
on('ui.render', { component: 'ToolUse' }, async ($, e, next) => {
|
|
164
|
+
const input = e.props.input as { command?: unknown } | undefined;
|
|
165
|
+
if (e.props.tool !== 'Bash' || !isCodexAgentCommand(input?.command)) return next(e);
|
|
166
|
+
const [row, claimed, shown, now] = await Promise.all([
|
|
167
|
+
next(e),
|
|
168
|
+
read($, toolRuns),
|
|
169
|
+
read($, agentRuns),
|
|
170
|
+
$.clock.now(),
|
|
171
|
+
]);
|
|
172
|
+
const run = shown.find((run) => run.id === claimed[e.props.tool_use_id]);
|
|
173
|
+
if (!run) return row;
|
|
174
|
+
const { Box, Text } = $.ui.resolve(e);
|
|
175
|
+
const detail = run.state === 'failed' ? run.error : run.progress;
|
|
176
|
+
return (
|
|
177
|
+
<Box flexDirection="column">
|
|
178
|
+
{row}
|
|
179
|
+
<Text dimColor wrap="truncate-end">
|
|
180
|
+
{` ⎿ codex ${run.state} · ${agentDurationOf(run, now)} · ${detail} · /codex-runs ${shortIdOf(run.id)}`}
|
|
181
|
+
</Text>
|
|
182
|
+
</Box>
|
|
183
|
+
);
|
|
184
|
+
});
|
|
185
|
+
|
|
63
186
|
on('command.run', { command: PANE }, async ($, e) => {
|
|
64
187
|
await poll($);
|
|
65
188
|
const name = e.args.trim();
|
|
66
|
-
const
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
189
|
+
const agentRun = name ? (await read($, agentRuns)).find((run) => isRunNamed(run, name)) : undefined;
|
|
190
|
+
const run =
|
|
191
|
+
name && !agentRun
|
|
192
|
+
? (await runsForSession($)).find((run) => run.name === name || run.name.startsWith(`${name}@`))
|
|
193
|
+
: undefined;
|
|
194
|
+
if (name && !run && !agentRun) return { text: `No visible Codex run named ${name}.` };
|
|
195
|
+
|
|
196
|
+
await update($, selected, () => agentRun?.id ?? run?.id ?? null);
|
|
197
|
+
await $.ui.open({ id: PANE, title: 'Codex' });
|
|
198
|
+
if (agentRun) return { text: `Showing the trace of the Codex run ${name}.` };
|
|
199
|
+
return { text: run ? `Showing recent output for ${run.name}.` : 'Codex pane opened.' };
|
|
74
200
|
});
|
|
75
201
|
|
|
76
202
|
on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
|
|
77
203
|
const { Box, Text } = $.ui.resolve(e);
|
|
78
|
-
const [shown, selectedId, now] = await Promise.all([
|
|
79
|
-
|
|
204
|
+
const [shown, agents, selectedId, sessionId, now] = await Promise.all([
|
|
205
|
+
runsForSession($),
|
|
206
|
+
read($, agentRuns),
|
|
207
|
+
read($, selected),
|
|
208
|
+
$.session.id(),
|
|
209
|
+
$.clock.now(),
|
|
210
|
+
]);
|
|
211
|
+
if (shown.length === 0 && agents.length === 0) return <Text dimColor>No Codex runs found.</Text>;
|
|
80
212
|
|
|
81
213
|
const run = shown.find((run) => run.id === selectedId);
|
|
214
|
+
const traced =
|
|
215
|
+
agents.find((agent) => agent.id === selectedId) ??
|
|
216
|
+
(run ? undefined : (agents.find((agent) => agent.state === 'running') ?? agents[0]));
|
|
82
217
|
return (
|
|
83
218
|
<Box flexDirection="column">
|
|
219
|
+
{agents.map((agent) => (
|
|
220
|
+
<Text key={agent.id} wrap="truncate-end" bold={agent.id === traced?.id}>
|
|
221
|
+
{`${shortIdOf(agent.id)} ${agent.state} · ${agentDurationOf(agent, now)} · ${agent.label}`}
|
|
222
|
+
{agent.session && agent.session !== sessionId ? ' · other session' : ''}
|
|
223
|
+
{` · ${agent.prompt || agent.progress}`}
|
|
224
|
+
</Text>
|
|
225
|
+
))}
|
|
84
226
|
{shown.map((run) => (
|
|
85
227
|
<Text key={run.id} wrap="truncate-end">
|
|
86
228
|
{run.name} · {run.state} · {durationOf(run, now)}
|
|
87
229
|
</Text>
|
|
88
230
|
))}
|
|
231
|
+
{traced && (
|
|
232
|
+
<Box flexDirection="column" marginTop={1}>
|
|
233
|
+
<Text bold wrap="truncate-end">
|
|
234
|
+
{`${shortIdOf(traced.id)} trace · ${traced.progress}`}
|
|
235
|
+
</Text>
|
|
236
|
+
{traced.error && <Text color="red">{traced.error}</Text>}
|
|
237
|
+
{traced.trace.length === 0 && <Text dimColor>No trace yet.</Text>}
|
|
238
|
+
{traced.trace.slice(-20).map((line, index) => (
|
|
239
|
+
<Text key={String(index)} wrap="truncate-end" dimColor={line.kind === 'command'}>
|
|
240
|
+
{line.kind === 'command' ? `$ ${line.text}` : line.kind === 'files' ? `~ ${line.text}` : line.text}
|
|
241
|
+
</Text>
|
|
242
|
+
))}
|
|
243
|
+
<Text dimColor wrap="truncate-end">
|
|
244
|
+
{traced.log}
|
|
245
|
+
</Text>
|
|
246
|
+
</Box>
|
|
247
|
+
)}
|
|
89
248
|
{run && (
|
|
90
249
|
<Box flexDirection="column" marginTop={1}>
|
|
91
250
|
<Text bold>{run.name} output</Text>
|
|
@@ -9,11 +9,29 @@ export type CodexRun = {
|
|
|
9
9
|
tail: string[];
|
|
10
10
|
};
|
|
11
11
|
|
|
12
|
+
export type AgentRun = {
|
|
13
|
+
id: string;
|
|
14
|
+
log: string;
|
|
15
|
+
session: string;
|
|
16
|
+
cwd: string;
|
|
17
|
+
label: string;
|
|
18
|
+
prompt: string;
|
|
19
|
+
startedAt: number;
|
|
20
|
+
endedAt: number | null;
|
|
21
|
+
state: 'running' | 'done' | 'failed';
|
|
22
|
+
error: string;
|
|
23
|
+
progress: string;
|
|
24
|
+
trace: { kind: 'command' | 'files' | 'message' | 'error'; text: string }[];
|
|
25
|
+
};
|
|
26
|
+
|
|
12
27
|
declare module 'claude-code' {
|
|
13
28
|
interface PluginState {
|
|
14
29
|
'codex-runs': {
|
|
15
30
|
runs: CodexRun[];
|
|
16
31
|
selected: string | null;
|
|
32
|
+
agentRuns: AgentRun[];
|
|
33
|
+
toolRuns: Record<string, string>;
|
|
34
|
+
waitingCalls: { toolUseId: string; at: number }[];
|
|
17
35
|
};
|
|
18
36
|
}
|
|
19
37
|
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
type RateLimit = { kind: string; percentUsed: number; resetsAt?: string };
|
|
2
|
+
|
|
3
|
+
export type RateLimitsFile = {
|
|
4
|
+
updatedAt: string;
|
|
5
|
+
limits: { kind: string; usedPercent: number; resetsAt: string | null }[];
|
|
6
|
+
};
|
|
7
|
+
|
|
8
|
+
export const RATE_LIMITS_FILE = 'state/rate-limits.json';
|
|
9
|
+
|
|
10
|
+
export function rateLimitsFileOf(limits: readonly RateLimit[], now: number): RateLimitsFile {
|
|
11
|
+
return {
|
|
12
|
+
updatedAt: new Date(now).toISOString(),
|
|
13
|
+
limits: limits.map(({ kind, percentUsed, resetsAt }) => ({
|
|
14
|
+
kind,
|
|
15
|
+
usedPercent: percentUsed,
|
|
16
|
+
resetsAt: resetsAt ?? null,
|
|
17
|
+
})),
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function rateLimitsKey(limits: readonly RateLimit[]) {
|
|
22
|
+
return JSON.stringify(limits.map(({ kind, percentUsed, resetsAt }) => [kind, percentUsed, resetsAt ?? null]));
|
|
23
|
+
}
|
|
@@ -4,6 +4,7 @@ import type { EngineInterface, Register } from 'claude-code';
|
|
|
4
4
|
import { latestCodexSample, formatCodex } from './codex';
|
|
5
5
|
import type { CodexSample } from './codex';
|
|
6
6
|
import { formatUsage, statusTextOf } from './format';
|
|
7
|
+
import { RATE_LIMITS_FILE, rateLimitsFileOf, rateLimitsKey } from './rate-limits';
|
|
7
8
|
|
|
8
9
|
const usage = atom({ plugin: 'usage-line', key: 'usage' } as const, null);
|
|
9
10
|
|
|
@@ -13,6 +14,7 @@ const CODEX_SCAN_FILES = 3;
|
|
|
13
14
|
|
|
14
15
|
let codexSample: CodexSample | undefined;
|
|
15
16
|
let codexCheckedAt = 0;
|
|
17
|
+
let writtenLimits = '';
|
|
16
18
|
|
|
17
19
|
async function newestDirectory($: EngineInterface, path: string) {
|
|
18
20
|
const entries = await $.fs.list(path).catch(() => []);
|
|
@@ -50,9 +52,23 @@ async function refreshCodex($: EngineInterface, now: number) {
|
|
|
50
52
|
codexSample = latest ?? codexSample;
|
|
51
53
|
}
|
|
52
54
|
|
|
55
|
+
async function writeRateLimits($: EngineInterface, limits: Parameters<typeof rateLimitsFileOf>[0], now: number) {
|
|
56
|
+
const key = rateLimitsKey(limits);
|
|
57
|
+
if (limits.length === 0 || key === writtenLimits) return;
|
|
58
|
+
const home = await $.env.get('HOME');
|
|
59
|
+
const configDir = (await $.env.get('CLAUDE_CONFIG_DIR')) ?? (home ? `${home}/.claude` : '');
|
|
60
|
+
if (!configDir) return;
|
|
61
|
+
const path = `${configDir.replace(/\/$/, '')}/${RATE_LIMITS_FILE}`;
|
|
62
|
+
const temp = `${path}.${now}.tmp`;
|
|
63
|
+
await $.fs.write(temp, `${JSON.stringify(rateLimitsFileOf(limits, now), null, 2)}\n`);
|
|
64
|
+
const moved = await $.process.run(['mv', '-f', temp, path], { timeoutMs: 2000 });
|
|
65
|
+
if (moved.exitCode === 0) writtenLimits = key;
|
|
66
|
+
}
|
|
67
|
+
|
|
53
68
|
export const register: Register = (on) => {
|
|
54
69
|
on('session.measure', async ($, e, next) => {
|
|
55
70
|
const now = await $.clock.now();
|
|
71
|
+
await writeRateLimits($, e.rateLimits, now).catch(() => undefined);
|
|
56
72
|
await refreshCodex($, now).catch(() => undefined);
|
|
57
73
|
const parts = [formatUsage(e.rateLimits), formatCodex(codexSample, now)].filter(Boolean);
|
|
58
74
|
const text = parts.length > 0 ? parts.join(' · ') : null;
|
|
@@ -97,4 +97,4 @@ A claim is advisory, not a lock. `--force` claims over another agent: use it onl
|
|
|
97
97
|
|
|
98
98
|
## Stop own processes
|
|
99
99
|
|
|
100
|
-
`stop-own [--dry-run]` stops what a session leaves behind, with no raw `kill`: processes that carry the caller's `CLAUDE_PID` but are reparented (no longer below that Claude process), and orphans of a dead session whose cwd lies in this checkout or its scratch dir, each with its whole subtree. Background tasks still attached to a live Claude process always stay: stop those with TaskStop first. Subagents share their session's `CLAUDE_PID`, so a process below the live session is never touched, and a reparented process counts as own only when its `ET_AGENT_ID` (stamped on every subagent Bash call by the `background-
|
|
100
|
+
`stop-own [--dry-run]` stops what a session leaves behind, with no raw `kill`: processes that carry the caller's `CLAUDE_PID` but are reparented (no longer below that Claude process), and orphans of a dead session whose cwd lies in this checkout or its scratch dir, each with its whole subtree. Background tasks still attached to a live Claude process always stay: stop those with TaskStop first. Subagents share their session's `CLAUDE_PID`, so a process below the live session is never touched, and a reparented process counts as own only when its `ET_AGENT_ID` (stamped on every subagent Bash call by the `background-commands` hook) equals the caller's: a subagent never stops a sibling's runs, and the main session never stops a subagent's. `--dry-run` lists without signalling; otherwise SIGTERM, up to 5 s, then SIGKILL. Linux only, same uid.
|