pi-optchat 0.5.1 → 0.6.1
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/README.md +13 -10
- package/package.json +2 -2
- package/src/agent-view.ts +305 -0
- package/src/agents.ts +1 -1
- package/src/browser.ts +225 -16
- package/src/import/guidance.ts +1 -1
- package/src/import/sources.ts +77 -0
- package/src/import/ui.ts +13 -12
- package/src/index.ts +4 -1
- package/src/inspector.ts +21 -102
- package/src/memory.ts +1 -1
- package/src/runs.ts +3 -2
package/README.md
CHANGED
|
@@ -5,7 +5,7 @@ A Pi extension that implements [Victor Taelin's OptChat recipe](https://gist.git
|
|
|
5
5
|
- **Memory**: every message is logged and summarized into a binary tree. Each turn starts from a fresh context holding a bounded memory view; the agent uses `zoom` and `date` to read originals.
|
|
6
6
|
- **Profiles**: separate memories and instructions, such as `work` and `personal`.
|
|
7
7
|
- **Subagents**: delegate tasks to background agents, inspect them live, and send them guidance.
|
|
8
|
-
- **Import**: bring in history from Claude Code, Codex, or ChatGPT.
|
|
8
|
+
- **Import**: bring in history from Claude Code (conversations and memories), Codex, or ChatGPT.
|
|
9
9
|
- **Connected windows**: a second Pi window on the same profile becomes a subagent you talk to directly.
|
|
10
10
|
|
|
11
11
|
It runs inside ordinary Pi, with no fork or separate launcher.
|
|
@@ -46,7 +46,7 @@ For headless use, pass `--optchat-profile work`.
|
|
|
46
46
|
| `/optchat agents model` | Subagent model and effort for this profile. |
|
|
47
47
|
| `/optchat usage` | Token usage and cost estimates. |
|
|
48
48
|
| `/optchat instructions` | Edit this profile's `AGENTS.md`. |
|
|
49
|
-
| `/optchat browse` | Open
|
|
49
|
+
| `/optchat browse` | Open a readable snapshot of memory: the shape of what the model sees, summaries you can open down to the original messages, and search that shows where each message is folded. Run again to refresh. |
|
|
50
50
|
| `/optchat import` | Import history, or resume/discard a paused import. |
|
|
51
51
|
| `/complete` | In a connected window: end the conversation and hand off to the main agent. |
|
|
52
52
|
| `/tell-main <message>` | In a connected window: message the main agent. |
|
|
@@ -89,15 +89,16 @@ An **Agents | Usage** bar sits below the input.
|
|
|
89
89
|
|
|
90
90
|
Set a different shortcut with `OPTCHAT_INSPECT_KEY=ctrl+shift+a pi`. If another extension supplies a custom editor, OptChat leaves its Down key alone; use the shortcut or commands instead.
|
|
91
91
|
|
|
92
|
-
**Agents** lists runs as a tree with state, elapsed time, current tool, and last activity. Navigate with **Up/Down**, **Page Up/Down**, **Home/End**,
|
|
92
|
+
**Agents** lists runs as a tree with state, elapsed time, current tool, and last activity. Navigate with **Up/Down**, **Page Up/Down**, **Home/End**, and press **M** to pick the subagent model.
|
|
93
|
+
|
|
94
|
+
**Enter** swaps the screen to that agent's conversation, drawn with Pi's own chat components, so it reads like the main chat: its task, replies, and collapsed tool calls, following live output. Typing and **Enter** send it guidance. Guidance from the main agent and reports from the agent's own agents show in labelled boxes, so only your own messages look typed. **Escape** goes back to the main chat.
|
|
93
95
|
|
|
94
96
|
| Key | Action |
|
|
95
97
|
| --- | --- |
|
|
96
|
-
| **
|
|
97
|
-
| **
|
|
98
|
-
| **
|
|
99
|
-
| **
|
|
100
|
-
| **Escape** | Back |
|
|
98
|
+
| **Escape** or **Ctrl+C** | Clear a draft, else back to the main chat |
|
|
99
|
+
| **Ctrl+X** twice | Stop this agent and the agents it started |
|
|
100
|
+
| **Page Up/Down**, mouse wheel | Scroll; back at the bottom it follows again. The wheel needs Pi's default fullscreen mode |
|
|
101
|
+
| **Ctrl+O** | Expand tool output (Pi's own toggle) |
|
|
101
102
|
|
|
102
103
|
Guidance shows as queued until delivered, or undelivered if the child stops first. Guidance you send is also saved in main memory. Reasoning is not shown. Transcripts stay browsable after restart, and browsing them makes no model calls.
|
|
103
104
|
|
|
@@ -112,8 +113,8 @@ Guidance shows as queued until delivered, or undelivered if the child stops firs
|
|
|
112
113
|
|
|
113
114
|
Pick the destination profile, then run `/optchat import`.
|
|
114
115
|
|
|
115
|
-
1. **Source**: Claude Code (`~/.claude/projects`), Codex (`~/.codex/sessions`, `~/.codex/archived_sessions`), or a ChatGPT export (ZIP, folder, or `conversations.json`; ZIP needs `unzip`). Scanning is local and makes no model calls.
|
|
116
|
-
2. **Select**: for Claude Code and Codex, pick projects (busiest first), optionally filter by start date, then take all conversations or pick some. **Space** toggles, **Enter** continues, type to filter, **Ctrl+A**/**Ctrl+D** select/clear matches, **Esc** cancels. Nothing is classified as work or personal for you.
|
|
116
|
+
1. **Source**: Claude Code (`~/.claude/projects`), Claude Code memories, Codex (`~/.codex/sessions`, `~/.codex/archived_sessions`), or a ChatGPT export (ZIP, folder, or `conversations.json`; ZIP needs `unzip`). Scanning is local and makes no model calls.
|
|
117
|
+
2. **Select**: for Claude Code, its memories, and Codex, pick projects (busiest first), optionally filter by start date, then take all conversations or pick some. **Space** toggles, **Enter** continues, type to filter, **Ctrl+A**/**Ctrl+D** select/clear matches, **Esc** cancels. Nothing is classified as work or personal for you.
|
|
117
118
|
3. **Mode** (only if the profile already has history):
|
|
118
119
|
- **Append**: keep existing summaries and add the import. Faster and cheaper.
|
|
119
120
|
- **Rebuild by conversation start date**: regenerate the whole tree, ordered by conversation start.
|
|
@@ -121,6 +122,8 @@ Pick the destination profile, then run `/optchat import`.
|
|
|
121
122
|
|
|
122
123
|
**What gets imported**: user messages and final assistant replies, with original dates and source labels, as in Victor's recipe. Tool calls and results, intermediate commentary, reasoning, subagent transcripts, replayed context, and image/audio/file bytes are left out. ChatGPT alternate branches are labelled as alternatives. Imported records are marked as historical so old requests are not treated as new instructions.
|
|
123
124
|
|
|
125
|
+
**Claude Code memories**: the auto-memory topic files in `~/.claude/projects/*/memory/` (not `MEMORY.md`, which only indexes them), picked by project. Each file becomes one dated note in the memory tree, not part of the prompt. An edited file comes in again as a newer note.
|
|
126
|
+
|
|
124
127
|
**Duplicates**: re-importing skips messages already present, even if titles or paths changed. Changed source messages can appear as a separate historical version.
|
|
125
128
|
|
|
126
129
|
**Pausing**: **Pause import** (or Escape) saves progress, and so does restarting Pi. `/optchat import` then offers **Resume** or **Discard staged import**. While an import is pending, chat in that profile is blocked; other profiles still work. Imports need the main agent and its subagents to be idle.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-optchat",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"pi": {
|
|
6
6
|
"extensions": [
|
|
@@ -52,7 +52,7 @@
|
|
|
52
52
|
},
|
|
53
53
|
"files": [
|
|
54
54
|
"src",
|
|
55
|
-
"docs",
|
|
55
|
+
"docs/*.md",
|
|
56
56
|
"README.md",
|
|
57
57
|
"LICENSE",
|
|
58
58
|
"THIRD_PARTY_NOTICES.md"
|
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AssistantMessageComponent, CustomMessageComponent, ToolExecutionComponent, UserMessageComponent, getMarkdownTheme, getSelectListTheme,
|
|
3
|
+
createBashToolDefinition, createEditToolDefinition, createFindToolDefinition, createGrepToolDefinition, createLsToolDefinition, createReadToolDefinition, createWriteToolDefinition,
|
|
4
|
+
type ExtensionContext,
|
|
5
|
+
} from '@earendil-works/pi-coding-agent';
|
|
6
|
+
import { Editor, Spacer, matchesKey, truncateToWidth, visibleWidth, type Component, type Focusable, type TUI, type TuiMouseEvent, type TuiMouseEventResult } from '@earendil-works/pi-tui';
|
|
7
|
+
import type { AgentMessage } from '@earendil-works/pi-agent-core';
|
|
8
|
+
import type { Children } from './agents.ts';
|
|
9
|
+
import type { RunInfo } from './runs.ts';
|
|
10
|
+
import { textContent } from './transcript.ts';
|
|
11
|
+
import { record } from './cache.ts';
|
|
12
|
+
import { elapsed, fit, oneLine } from './inspector.ts';
|
|
13
|
+
|
|
14
|
+
export type ViewTone = 'accent' | 'muted' | 'dim' | 'error' | 'warning' | 'success' | 'borderMuted';
|
|
15
|
+
type ToolResult = Parameters<ToolExecutionComponent['updateResult']>[0];
|
|
16
|
+
type Renderers = ConstructorParameters<typeof ToolExecutionComponent>[4];
|
|
17
|
+
type Guidance = RunInfo['guidance'];
|
|
18
|
+
type Running = Map<string, { output?: unknown; started: number }>;
|
|
19
|
+
|
|
20
|
+
/** Pi's own renderers for its built-in tools, so saved runs draw like the main chat. */
|
|
21
|
+
const builtIns: Record<string, (cwd: string) => Renderers> = {
|
|
22
|
+
bash: createBashToolDefinition, read: createReadToolDefinition, edit: createEditToolDefinition, write: createWriteToolDefinition,
|
|
23
|
+
grep: createGrepToolDefinition, find: createFindToolDefinition, ls: createLsToolDefinition,
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
/** Reports from the child's own agents start with their id, e.g. "[1a2b3c4d] ...". */
|
|
27
|
+
const REPORT = /^\[[0-9a-f]{8}\] /;
|
|
28
|
+
/** Connected windows prefix the main agent's guidance with this line. */
|
|
29
|
+
const MAIN_PREFIX = '[Main agent guidance]\n';
|
|
30
|
+
|
|
31
|
+
/** Who a user-role message in the child's conversation came from. Runs saved before senders were recorded count as the user's. */
|
|
32
|
+
export function senderOf(text: string, guidance: Guidance = []): 'user' | 'manager' | 'report' {
|
|
33
|
+
if (REPORT.test(text)) return 'report';
|
|
34
|
+
if (text.startsWith(MAIN_PREFIX)) return 'manager';
|
|
35
|
+
return guidance.findLast(g => g.text === text)?.from === 'manager' ? 'manager' : 'user';
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Background traffic gets Pi's labelled box, as extension messages do in the main chat; only the user's own words look typed. */
|
|
39
|
+
const boxed = (label: string, text: string, timestamp: number) =>
|
|
40
|
+
new CustomMessageComponent({ role: 'custom', customType: label, content: text, display: true, timestamp }, undefined, getMarkdownTheme());
|
|
41
|
+
|
|
42
|
+
function toolResult(value: unknown, isError = false): ToolResult | undefined {
|
|
43
|
+
if (!record(value) || !Array.isArray(value.content)) return undefined;
|
|
44
|
+
const content = value.content.flatMap((part: unknown) => record(part) && typeof part.type === 'string'
|
|
45
|
+
? [{ type: part.type, ...(typeof part.text === 'string' ? { text: part.text } : {}), ...(typeof part.data === 'string' ? { data: part.data } : {}), ...(typeof part.mimeType === 'string' ? { mimeType: part.mimeType } : {}) }] : []);
|
|
46
|
+
return { content, details: value.details, isError };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Builds the child's conversation from Pi's chat components and keeps them between frames,
|
|
51
|
+
* so streaming text and running tools update in place like in the main chat.
|
|
52
|
+
*/
|
|
53
|
+
export class TranscriptView {
|
|
54
|
+
private readonly messages = new WeakMap<AgentMessage, Component>();
|
|
55
|
+
private readonly tools = new Map<string, ToolExecutionComponent>();
|
|
56
|
+
private readonly settled = new Set<string>();
|
|
57
|
+
private readonly partials = new Map<string, unknown>();
|
|
58
|
+
private readonly starts = new Map<string, number>();
|
|
59
|
+
private readonly ends = new Map<string, number>();
|
|
60
|
+
private streaming?: AssistantMessageComponent;
|
|
61
|
+
private expanded = false;
|
|
62
|
+
constructor(private readonly tui: TUI, private readonly cwd: string, private readonly definition: (name: string) => Renderers = () => undefined) {}
|
|
63
|
+
toggleTools() { this.expanded = !this.expanded; for (const tool of this.tools.values()) tool.setExpanded(this.expanded); }
|
|
64
|
+
private tool(id: string, name: string, args: unknown) {
|
|
65
|
+
let tool = this.tools.get(id);
|
|
66
|
+
if (!tool) {
|
|
67
|
+
tool = new ToolExecutionComponent(name, id, args, { showImages: false }, this.renderers(id, name), this.tui, this.cwd);
|
|
68
|
+
tool.setExpanded(this.expanded); this.tools.set(id, tool);
|
|
69
|
+
}
|
|
70
|
+
return tool;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Pi's shell renderer times a command from the moment it is first drawn, so opening the view would restart the clock.
|
|
74
|
+
* Hand it the real start and end instead; unknown starts (runs finished before the view saw them) show no time.
|
|
75
|
+
*/
|
|
76
|
+
private renderers(id: string, name: string): Renderers {
|
|
77
|
+
const base = builtIns[name]?.(this.cwd);
|
|
78
|
+
if (!base) return this.definition(name);
|
|
79
|
+
const { renderCall, renderResult } = base;
|
|
80
|
+
const stamp = (state: unknown) => {
|
|
81
|
+
if (!record(state)) return;
|
|
82
|
+
const started = this.starts.get(id), ended = this.ends.get(id);
|
|
83
|
+
if (started !== undefined) state.startedAt = started;
|
|
84
|
+
if (ended !== undefined) state.endedAt = ended;
|
|
85
|
+
// The view redraws every second itself; the renderer's own timer would keep redrawing Pi after the view closes.
|
|
86
|
+
state.interval ??= 'view';
|
|
87
|
+
};
|
|
88
|
+
return {
|
|
89
|
+
...base,
|
|
90
|
+
...(renderCall ? { renderCall: (args, theme, context) => { stamp(context.state); return renderCall.call(base, args, theme, context); } } : {}),
|
|
91
|
+
...(renderResult ? { renderResult: (result, options, theme, context) => { stamp(context.state); return renderResult.call(base, result, options, theme, context); } } : {}),
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
/** `task` replaces the first prompt, which also carries the memory view the child got as context. */
|
|
95
|
+
build(task: string, messages: AgentMessage[], streaming?: AgentMessage, running?: Running, guidance?: Guidance): Component[] {
|
|
96
|
+
const parts: Component[] = [];
|
|
97
|
+
let first = true;
|
|
98
|
+
for (const message of messages) {
|
|
99
|
+
if (message.role === 'user') {
|
|
100
|
+
const opening = first; first = false;
|
|
101
|
+
const text = opening ? task : textContent(message.content).trim();
|
|
102
|
+
if (!text) continue;
|
|
103
|
+
let component = this.messages.get(message);
|
|
104
|
+
if (!component) {
|
|
105
|
+
const sender = opening ? 'user' : senderOf(text, guidance);
|
|
106
|
+
component = sender === 'manager' ? boxed('main agent', text.startsWith(MAIN_PREFIX) ? text.slice(MAIN_PREFIX.length) : text, message.timestamp)
|
|
107
|
+
: sender === 'report' ? boxed('agent report', text, message.timestamp)
|
|
108
|
+
: new UserMessageComponent(text, getMarkdownTheme());
|
|
109
|
+
this.messages.set(message, component);
|
|
110
|
+
}
|
|
111
|
+
if (parts.length && component instanceof UserMessageComponent) parts.push(new Spacer(1)); // Boxes bring their own.
|
|
112
|
+
parts.push(component);
|
|
113
|
+
} else if (message.role === 'assistant') {
|
|
114
|
+
const live = message === streaming;
|
|
115
|
+
let component: Component | undefined;
|
|
116
|
+
if (live) { this.streaming ??= new AssistantMessageComponent(undefined, true, getMarkdownTheme()); this.streaming.updateContent(message, true); component = this.streaming; }
|
|
117
|
+
else {
|
|
118
|
+
component = this.messages.get(message);
|
|
119
|
+
if (!component) { component = new AssistantMessageComponent(message, true, getMarkdownTheme()); this.messages.set(message, component); }
|
|
120
|
+
}
|
|
121
|
+
parts.push(component);
|
|
122
|
+
for (const part of message.content) {
|
|
123
|
+
if (part.type !== 'toolCall') continue;
|
|
124
|
+
const tool = this.tool(part.id, part.name, part.arguments);
|
|
125
|
+
if (live) { if (this.partials.get(`args:${part.id}`) !== part.arguments) { tool.updateArgs(part.arguments); this.partials.set(`args:${part.id}`, part.arguments); } }
|
|
126
|
+
else if (!this.settled.has(`args:${part.id}`)) {
|
|
127
|
+
tool.updateArgs(part.arguments); tool.setArgsComplete(); this.settled.add(`args:${part.id}`);
|
|
128
|
+
if ((message.stopReason === 'aborted' || message.stopReason === 'error') && !this.settled.has(part.id)) {
|
|
129
|
+
tool.updateResult({ content: [{ type: 'text', text: message.errorMessage || (message.stopReason === 'aborted' ? 'Operation aborted' : 'Error') }], isError: true });
|
|
130
|
+
this.settled.add(part.id);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
parts.push(tool);
|
|
134
|
+
}
|
|
135
|
+
} else if (message.role === 'toolResult' && !this.settled.has(message.toolCallId)) {
|
|
136
|
+
const result = toolResult(message, message.isError);
|
|
137
|
+
const tool = this.tools.get(message.toolCallId);
|
|
138
|
+
if (result && tool) { this.ends.set(message.toolCallId, message.timestamp); tool.updateResult(result); this.settled.add(message.toolCallId); }
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
if (!streaming) this.streaming = undefined;
|
|
142
|
+
// Each call below redraws, so only pass on what changed since the last frame.
|
|
143
|
+
for (const [id, run] of running ?? []) {
|
|
144
|
+
const tool = this.tools.get(id);
|
|
145
|
+
if (!tool || this.settled.has(id)) continue;
|
|
146
|
+
if (!this.settled.has(`started:${id}`)) { this.starts.set(id, run.started); tool.markExecutionStarted(); this.settled.add(`started:${id}`); }
|
|
147
|
+
const partial = run.output !== this.partials.get(id) ? toolResult(run.output) : undefined;
|
|
148
|
+
if (partial) { tool.updateResult(partial, true); this.partials.set(id, run.output); }
|
|
149
|
+
else tool.invalidate(); // Ticks the running time.
|
|
150
|
+
}
|
|
151
|
+
return parts;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export interface AgentViewOptions {
|
|
156
|
+
id: string; children: Children; tui: TUI;
|
|
157
|
+
rows: () => number; redraw: () => void; done: () => void;
|
|
158
|
+
color: (tone: ViewTone, text: string) => string;
|
|
159
|
+
/** Pi's tool-output toggle (Ctrl+O by default), so tool calls expand the same way as in the main chat. */
|
|
160
|
+
isExpandKey?: (data: string) => boolean;
|
|
161
|
+
signal?: AbortSignal;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const statusOf = (run: RunInfo, children: Children) => {
|
|
165
|
+
const live = children.live(run.id);
|
|
166
|
+
if (!live) return run.state;
|
|
167
|
+
if (run.state === 'stopping') return 'stopping';
|
|
168
|
+
if (run.state === 'waiting') return 'waiting for its agents';
|
|
169
|
+
const tools = [...live.tools.values()].map(t => t.name);
|
|
170
|
+
return tools.length ? `running ${tools.join(', ')}` : live.streaming ? 'writing' : 'working';
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* The subagent's conversation in place of the main one: same message components, one header line,
|
|
175
|
+
* an input that guides the agent, and Esc back to the main chat. A UI projection only.
|
|
176
|
+
*/
|
|
177
|
+
export class AgentView implements Component, Focusable {
|
|
178
|
+
private readonly editor: Editor;
|
|
179
|
+
private readonly transcript: TranscriptView;
|
|
180
|
+
private back = 0; // Lines scrolled up from the newest; 0 follows live output.
|
|
181
|
+
private bodyHeight = 1;
|
|
182
|
+
private overflow = 0;
|
|
183
|
+
private drawn = { lines: 0, width: 0 }; // Last frame, so new output doesn't move what you're reading while scrolled up.
|
|
184
|
+
private saved?: AgentMessage[];
|
|
185
|
+
private wasLive = false;
|
|
186
|
+
private confirmStop = false;
|
|
187
|
+
private notice = '';
|
|
188
|
+
private ended = false;
|
|
189
|
+
private hasFocus = true;
|
|
190
|
+
private readonly unsubscribe: () => void;
|
|
191
|
+
private readonly timer: ReturnType<typeof setInterval>;
|
|
192
|
+
constructor(private readonly options: AgentViewOptions) {
|
|
193
|
+
const { children, id, tui, color } = options;
|
|
194
|
+
const run = children.history.records.get(id);
|
|
195
|
+
this.transcript = new TranscriptView(tui, run?.cwd ?? process.cwd(), name => children.live(id)?.session.getToolDefinition(name));
|
|
196
|
+
this.editor = new Editor(tui, { borderColor: text => color('borderMuted', text), selectList: getSelectListTheme() });
|
|
197
|
+
this.editor.onSubmit = text => this.send(text);
|
|
198
|
+
this.editor.focused = true;
|
|
199
|
+
this.unsubscribe = children.subscribe(() => options.redraw());
|
|
200
|
+
this.timer = setInterval(() => options.redraw(), 1000); this.timer.unref();
|
|
201
|
+
options.signal?.addEventListener('abort', this.close, { once: true });
|
|
202
|
+
if (options.signal?.aborted) queueMicrotask(this.close);
|
|
203
|
+
}
|
|
204
|
+
get focused() { return this.hasFocus; }
|
|
205
|
+
set focused(value: boolean) { this.hasFocus = value; this.editor.focused = value; }
|
|
206
|
+
private readonly close = () => { if (!this.ended) { this.dispose(); this.options.done(); } };
|
|
207
|
+
dispose() { this.ended = true; clearInterval(this.timer); this.unsubscribe(); this.options.signal?.removeEventListener('abort', this.close); }
|
|
208
|
+
invalidate() { this.editor.invalidate(); }
|
|
209
|
+
private get canMessage() { return ['running', 'waiting'].includes(this.options.children.live(this.options.id)?.info.state ?? ''); }
|
|
210
|
+
private scroll(lines: number) { this.back = Math.max(0, Math.min(this.overflow, this.back + lines)); }
|
|
211
|
+
/** Wheel scrolling, in Pi's default fullscreen mode; in "regular" mode the terminal keeps the wheel. */
|
|
212
|
+
handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
|
|
213
|
+
if (this.ended || event.type !== 'wheel' || !event.wheelDelta) return undefined;
|
|
214
|
+
this.scroll(-event.wheelDelta);
|
|
215
|
+
return { handled: true };
|
|
216
|
+
}
|
|
217
|
+
private send(text: string) {
|
|
218
|
+
const message = text.trim(), { children, id } = this.options;
|
|
219
|
+
if (!message) return;
|
|
220
|
+
children.tell(id, message, 'user').then(() => { this.notice = ''; }, (error: unknown) => {
|
|
221
|
+
this.editor.setText(text); this.notice = `Not sent: ${error instanceof Error ? error.message : String(error)}`;
|
|
222
|
+
}).finally(() => { if (!this.ended) this.options.redraw(); });
|
|
223
|
+
}
|
|
224
|
+
handleInput(data: string) {
|
|
225
|
+
if (this.ended) return;
|
|
226
|
+
const { children, id } = this.options;
|
|
227
|
+
const stopping = this.confirmStop; this.confirmStop = false; this.notice = '';
|
|
228
|
+
if ((matchesKey(data, 'escape') && !this.editor.isShowingAutocomplete()) || matchesKey(data, 'ctrl+c')) {
|
|
229
|
+
if (!this.editor.getText()) return this.close();
|
|
230
|
+
this.editor.setText(''); // First press clears a draft, as in the main editor.
|
|
231
|
+
return this.options.redraw();
|
|
232
|
+
}
|
|
233
|
+
if (matchesKey(data, 'ctrl+x')) {
|
|
234
|
+
if (!children.live(id)) this.notice = 'This agent has already finished.';
|
|
235
|
+
else if (stopping) children.stop(id).catch((error: unknown) => { this.notice = `Could not stop: ${String(error)}`; this.options.redraw(); });
|
|
236
|
+
else this.confirmStop = true;
|
|
237
|
+
} else if (matchesKey(data, 'pageUp')) this.scroll(Math.max(1, this.bodyHeight - 2));
|
|
238
|
+
else if (matchesKey(data, 'pageDown')) this.scroll(-Math.max(1, this.bodyHeight - 2));
|
|
239
|
+
else if (this.options.isExpandKey?.(data)) this.transcript.toggleTools();
|
|
240
|
+
else if (this.canMessage) this.editor.handleInput(data);
|
|
241
|
+
this.options.redraw();
|
|
242
|
+
}
|
|
243
|
+
private messages(run: RunInfo) {
|
|
244
|
+
const { children } = this.options, live = children.live(run.id);
|
|
245
|
+
// Saved transcripts are read once; live ones come from memory each frame, plus one final read when the run ends.
|
|
246
|
+
if (live || this.wasLive || !this.saved) {
|
|
247
|
+
try { this.saved = children.messages(run.id); }
|
|
248
|
+
catch (error) { this.notice = `Transcript unavailable: ${String(error)}`; this.saved = []; }
|
|
249
|
+
}
|
|
250
|
+
this.wasLive = !!live;
|
|
251
|
+
return this.saved;
|
|
252
|
+
}
|
|
253
|
+
private header(run: RunInfo | undefined, width: number) {
|
|
254
|
+
const { color, children, id } = this.options;
|
|
255
|
+
if (!run) return color('error', ` ${id} · run not found`);
|
|
256
|
+
const live = children.live(run.id);
|
|
257
|
+
const dot = live ? color('accent', '●') : run.state === 'completed' ? color('success', '✓') : run.state === 'failed' ? color('error', '✗') : color('muted', '■');
|
|
258
|
+
const right = `${statusOf(run, children)} · ${elapsed((run.ended ?? Date.now()) - run.started)} · ${run.model.slice(run.model.indexOf('/') + 1)}`;
|
|
259
|
+
const left = ` ${dot} ${color('accent', run.id)} `;
|
|
260
|
+
const room = width - visibleWidth(left) - visibleWidth(right) - 3;
|
|
261
|
+
if (room < 8) return truncateToWidth(`${left}${color('dim', right)}`, width);
|
|
262
|
+
const task = fit(oneLine(run.task), room);
|
|
263
|
+
return `${left}${task}${' '.repeat(Math.max(2, width - visibleWidth(left) - visibleWidth(task) - visibleWidth(right) - 1))}${color('dim', right)} `;
|
|
264
|
+
}
|
|
265
|
+
render(width: number): string[] {
|
|
266
|
+
const { color, children, id, rows } = this.options;
|
|
267
|
+
const run = children.history.records.get(id), live = children.live(id);
|
|
268
|
+
const height = Math.max(1, rows());
|
|
269
|
+
const top = [this.header(run, width), color('borderMuted', '─'.repeat(width))];
|
|
270
|
+
let input: string[];
|
|
271
|
+
if (this.canMessage) input = this.editor.render(width);
|
|
272
|
+
else if (live) input = [color('dim', ' Stopping…')];
|
|
273
|
+
else input = run ? [color('borderMuted', '─'.repeat(width)), color('dim', ` ${run.state === 'completed' ? 'Finished' : `Ended (${run.state})`}. ${run.parentId ? 'Its report went to the agent that started it.' : 'Its report went to the main agent.'}`)] : [];
|
|
274
|
+
const pending = (run?.guidance ?? []).filter(g => g.state !== 'delivered');
|
|
275
|
+
// Only the conversation gives way to the controls: at most three pending lines, then a count.
|
|
276
|
+
const queued = pending.slice(-3).map(g => color(g.state === 'queued' ? 'muted' : 'warning',
|
|
277
|
+
` ${g.state === 'queued' ? 'Queued' : 'Not delivered'}${g.from === 'manager' ? ' (main agent)' : ''}: ${oneLine(g.text)}`));
|
|
278
|
+
if (pending.length > 3) queued.unshift(color('muted', ` +${pending.length - 3} more not yet delivered`));
|
|
279
|
+
this.bodyHeight = Math.max(0, height - top.length - input.length - 1 - queued.length); // One footer line.
|
|
280
|
+
const parts = run ? this.transcript.build(run.task, this.messages(run), live?.streaming, live?.tools, run.guidance) : [];
|
|
281
|
+
const lines = parts.flatMap(part => part.render(width));
|
|
282
|
+
if (this.back && this.drawn.width === width) this.back += Math.max(0, lines.length - this.drawn.lines);
|
|
283
|
+
this.drawn = { lines: lines.length, width };
|
|
284
|
+
this.overflow = Math.max(0, lines.length - this.bodyHeight);
|
|
285
|
+
this.back = Math.min(this.back, this.overflow);
|
|
286
|
+
const end = lines.length - this.back;
|
|
287
|
+
const body = lines.slice(Math.max(0, end - this.bodyHeight), end);
|
|
288
|
+
while (body.length < this.bodyHeight) body.push('');
|
|
289
|
+
const hint = this.confirmStop ? color('warning', ' Press Ctrl+X again to stop this agent and the agents it started')
|
|
290
|
+
: this.notice ? color('error', ` ${this.notice}`)
|
|
291
|
+
: color('dim', ` ${this.editor.getText() ? 'Esc clear' : 'Esc back to main'}${live ? ' · Ctrl+X stop' : ''}${this.overflow ? this.back ? ' · PgDn newer' : ' · PgUp older' : ''}`);
|
|
292
|
+
const scrolled = this.back ? color('warning', `↑ ${this.back} lines up `) : '';
|
|
293
|
+
const footer = [visibleWidth(hint) + visibleWidth(scrolled) < width ? `${hint}${' '.repeat(width - visibleWidth(hint) - visibleWidth(scrolled))}${scrolled}` : hint];
|
|
294
|
+
// On a terminal too short for everything, the header goes first; the input and footer stay.
|
|
295
|
+
return [...top, ...body, ...queued, ...input, ...footer].slice(-height).map(line => truncateToWidth(line, width));
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** Swaps the whole screen to the subagent's conversation; Pi restores the main chat on close. */
|
|
300
|
+
export function showAgentView(ctx: ExtensionContext, options: { id: string; children: Children; signal?: AbortSignal }) {
|
|
301
|
+
return ctx.ui.custom<void>((tui, theme, keybindings, done) => new AgentView({ ...options, tui,
|
|
302
|
+
rows: () => tui.terminal.rows, redraw: () => tui.requestRender(), done: () => done(undefined),
|
|
303
|
+
color: (tone, text) => theme.fg(tone, text), isExpandKey: data => keybindings.matches(data, 'app.tools.expand'),
|
|
304
|
+
}), { overlay: true, overlayOptions: { width: '100%', maxHeight: '100%', row: 0, col: 0 } });
|
|
305
|
+
}
|
package/src/agents.ts
CHANGED
|
@@ -255,7 +255,7 @@ export class Children {
|
|
|
255
255
|
if (!live || !['running', 'waiting'].includes(live.info.state)) throw new Error(`No running subagent ${id}.`);
|
|
256
256
|
const text = live.info.connected && source === 'manager' ? `[Main agent guidance]\n${message.trim()}` : message.trim(); if (!message.trim()) throw new Error('Message is empty.');
|
|
257
257
|
if (source === 'user') this.memory.append('user', `Direct guidance to subagent [${id}]: ${text}`);
|
|
258
|
-
const guidance: RunInfo['guidance'][number] = { text, date: Date.now(), state: 'queued' };
|
|
258
|
+
const guidance: RunInfo['guidance'][number] = { text, date: Date.now(), state: 'queued', from: source };
|
|
259
259
|
live.info.guidance.push(guidance); this.save(live.info);
|
|
260
260
|
try {
|
|
261
261
|
if (live.info.state === 'waiting') { live.pendingGuidance.push(text); live.wake?.(); }
|
package/src/browser.ts
CHANGED
|
@@ -2,21 +2,230 @@ import { join } from 'node:path';
|
|
|
2
2
|
import { atomicWrite } from './profiles.ts';
|
|
3
3
|
import { type Memory } from './memory.ts';
|
|
4
4
|
|
|
5
|
+
// One self-contained, read-only HTML snapshot of a profile's memory.
|
|
5
6
|
export function exportBrowser(memory: Memory, profile: string, directory = memory.directory) {
|
|
6
|
-
const data = JSON.stringify({
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
const
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
7
|
+
const data = JSON.stringify({
|
|
8
|
+
profile, budget: memory.budget, size: memory.size, view: memory.view,
|
|
9
|
+
root: memory.root.map(({ i, kind, text, date, origin }) => ({ i, kind, text, date, ...(origin ? { origin: { source: origin.source, title: origin.title } } : {}) })),
|
|
10
|
+
tree: [...memory.tree.values()].map(({ l, i, text }) => ({ l, i, text })),
|
|
11
|
+
}).replace(/</g, '\\u003c');
|
|
12
|
+
const path = join(directory, 'memory.html'); atomicWrite(path, PAGE.replace('__DATA__', () => data)); return path;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// Client code avoids backticks and template placeholders so it can live in String.raw.
|
|
16
|
+
const PAGE = String.raw`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>OptChat memory</title>
|
|
17
|
+
<style>
|
|
18
|
+
:root{--bg:#f7f3ea;--paper:#fffdf8;--ink:#2a2723;--muted:#6b6357;--rule:#e4dccd;--accent:#7d5630;--bar:#d5c7ad;--you:#3f6380;--talk:#2a2723;--work:#4c6a41;--tool:#6b6357;--note:#80601f;--hl:#f6e7c1}
|
|
19
|
+
*{box-sizing:border-box}
|
|
20
|
+
body{margin:0;background:var(--bg);color:var(--ink);font:16px/1.6 -apple-system,BlinkMacSystemFont,"Segoe UI",system-ui,sans-serif;-webkit-font-smoothing:antialiased}
|
|
21
|
+
.wrap{max-width:780px;margin:0 auto;padding:64px 28px 160px}
|
|
22
|
+
h1{font:400 36px/1.15 "Iowan Old Style",Charter,Georgia,serif;margin:0 0 4px}
|
|
23
|
+
h1 small{font-size:18px;color:var(--muted);margin-left:10px}
|
|
24
|
+
.lede{color:var(--muted);margin:0 0 4px}
|
|
25
|
+
.explain{font-size:14px;color:var(--muted);margin:16px 0 0;max-width:620px}
|
|
26
|
+
.shape{display:flex;align-items:flex-end;gap:1px;height:84px;margin:36px 0 6px}
|
|
27
|
+
.shape.dense{gap:0}
|
|
28
|
+
.shape button{flex:1 1 0;min-width:0;border:0;padding:0;background:var(--bar);border-radius:1px;cursor:pointer}
|
|
29
|
+
.shape button:hover,.shape button:focus-visible{background:var(--accent);outline:none}
|
|
30
|
+
.axis{display:flex;justify-content:space-between;font-size:12px;color:var(--muted)}
|
|
31
|
+
nav{display:flex;gap:28px;margin:48px 0 8px;border-bottom:1px solid var(--rule)}
|
|
32
|
+
nav button{background:none;border:0;border-bottom:2px solid transparent;margin-bottom:-1px;padding:0 0 10px;font:inherit;color:var(--muted);cursor:pointer}
|
|
33
|
+
nav button.on{color:var(--ink);border-color:var(--ink)}
|
|
34
|
+
h2.day{font-size:12px;font-weight:600;line-height:1;letter-spacing:.08em;text-transform:uppercase;color:var(--muted);margin:44px 0 0;padding-bottom:10px;border-bottom:1px solid var(--rule)}
|
|
35
|
+
.block,.msg{padding:18px 0;border-bottom:1px solid var(--rule)}
|
|
36
|
+
.children .block,.children .msg{border-bottom:0;padding:12px 0}
|
|
37
|
+
.meta,.who{font-size:13px;color:var(--muted)}
|
|
38
|
+
.who b{font-weight:600;letter-spacing:.04em;text-transform:uppercase;font-size:11.5px}
|
|
39
|
+
.msg.you .who b{color:var(--you)}.msg.talk .who b{color:var(--talk)}.msg.work .who b{color:var(--work)}.msg.tool .who b{color:var(--tool)}.msg.note .who b{color:var(--note)}
|
|
40
|
+
.summary{margin:6px 0 8px}
|
|
41
|
+
.pending{color:var(--muted);font-style:italic}
|
|
42
|
+
.text{margin-top:4px;white-space:pre-wrap;overflow-wrap:anywhere}
|
|
43
|
+
.clamp{display:-webkit-box;-webkit-line-clamp:7;-webkit-box-orient:vertical;overflow:hidden}
|
|
44
|
+
.children{margin:4px 0 0 2px;padding-left:20px;border-left:1px solid var(--rule)}
|
|
45
|
+
button.link{background:none;border:0;padding:0;font:inherit;font-size:14px;color:var(--accent);cursor:pointer}
|
|
46
|
+
button.link:hover{text-decoration:underline}
|
|
47
|
+
.target{background:var(--hl);box-shadow:-12px 0 0 var(--hl),12px 0 0 var(--hl)}
|
|
48
|
+
input[type=search]{width:100%;margin:24px 0 8px;padding:12px 16px;font:inherit;border:1px solid var(--rule);border-radius:10px;background:var(--paper);color:var(--ink);outline:none}
|
|
49
|
+
input[type=search]:focus{border-color:var(--bar)}
|
|
50
|
+
.count{font-size:14px;color:var(--muted);margin:0 0 8px}
|
|
51
|
+
mark{background:var(--hl);color:inherit;border-radius:2px;padding:0 1px}
|
|
52
|
+
.path{margin-top:10px;font-size:13px;color:var(--muted)}
|
|
53
|
+
.path .steps{display:flex;flex-wrap:wrap;align-items:center;gap:4px;margin-top:6px}
|
|
54
|
+
.path .steps button{font:inherit;font-size:12px;padding:2px 9px;border:1px solid var(--rule);border-radius:99px;background:var(--paper);color:var(--ink);cursor:pointer}
|
|
55
|
+
.path .steps button.on{border-color:var(--accent);color:var(--accent)}
|
|
56
|
+
.peek{margin:8px 0 0;padding:10px 14px;background:var(--paper);border:1px solid var(--rule);border-radius:8px;font-size:14px;color:var(--ink)}
|
|
57
|
+
.empty{color:var(--muted);margin-top:40px}
|
|
58
|
+
</style>
|
|
59
|
+
<div class="wrap">
|
|
60
|
+
<header><h1>Memory <small id="profile"></small></h1><p class="lede" id="lede"></p>
|
|
61
|
+
<p class="explain">Recent messages are kept one by one. Older ones are folded into summaries of 2, 4, 8 or more messages, so the whole history fits in what the model reads each turn. Open a summary to see the two halves it was made from, down to the original messages.</p>
|
|
62
|
+
<div class="shape" id="shape"></div><div class="axis"><span id="from"></span><span>Each bar is one block the model sees. Taller bars fold more messages.</span><span>now</span></div></header>
|
|
63
|
+
<nav><button id="tab-view" class="on">What the model sees</button><button id="tab-search">Search</button></nav>
|
|
64
|
+
<main id="view"></main>
|
|
65
|
+
<main id="search" hidden><input type="search" id="q" placeholder="Search every message" autocomplete="off"><p class="count" id="count"></p><div id="hits"></div></main>
|
|
66
|
+
</div>
|
|
67
|
+
<script type="application/json" id="data">__DATA__</script>
|
|
68
|
+
<script>
|
|
69
|
+
const D = JSON.parse(document.getElementById('data').textContent);
|
|
70
|
+
const nodes = new Map(D.tree.map(n => [n.l + ':' + n.i, n]));
|
|
71
|
+
const $ = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };
|
|
72
|
+
const first = p => p.i * 2 ** p.l, count = p => 2 ** p.l;
|
|
73
|
+
const year = new Date().getFullYear();
|
|
74
|
+
const day = d => d.toLocaleDateString(undefined, Object.assign({ weekday: 'short', day: 'numeric', month: 'short' }, d.getFullYear() !== year ? { year: 'numeric' } : {}));
|
|
75
|
+
const time = d => d.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' });
|
|
76
|
+
const times = D.root.map(e => new Date(e.date).getTime()), at = i => new Date(times[i]);
|
|
77
|
+
// Imported history is not always in date order, so a range shows its earliest and latest message.
|
|
78
|
+
function when(a, b) {
|
|
79
|
+
let lo = times[a], hi = times[a];
|
|
80
|
+
for (let k = a + 1; k <= b; k++) { lo = Math.min(lo, times[k]); hi = Math.max(hi, times[k]); }
|
|
81
|
+
const x = new Date(lo), y = new Date(hi);
|
|
82
|
+
if (lo === hi) return day(x) + ', ' + time(x);
|
|
83
|
+
return x.toDateString() === y.toDateString() ? day(x) + ', ' + time(x) + '–' + time(y) : day(x) + ' ' + time(x) + ' – ' + day(y) + ' ' + time(y);
|
|
84
|
+
}
|
|
85
|
+
const SOURCE = { claude: 'Claude Code', 'claude-memory': 'Claude Code memory', codex: 'Codex', chatgpt: 'ChatGPT' };
|
|
86
|
+
// Imported text starts with a "[Historical …]" line for the model; the meta line already says it.
|
|
87
|
+
const body = e => { const j = e.origin && e.text.startsWith('[Historical ') ? e.text.indexOf(']\n') : -1; return j < 0 ? e.text : e.text.slice(j + 2); };
|
|
88
|
+
const short = (s, n) => { s = s.replace(/\s+/g, ' ').trim(); return s.length > n ? s.slice(0, n - 1) + '…' : s; };
|
|
89
|
+
function who(e) {
|
|
90
|
+
if (e.kind === 'user') return /^\[[0-9a-f]{6,}\] /.test(e.text) ? ['Subagent', 'work', 'subagent report'] : ['You', 'you', 'from you'];
|
|
91
|
+
if (e.kind === 'talk') return ['OptChat', 'talk', 'reply'];
|
|
92
|
+
if (e.kind === 'tool') return ['Tool call', 'tool', 'tool step'];
|
|
93
|
+
if (e.kind === 'echo') return ['Tool result', 'tool', 'tool step'];
|
|
94
|
+
return ['Note', 'note', 'note'];
|
|
95
|
+
}
|
|
96
|
+
function mix(a, b) {
|
|
97
|
+
const c = new Map();
|
|
98
|
+
for (let k = a; k < b; k++) { const w = who(D.root[k])[2]; c.set(w, (c.get(w) || 0) + 1); }
|
|
99
|
+
return [...c].map(([w, n]) => n.toLocaleString() + ' ' + (n === 1 || w === 'from you' ? w : w === 'reply' ? 'replies' : w + 's')).join(', ');
|
|
100
|
+
}
|
|
101
|
+
function head(e) {
|
|
102
|
+
const [label] = who(e), h = $('div', 'who');
|
|
103
|
+
h.append($('b', null, label), ' · ' + when(e.i, e.i));
|
|
104
|
+
if (e.origin) h.append(' · imported from ' + SOURCE[e.origin.source] + (e.origin.title ? ': ' + short(e.origin.title, 60) : ''));
|
|
105
|
+
return h;
|
|
106
|
+
}
|
|
107
|
+
function message(e) {
|
|
108
|
+
const text = body(e), el = $('div', 'msg ' + who(e)[1]), t = $('div', 'text clamp', text);
|
|
109
|
+
el.dataset.k = '0:' + e.i; el.append(head(e), t);
|
|
110
|
+
if (text.length > 600 || text.split('\n').length > 7) {
|
|
111
|
+
const b = $('button', 'link', 'Show all');
|
|
112
|
+
b.onclick = () => { b.textContent = t.classList.toggle('clamp') ? 'Show all' : 'Show less'; };
|
|
113
|
+
el.append(b);
|
|
114
|
+
} else t.classList.remove('clamp');
|
|
115
|
+
return el;
|
|
116
|
+
}
|
|
117
|
+
// The model sees a large message as its shortened node, so the view shows that and keeps the original one click away.
|
|
118
|
+
function leaf(p) {
|
|
119
|
+
const e = D.root[p.i], n = nodes.get('0:' + p.i);
|
|
120
|
+
if (!n || n.text === e.text) return message(e);
|
|
121
|
+
const el = $('article', 'block'), kids = $('div', 'children'), b = $('button', 'link', 'Show the original');
|
|
122
|
+
el.dataset.k = '0:' + p.i; kids.hidden = true;
|
|
123
|
+
el.append($('div', 'meta', who(e)[0] + ' · ' + when(p.i, p.i) + ' · shortened for the model'), $('p', 'summary', n.text), b, kids);
|
|
124
|
+
b.onclick = () => { if (!kids.childElementCount) kids.append(message(e)); kids.hidden = !kids.hidden; b.textContent = kids.hidden ? 'Show the original' : 'Close'; };
|
|
125
|
+
return el;
|
|
126
|
+
}
|
|
127
|
+
function block(p) {
|
|
128
|
+
if (p.l === 0) return message(D.root[p.i]);
|
|
129
|
+
const a = first(p), n = nodes.get(p.l + ':' + p.i), el = $('article', 'block');
|
|
130
|
+
el.dataset.k = p.l + ':' + p.i;
|
|
131
|
+
el.append($('div', 'meta', when(a, a + count(p) - 1) + ' · ' + count(p).toLocaleString() + ' messages: ' + mix(a, a + count(p))));
|
|
132
|
+
el.append(n ? $('p', 'summary', n.text) : $('p', 'summary pending', 'Not summarized yet.'));
|
|
133
|
+
const b = $('button', 'link', 'Open the two halves'), kids = $('div', 'children');
|
|
134
|
+
kids.hidden = true; b.onclick = () => open(el); el.append(b, kids);
|
|
135
|
+
return el;
|
|
136
|
+
}
|
|
137
|
+
function open(el, force) {
|
|
138
|
+
const [l, i] = el.dataset.k.split(':').map(Number), kids = el.querySelector(':scope > .children'), b = el.querySelector(':scope > button.link');
|
|
139
|
+
if (!kids.childElementCount) kids.append(block({ l: l - 1, i: 2 * i }), block({ l: l - 1, i: 2 * i + 1 }));
|
|
140
|
+
kids.hidden = force === undefined ? !kids.hidden : !force;
|
|
141
|
+
b.textContent = kids.hidden ? 'Open the two halves' : 'Close';
|
|
142
|
+
return kids;
|
|
22
143
|
}
|
|
144
|
+
const view = document.getElementById('view'), search = document.getElementById('search');
|
|
145
|
+
function show(tab) {
|
|
146
|
+
view.hidden = tab !== 'view'; search.hidden = tab !== 'search';
|
|
147
|
+
document.getElementById('tab-view').classList.toggle('on', tab === 'view');
|
|
148
|
+
document.getElementById('tab-search').classList.toggle('on', tab === 'search');
|
|
149
|
+
if (tab === 'search') document.getElementById('q').focus();
|
|
150
|
+
}
|
|
151
|
+
document.getElementById('tab-view').onclick = () => show('view');
|
|
152
|
+
document.getElementById('tab-search').onclick = () => show('search');
|
|
153
|
+
function target(el) { document.querySelectorAll('.target').forEach(x => x.classList.remove('target')); el.classList.add('target'); el.scrollIntoView({ block: 'center' }); }
|
|
154
|
+
const holder = m => D.view.find(p => first(p) <= m && m < first(p) + count(p));
|
|
155
|
+
function reveal(m) {
|
|
156
|
+
show('view');
|
|
157
|
+
const p = holder(m); let el = view.querySelector('[data-k="' + p.l + ':' + p.i + '"]');
|
|
158
|
+
for (let k = p.l; k > 0; k--) el = open(el, true).querySelector(':scope > [data-k="' + (k - 1) + ':' + Math.floor(m / 2 ** (k - 1)) + '"]');
|
|
159
|
+
if (el.matches('article')) { const b = el.querySelector(':scope > button.link'); if (b.textContent !== 'Close') b.click(); el = el.querySelector('.children > .msg'); }
|
|
160
|
+
target(el);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
document.getElementById('profile').textContent = D.profile;
|
|
164
|
+
if (!D.root.length) { document.getElementById('lede').textContent = 'No messages yet.'; document.querySelector('.shape').remove(); document.querySelector('.axis').remove(); }
|
|
165
|
+
else {
|
|
166
|
+
const kb = n => Math.round(n / 1000).toLocaleString() + ' KB';
|
|
167
|
+
document.getElementById('lede').textContent = D.root.length.toLocaleString() + ' messages since ' + day(at(0)) + '. The model sees them as ' + D.view.length.toLocaleString() + ' blocks, using ' + kb(D.size) + ' of its ' + kb(D.budget) + ' memory view.';
|
|
168
|
+
document.getElementById('from').textContent = day(at(0));
|
|
169
|
+
const shape = document.getElementById('shape'), top = Math.max(1, ...D.view.map(p => p.l));
|
|
170
|
+
shape.classList.toggle('dense', D.view.length > 250);
|
|
171
|
+
for (const p of D.view) {
|
|
172
|
+
const s = $('button'), a = first(p);
|
|
173
|
+
s.style.height = (6 + 78 * p.l / top) + 'px';
|
|
174
|
+
s.title = when(a, a + count(p) - 1) + ' · ' + count(p).toLocaleString() + (count(p) === 1 ? ' message' : ' messages');
|
|
175
|
+
s.onclick = () => { show('view'); target(view.querySelector('[data-k="' + p.l + ':' + p.i + '"]')); };
|
|
176
|
+
s.setAttribute('aria-label', s.title);
|
|
177
|
+
shape.append(s);
|
|
178
|
+
}
|
|
179
|
+
let last = '';
|
|
180
|
+
for (const p of D.view) {
|
|
181
|
+
const d = at(first(p));
|
|
182
|
+
if (d.toDateString() !== last) { view.append($('h2', 'day', day(d))); last = d.toDateString(); }
|
|
183
|
+
view.append(p.l ? block(p) : leaf(p));
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
const q = document.getElementById('q'), hits = document.getElementById('hits'), counter = document.getElementById('count');
|
|
188
|
+
const lower = D.root.map(e => body(e).toLowerCase());
|
|
189
|
+
function snippet(text, j, len) {
|
|
190
|
+
const a = Math.max(0, j - 140), b = Math.min(text.length, j + len + 220), el = $('div', 'text');
|
|
191
|
+
el.append((a ? '…' : '') + text.slice(a, j), $('mark', null, text.slice(j, j + len)), text.slice(j + len, b) + (b < text.length ? '…' : ''));
|
|
192
|
+
return el;
|
|
193
|
+
}
|
|
194
|
+
function path(m) {
|
|
195
|
+
const p = holder(m), wrap = $('div', 'path'), steps = $('div', 'steps'), peek = $('div', 'peek');
|
|
196
|
+
wrap.append(p.l ? 'The model sees this inside a ' + count(p).toLocaleString() + '-message summary. Each step is one zoom:' : 'The model sees this message on its own.');
|
|
197
|
+
const go = $('button', 'link', 'Show in memory'); go.onclick = () => reveal(m);
|
|
198
|
+
if (!p.l) { wrap.append(' ', go); return wrap; }
|
|
199
|
+
peek.hidden = true; go.style.marginLeft = '8px';
|
|
200
|
+
for (let k = p.l; k >= 0; k--) {
|
|
201
|
+
const i = Math.floor(m / 2 ** k), b = $('button', null, k ? (2 ** k).toLocaleString() + ' messages' : 'this message');
|
|
202
|
+
b.onclick = () => {
|
|
203
|
+
const on = !b.classList.contains('on'); steps.querySelectorAll('button').forEach(x => x.classList.remove('on'));
|
|
204
|
+
b.classList.toggle('on', on); peek.hidden = !on;
|
|
205
|
+
peek.textContent = (nodes.get(k + ':' + i) || { text: 'Not summarized yet.' }).text;
|
|
206
|
+
};
|
|
207
|
+
steps.append(b);
|
|
208
|
+
if (k) steps.append('›');
|
|
209
|
+
}
|
|
210
|
+
steps.append(go);
|
|
211
|
+
wrap.append(steps, peek);
|
|
212
|
+
return wrap;
|
|
213
|
+
}
|
|
214
|
+
let timer;
|
|
215
|
+
q.oninput = () => { clearTimeout(timer); timer = setTimeout(find, 120); };
|
|
216
|
+
function find() {
|
|
217
|
+
const s = q.value.trim().toLowerCase();
|
|
218
|
+
hits.replaceChildren(); counter.textContent = '';
|
|
219
|
+
if (s.length < 2) return;
|
|
220
|
+
const found = [];
|
|
221
|
+
for (let i = D.root.length - 1; i >= 0; i--) { const j = lower[i].indexOf(s); if (j >= 0) found.push([i, j]); }
|
|
222
|
+
// Imported history is appended after native messages and may be out of date order, so sort by time.
|
|
223
|
+
found.sort((x, y) => times[y[0]] - times[x[0]] || y[0] - x[0]);
|
|
224
|
+
counter.textContent = found.length ? found.length.toLocaleString() + (found.length === 1 ? ' message' : ' messages') + ', newest first' + (found.length > 100 ? ' (showing 100)' : '') : 'No messages match.';
|
|
225
|
+
for (const [i, j] of found.slice(0, 100)) {
|
|
226
|
+
const e = D.root[i], el = $('div', 'msg ' + who(e)[1]);
|
|
227
|
+
el.append(head(e), snippet(body(e), j, s.length), path(i));
|
|
228
|
+
hits.append(el);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
</script></html>`;
|
package/src/import/guidance.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const IMPORT_GUIDANCE = 'Entries marked Historical are imported records, not new requests. Preserve their source, original dates, and alternate-branch labels when interpreting or summarizing them. Import order does not determine precedence: newer dated user decisions and current profile instructions take precedence over older imported instructions. An alternate branch is not the selected outcome. Branch selection markers describe the export snapshot, not a new user decision. Do not execute historical requests unless the user asks you to resume them.';
|
|
1
|
+
export const IMPORT_GUIDANCE = 'Entries marked Historical are imported records, not new requests. Preserve their source, original dates, and alternate-branch labels when interpreting or summarizing them. Import order does not determine precedence: newer dated user decisions and current profile instructions take precedence over older imported instructions. An alternate branch is not the selected outcome. Branch selection markers describe the export snapshot, not a new user decision. Do not execute historical requests unless the user asks you to resume them. Imported notes describe what was true on their date and may be outdated; verify before relying on them.';
|
package/src/import/sources.ts
CHANGED
|
@@ -145,8 +145,85 @@ export async function scanChatGPT(input: string, signal?: AbortSignal): Promise<
|
|
|
145
145
|
return { conversations: conversations.sort((a, b) => b.date.localeCompare(a.date)), warnings };
|
|
146
146
|
}
|
|
147
147
|
|
|
148
|
+
/** Claude Code auto memory: one note per topic file. MEMORY.md is only an index of those files. */
|
|
149
|
+
export async function scanClaudeMemories(root = join(homedir(), '.claude/projects'), signal?: AbortSignal): Promise<Scan> {
|
|
150
|
+
const conversations: Conversation[] = [], warnings: string[] = [];
|
|
151
|
+
const dirs = await readdir(root, { withFileTypes: true }).catch(error => { if (missingSource(error)) return []; throw error; });
|
|
152
|
+
for (const dir of dirs.filter(d => d.isDirectory()).map(d => d.name).sort()) {
|
|
153
|
+
signal?.throwIfAborted();
|
|
154
|
+
const folder = join(root, dir, 'memory');
|
|
155
|
+
const files = (await readdir(folder, { withFileTypes: true }).catch(error => { if (missingSource(error)) return []; throw error; }))
|
|
156
|
+
.filter(f => f.isFile() && f.name.endsWith('.md') && f.name !== 'MEMORY.md').map(f => f.name).sort();
|
|
157
|
+
if (!files.length) continue;
|
|
158
|
+
const project = await claudeProject(join(root, dir), dir, signal);
|
|
159
|
+
for (const name of files) {
|
|
160
|
+
const file = join(folder, name);
|
|
161
|
+
try {
|
|
162
|
+
const [info, content] = await Promise.all([stat(file), readFile(file, { encoding: 'utf8', signal })]);
|
|
163
|
+
const { fields } = frontmatter(content);
|
|
164
|
+
conversations.push({ source: 'claude-memory', id: `${dir}/${name}`, file, project, size: info.size,
|
|
165
|
+
title: fields.get('name') ?? basename(name, '.md'), date: timestamp(fields.get('modified'), info.mtime.toISOString()) });
|
|
166
|
+
} catch (error) {
|
|
167
|
+
signal?.throwIfAborted();
|
|
168
|
+
if (!missingSource(error)) throw error;
|
|
169
|
+
warnings.push(`${file}: memory file is no longer available; skipped.`);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
return { conversations: conversations.sort((a, b) => b.date.localeCompare(a.date)), warnings };
|
|
174
|
+
}
|
|
175
|
+
/** Claude names project folders after the launch directory with every other character replaced by '-'. Recover it from a transcript. */
|
|
176
|
+
async function claudeProject(folder: string, name: string, signal?: AbortSignal): Promise<string> {
|
|
177
|
+
const transcripts = (await readdir(folder)).filter(f => f.endsWith('.jsonl')).sort();
|
|
178
|
+
for (const transcript of transcripts) {
|
|
179
|
+
try {
|
|
180
|
+
for await (const { value } of jsonLines(join(folder, transcript), [], 60, signal)) {
|
|
181
|
+
const cwd = string(value.cwd);
|
|
182
|
+
if (cwd && cwd.replace(/[^a-zA-Z0-9]/g, '-') === name) return cwd;
|
|
183
|
+
}
|
|
184
|
+
} catch (error) { signal?.throwIfAborted(); if (!missingSource(error)) throw error; }
|
|
185
|
+
}
|
|
186
|
+
return name; // Transcripts can be cleaned up while memory remains.
|
|
187
|
+
}
|
|
188
|
+
function frontmatter(content: string) {
|
|
189
|
+
const match = /^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(content);
|
|
190
|
+
const fields = new Map<string, string>();
|
|
191
|
+
for (const line of match ? match[1].split(/\r?\n/) : []) {
|
|
192
|
+
// Newer files nest type/modified under `metadata:`; the first occurrence of each key wins.
|
|
193
|
+
const m = /^\s*([A-Za-z]+):\s*(.+?)\s*$/.exec(line);
|
|
194
|
+
if (m && !fields.has(m[1])) fields.set(m[1], unquote(m[2]));
|
|
195
|
+
}
|
|
196
|
+
return { fields, body: match ? content.slice(match[0].length) : content };
|
|
197
|
+
}
|
|
198
|
+
function unquote(value: string): string {
|
|
199
|
+
if (value.startsWith('"')) { try { const parsed: unknown = JSON.parse(value); if (typeof parsed === 'string') return parsed; } catch { /* plain text */ } }
|
|
200
|
+
if (/^'.*'$/.test(value)) return value.slice(1, -1).replaceAll("''", "'");
|
|
201
|
+
return value;
|
|
202
|
+
}
|
|
203
|
+
async function readMemory(c: Conversation, signal?: AbortSignal): Promise<{ entries: ImportedEntry[]; warnings: string[] }> {
|
|
204
|
+
let content: string, modified: Date;
|
|
205
|
+
try { [content, { mtime: modified }] = await Promise.all([readFile(c.file, { encoding: 'utf8', signal }), stat(c.file)]); } catch (error) {
|
|
206
|
+
signal?.throwIfAborted();
|
|
207
|
+
if (!missingSource(error)) throw error;
|
|
208
|
+
return { entries: [], warnings: [`${c.file}: memory file is no longer available; skipped.`] };
|
|
209
|
+
}
|
|
210
|
+
const { fields, body } = frontmatter(content);
|
|
211
|
+
if (!body.trim()) return { entries: [], warnings: [] };
|
|
212
|
+
const one = (s: string) => s.replace(/\s+/g, ' ').trim();
|
|
213
|
+
const name = one(fields.get('name') ?? c.title), type = fields.get('type'), description = fields.get('description');
|
|
214
|
+
// The whole file is the identity, so an edited memory arrives as a newer note and an unchanged one is skipped.
|
|
215
|
+
const hash = digest(content);
|
|
216
|
+
// Date the note from this read, not the earlier scan, in case Claude edited the file meanwhile.
|
|
217
|
+
const date = timestamp(fields.get('modified'), modified.toISOString());
|
|
218
|
+
return { warnings: [], entries: [{ kind: 'note', date,
|
|
219
|
+
origin: { source: c.source, conversation: c.id, message: hash.slice(0, 16), title: name, project: c.project },
|
|
220
|
+
text: `[Historical Claude Code memory · ${date} · project ${c.project}${type ? ` · type ${one(type)}` : ''} · ${name}]\n${description ? one(description) + '\n\n' : ''}${body.trim()}`,
|
|
221
|
+
receipt: `import:${digest(JSON.stringify([c.source, c.id, hash]))}` }] };
|
|
222
|
+
}
|
|
223
|
+
|
|
148
224
|
export async function readConversation(c: Conversation, signal?: AbortSignal): Promise<{ entries: ImportedEntry[]; warnings: string[] }> {
|
|
149
225
|
signal?.throwIfAborted();
|
|
226
|
+
if (c.source === 'claude-memory') return readMemory(c, signal);
|
|
150
227
|
const entries: ImportedEntry[] = [], warnings: string[] = [];
|
|
151
228
|
const add = (id: string, kind: Kind, value: string, date: string, identity = value) => { const entry = imported(c, id, kind, value, date, identity); if (entry) entries.push(entry); };
|
|
152
229
|
if (c.source === 'chatgpt') {
|
package/src/import/ui.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { ExtensionUIContext } from '@earendil-works/pi-coding-agent';
|
|
2
2
|
import type { Memory } from '../memory.ts';
|
|
3
3
|
import { bytes } from '../memory.ts';
|
|
4
|
-
import { scanLocal, scanChatGPT, readConversation, type Conversation, type ImportedEntry, type Source } from './sources.ts';
|
|
4
|
+
import { scanLocal, scanChatGPT, scanClaudeMemories, readConversation, type Conversation, type ImportedEntry, type Source } from './sources.ts';
|
|
5
5
|
import { deduplicate, type ImportMode, type ImportJob, type ImportProgress } from './job.ts';
|
|
6
6
|
import { selectMany } from './multi-select.ts';
|
|
7
7
|
import { homedir } from 'node:os';
|
|
@@ -10,9 +10,10 @@ type ImportUI = { ui: Pick<ExtensionUIContext, 'select' | 'input' | 'confirm' |
|
|
|
10
10
|
const clean = (s: string) => s.replace(/[\x00-\x1f\x7f-\x9f]/g, ' ');
|
|
11
11
|
const size = (n: number) => `${(n / 1_000_000).toFixed(1)} MB`;
|
|
12
12
|
export async function chooseImport(ctx: ImportUI, profile: string, memory: Memory, model: string, signal: AbortSignal): Promise<{ entries: ImportedEntry[]; mode: ImportMode } | undefined> {
|
|
13
|
-
const sourceLabel = await ctx.ui.select(`Import into ${profile} · source`, ['Claude Code', 'Codex', 'ChatGPT export'], { signal });
|
|
13
|
+
const sourceLabel = await ctx.ui.select(`Import into ${profile} · source`, ['Claude Code', 'Claude Code memories', 'Codex', 'ChatGPT export'], { signal });
|
|
14
14
|
if (!sourceLabel) return;
|
|
15
|
-
const source: Source = sourceLabel === 'Claude Code' ? 'claude' : sourceLabel === 'Codex' ? 'codex' : 'chatgpt';
|
|
15
|
+
const source: Source = sourceLabel === 'Claude Code' ? 'claude' : sourceLabel === 'Claude Code memories' ? 'claude-memory' : sourceLabel === 'Codex' ? 'codex' : 'chatgpt';
|
|
16
|
+
const unit = source === 'claude-memory' ? 'memories' : 'conversations';
|
|
16
17
|
ctx.ui.setWidget('optchat-import', ['Scanning local conversation metadata…']);
|
|
17
18
|
let scan;
|
|
18
19
|
try {
|
|
@@ -20,19 +21,19 @@ export async function chooseImport(ctx: ImportUI, profile: string, memory: Memor
|
|
|
20
21
|
const path = await ctx.ui.input('ChatGPT export ZIP, extracted folder, or conversations JSON path', undefined, { signal });
|
|
21
22
|
if (!path?.trim()) return;
|
|
22
23
|
scan = await scanChatGPT(path.trim(), signal);
|
|
23
|
-
} else scan = await scanLocal(source, undefined, signal);
|
|
24
|
+
} else scan = source === 'claude-memory' ? await scanClaudeMemories(undefined, signal) : await scanLocal(source, undefined, signal);
|
|
24
25
|
} finally { ctx.ui.setWidget('optchat-import', undefined); }
|
|
25
26
|
let candidates = scan.conversations;
|
|
26
|
-
if (!candidates.length) throw new Error(`No
|
|
27
|
+
if (!candidates.length) throw new Error(`No ${unit} found for this source.${scan.warnings.length ? '\n' + scan.warnings.slice(0, 4).map(clean).join('\n') : ''}`);
|
|
27
28
|
if (source !== 'chatgpt') {
|
|
28
29
|
const counts = new Map<string, number>();
|
|
29
30
|
for (const c of candidates) counts.set(c.project, (counts.get(c.project) ?? 0) + 1);
|
|
30
31
|
const projects = [...counts].sort(([a, x], [b, y]) => y - x || a.localeCompare(b)).map(([p]) => p);
|
|
31
|
-
const selected = await selectMany(ctx.ui, 'Projects', projects, p => `${p.startsWith(homedir() + '/') ? '~' + p.slice(homedir().length) : p} (${counts.get(p)}
|
|
32
|
+
const selected = await selectMany(ctx.ui, 'Projects', projects, p => `${p.startsWith(homedir() + '/') ? '~' + p.slice(homedir().length) : p} (${counts.get(p)} ${unit})`, signal);
|
|
32
33
|
if (!selected) return;
|
|
33
34
|
candidates = candidates.filter(c => selected.includes(c.project));
|
|
34
35
|
}
|
|
35
|
-
const range = await ctx.ui.select('Conversation dates', ['All history', 'Filter by start date'], { signal });
|
|
36
|
+
const range = await ctx.ui.select(source === 'claude-memory' ? 'Memory dates' : 'Conversation dates', ['All history', 'Filter by start date'], { signal });
|
|
36
37
|
if (!range) return;
|
|
37
38
|
if (range === 'Filter by start date') {
|
|
38
39
|
const after = await ctx.ui.input('Started on/after YYYY-MM-DD (blank = no lower bound)', undefined, { signal }); if (after === undefined) return;
|
|
@@ -41,11 +42,11 @@ export async function chooseImport(ctx: ImportUI, profile: string, memory: Memor
|
|
|
41
42
|
if (after && before && after > before) throw new Error('Start date must precede end date.');
|
|
42
43
|
candidates = candidates.filter(c => (!after || c.date.slice(0, 10) >= after) && (!before || c.date.slice(0, 10) <= before));
|
|
43
44
|
}
|
|
44
|
-
if (!candidates.length) throw new Error(
|
|
45
|
-
const scope = await ctx.ui.select(`${candidates.length}
|
|
45
|
+
if (!candidates.length) throw new Error(`No ${unit} match these dates.`);
|
|
46
|
+
const scope = await ctx.ui.select(`${candidates.length} ${unit} · ${size(candidates.reduce((n, c) => n + c.size, 0))} source files`, [`All matching ${unit}`, `Choose individual ${unit}`], { signal });
|
|
46
47
|
if (!scope) return;
|
|
47
|
-
const conversations: Conversation[] | undefined = scope ===
|
|
48
|
-
? await selectMany(ctx.ui, 'Conversations', candidates, c => `${c.date.slice(0, 10)} · ${c.title} · ${c.id}`, signal) : candidates;
|
|
48
|
+
const conversations: Conversation[] | undefined = scope === `Choose individual ${unit}`
|
|
49
|
+
? await selectMany(ctx.ui, source === 'claude-memory' ? 'Memories' : 'Conversations', candidates, c => `${c.date.slice(0, 10)} · ${c.title} · ${c.id}`, signal) : candidates;
|
|
49
50
|
if (!conversations) return;
|
|
50
51
|
const entries: ImportedEntry[] = [], warnings = [...scan.warnings];
|
|
51
52
|
try {
|
|
@@ -77,7 +78,7 @@ export async function chooseImport(ctx: ImportUI, profile: string, memory: Memor
|
|
|
77
78
|
let nodes = 0;
|
|
78
79
|
for (let n = memory.root.length + added.length; n > 0; n = Math.floor(n / 2)) nodes += n;
|
|
79
80
|
if (mode === 'append') nodes -= memory.tree.size;
|
|
80
|
-
const preview = `${profile} · ${mode}\
|
|
81
|
+
const preview = `${profile} · ${mode}\n${source === 'claude-memory' ? 'Each memory file as one dated historical note; MEMORY.md indexes excluded.' : 'Historical user messages and final replies; tool activity excluded.'}\n${conversations.length} ${unit} selected · ${added.length} new ${source === 'claude-memory' ? 'notes' : 'messages'} · ${skipped} duplicates skipped\n${size(inputBytes)} text to index (~${Math.ceil(inputBytes / 4).toLocaleString()} source tokens; rough estimate)\nCompactor: ${model}\nUp to ${nodes} new summary nodes; small nodes need no model call. Context and retries add usage.\nChatting in this profile pauses until completion or discard. You can pause and resume compression. The previous memory is retained.`;
|
|
81
82
|
if (!await ctx.ui.confirm('Start import?', preview, { signal })) return;
|
|
82
83
|
return { entries, mode };
|
|
83
84
|
}
|
package/src/index.ts
CHANGED
|
@@ -22,6 +22,7 @@ import { chooseImport, showProgress } from './import/ui.ts';
|
|
|
22
22
|
import { IMPORT_GUIDANCE } from './import/guidance.ts';
|
|
23
23
|
import { UsageLedger } from './usage.ts';
|
|
24
24
|
import { showInspector, type InspectorPage } from './inspector.ts';
|
|
25
|
+
import { showAgentView } from './agent-view.ts';
|
|
25
26
|
import { inspectorShortcut, mountNavigation } from './navigation.ts';
|
|
26
27
|
import { serveWindows } from './window-bridge.ts';
|
|
27
28
|
import { openConnectedWindow, registerConnectedRenderer } from './connected-window.ts';
|
|
@@ -305,7 +306,9 @@ export default function optchat(pi: ExtensionAPI) {
|
|
|
305
306
|
const action = await showInspector(ctx, { profile: a.name, session: ctx.sessionManager.getSessionId(), children: a.children, usage: a.usage, page, signal,
|
|
306
307
|
refreshUsage: () => { collectUsage(ctx); try { a.children.collectUsage(); } catch (error) { ctx.ui.notify(`Could not save child usage: ${errorText(error)}`, 'error'); } },
|
|
307
308
|
});
|
|
308
|
-
if (
|
|
309
|
+
if (signal.aborted) return;
|
|
310
|
+
if (action === 'model') await pickModel(ctx, 'subagent');
|
|
311
|
+
else if (action) await showAgentView(ctx, { id: action.open, children: a.children, signal });
|
|
309
312
|
} catch (error) { ctx.ui.notify(errorText(error), 'error'); }
|
|
310
313
|
finally { if (inspectorController === controller) inspectorController = undefined; }
|
|
311
314
|
};
|
package/src/inspector.ts
CHANGED
|
@@ -1,11 +1,8 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { matchesKey, sliceByColumn, truncateToWidth, visibleWidth, wrapTextWithAnsi, type Component, type Focusable } from '@earendil-works/pi-tui';
|
|
2
2
|
import type { ExtensionContext } from '@earendil-works/pi-coding-agent';
|
|
3
|
-
import type { AgentMessage } from '@earendil-works/pi-agent-core';
|
|
4
3
|
import type { Children } from './agents.ts';
|
|
5
|
-
import { isActiveRun
|
|
4
|
+
import { isActiveRun } from './runs.ts';
|
|
6
5
|
import { ranges, summarizeUsage, type UsageLedger, type UsageRange } from './usage.ts';
|
|
7
|
-
import { textContent } from './transcript.ts';
|
|
8
|
-
import { record } from './cache.ts';
|
|
9
6
|
|
|
10
7
|
export const clean = (text: string) => text.replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, '').replace(/\t/g, ' ');
|
|
11
8
|
export const oneLine = (text: string) => clean(text).replace(/\n/g, ' ');
|
|
@@ -24,10 +21,12 @@ const spread = (left: string, right: string, width: number) => {
|
|
|
24
21
|
return gap >= 2 ? `${left}${' '.repeat(gap)}${right}` : left;
|
|
25
22
|
};
|
|
26
23
|
export type InspectorPage = 'agents' | 'usage';
|
|
24
|
+
/** Closing the panel either picks the subagent model or opens one agent's conversation. */
|
|
25
|
+
export type InspectorAction = 'model' | { open: string };
|
|
27
26
|
type Tone = 'accent' | 'muted' | 'dim' | 'error' | 'border';
|
|
28
27
|
interface Options {
|
|
29
28
|
profile: string; session: string; children: Children; usage: UsageLedger; page: InspectorPage;
|
|
30
|
-
rows: () => number; redraw: () => void; done: (action?:
|
|
29
|
+
rows: () => number; redraw: () => void; done: (action?: InspectorAction) => void;
|
|
31
30
|
color: (tone: Tone, text: string) => string;
|
|
32
31
|
context: () => number | null | undefined;
|
|
33
32
|
refreshUsage?: () => void;
|
|
@@ -39,20 +38,12 @@ export class Inspector implements Component, Focusable {
|
|
|
39
38
|
focused = true;
|
|
40
39
|
private page: InspectorPage;
|
|
41
40
|
private selected?: string;
|
|
42
|
-
private opened?: string;
|
|
43
41
|
private top = 0;
|
|
44
42
|
private scroll = 0;
|
|
45
43
|
private lineCount = 0;
|
|
46
44
|
private hintLines = 1;
|
|
47
|
-
private follow = true;
|
|
48
|
-
private details = false;
|
|
49
45
|
private range: UsageRange = 'This session';
|
|
50
|
-
private composer?: Input;
|
|
51
|
-
private error = '';
|
|
52
|
-
private busy = false;
|
|
53
46
|
private ended = false;
|
|
54
|
-
private savedMessages?: AgentMessage[];
|
|
55
|
-
private liveTranscript = false;
|
|
56
47
|
private readonly unsubscribe: () => void;
|
|
57
48
|
private readonly timer: ReturnType<typeof setInterval>;
|
|
58
49
|
constructor(private readonly options: Options) {
|
|
@@ -64,50 +55,28 @@ export class Inspector implements Component, Focusable {
|
|
|
64
55
|
if (options.signal?.aborted) queueMicrotask(this.abort);
|
|
65
56
|
}
|
|
66
57
|
private readonly abort = () => this.finish();
|
|
67
|
-
private finish(action?:
|
|
58
|
+
private finish(action?: InspectorAction) { if (!this.ended) { this.dispose(); this.options.done(action); } }
|
|
68
59
|
dispose() {
|
|
69
60
|
this.ended = true; clearInterval(this.timer); this.unsubscribe(); this.options.signal?.removeEventListener('abort', this.abort);
|
|
70
61
|
}
|
|
71
|
-
invalidate() {
|
|
72
|
-
/** Body rows left after the rules, title, hint
|
|
73
|
-
private get height() { return Math.max(1, Math.floor(this.options.rows() * 0.8) -
|
|
62
|
+
invalidate() {}
|
|
63
|
+
/** Body rows left after the rules, title, hint and spacing; the rest of the screen keeps the footer visible. */
|
|
64
|
+
private get height() { return Math.max(1, Math.floor(this.options.rows() * 0.8) - 6 - (this.hintLines - 1)); }
|
|
74
65
|
private select(delta: number) {
|
|
75
66
|
const list = this.options.children.history.list();
|
|
76
67
|
const index = Math.max(0, list.findIndex(r => r.id === this.selected));
|
|
77
68
|
this.selected = list[Math.max(0, Math.min(list.length - 1, index + delta))]?.id;
|
|
78
69
|
}
|
|
79
|
-
private async act(action: () => Promise<unknown>) {
|
|
80
|
-
this.busy = true;
|
|
81
|
-
try { await action(); } catch (error) { this.error = String(error); }
|
|
82
|
-
finally { this.busy = false; if (!this.ended) this.options.redraw(); }
|
|
83
|
-
}
|
|
84
70
|
handleInput(data: string) {
|
|
85
71
|
if (this.ended) return;
|
|
86
|
-
|
|
87
|
-
if (
|
|
88
|
-
|
|
89
|
-
else if (matchesKey(data, 'return') && !this.busy) {
|
|
90
|
-
const text = this.composer.getValue().trim(), id = this.opened;
|
|
91
|
-
if (text && id) { this.composer = undefined; void this.act(() => this.options.children.tell(id, text, 'user')); }
|
|
92
|
-
} else this.composer.handleInput(data);
|
|
93
|
-
} else if (matchesKey(data, 'escape') || matchesKey(data, 'ctrl+c')) {
|
|
94
|
-
if (this.opened) { this.opened = undefined; this.savedMessages = undefined; this.scroll = 0; }
|
|
95
|
-
else return this.finish();
|
|
96
|
-
} else if (data === 'u' || matchesKey(data, 'tab')) {
|
|
97
|
-
this.page = this.page === 'agents' ? 'usage' : 'agents'; this.opened = undefined; this.scroll = 0; this.follow = true;
|
|
72
|
+
if (matchesKey(data, 'escape') || matchesKey(data, 'ctrl+c')) return this.finish();
|
|
73
|
+
if (data === 'u' || matchesKey(data, 'tab')) {
|
|
74
|
+
this.page = this.page === 'agents' ? 'usage' : 'agents'; this.scroll = 0;
|
|
98
75
|
} else if (this.page === 'usage') {
|
|
99
76
|
if (matchesKey(data, 'left') || matchesKey(data, 'right')) {
|
|
100
77
|
const delta = matchesKey(data, 'left') ? -1 : 1;
|
|
101
78
|
this.range = ranges[(ranges.indexOf(this.range) + delta + ranges.length) % ranges.length]; this.scroll = 0;
|
|
102
79
|
} else this.scrollInput(data);
|
|
103
|
-
} else if (this.opened) {
|
|
104
|
-
if (data === 's' && !this.busy && ['running', 'waiting'].includes(this.options.children.live(this.opened)?.info.state ?? '')) {
|
|
105
|
-
this.composer = new Input({ prompt: 'Message: ', placeholder: 'guidance for this child' }); this.composer.focused = this.focused;
|
|
106
|
-
} else if (data === 'x' && !this.busy && this.options.children.live(this.opened)) {
|
|
107
|
-
const id = this.opened; void this.act(() => this.options.children.stop(id));
|
|
108
|
-
} else if (data === 't') this.details = !this.details;
|
|
109
|
-
else if (data === 'f' || matchesKey(data, 'end')) { this.follow = true; this.scroll = Math.max(0, this.lineCount - this.height); }
|
|
110
|
-
else this.scrollInput(data);
|
|
111
80
|
} else {
|
|
112
81
|
if (matchesKey(data, 'up')) this.select(-1);
|
|
113
82
|
else if (matchesKey(data, 'down')) this.select(1);
|
|
@@ -116,62 +85,17 @@ export class Inspector implements Component, Focusable {
|
|
|
116
85
|
else if (matchesKey(data, 'home')) this.select(-Infinity);
|
|
117
86
|
else if (matchesKey(data, 'end')) this.select(Infinity);
|
|
118
87
|
else if (data === 'm') return this.finish('model');
|
|
119
|
-
else if (matchesKey(data, 'return') && this.selected) {
|
|
120
|
-
try {
|
|
121
|
-
this.savedMessages = this.options.children.messages(this.selected); this.opened = this.selected;
|
|
122
|
-
this.liveTranscript = !!this.options.children.live(this.selected);
|
|
123
|
-
this.follow = true; this.scroll = 0;
|
|
124
|
-
} catch (error) { this.error = `Transcript unavailable: ${String(error)}`; }
|
|
125
|
-
}
|
|
88
|
+
else if (matchesKey(data, 'return') && this.selected) return this.finish({ open: this.selected });
|
|
126
89
|
}
|
|
127
90
|
this.options.redraw();
|
|
128
91
|
}
|
|
129
92
|
private scrollInput(data: string) {
|
|
130
93
|
const delta = matchesKey(data, 'up') ? -1 : matchesKey(data, 'down') ? 1 : matchesKey(data, 'pageUp') ? -this.height : matchesKey(data, 'pageDown') ? this.height : 0;
|
|
131
94
|
if (delta || matchesKey(data, 'home') || matchesKey(data, 'end')) {
|
|
132
|
-
this.follow = false;
|
|
133
95
|
this.scroll = matchesKey(data, 'home') ? 0 : matchesKey(data, 'end') ? this.lineCount : this.scroll + delta;
|
|
134
96
|
this.scroll = Math.max(0, Math.min(this.scroll, this.lineCount - this.height));
|
|
135
97
|
}
|
|
136
98
|
}
|
|
137
|
-
private transcript(run: RunInfo) {
|
|
138
|
-
const live = this.options.children.live(run.id);
|
|
139
|
-
if (live || this.liveTranscript) {
|
|
140
|
-
try { this.savedMessages = this.options.children.messages(run.id); }
|
|
141
|
-
catch (error) { this.error = `Transcript unavailable: ${String(error)}`; }
|
|
142
|
-
this.liveTranscript = !!live;
|
|
143
|
-
}
|
|
144
|
-
const messages = this.savedMessages ?? [];
|
|
145
|
-
const usage = summarizeUsage(this.options.usage.entries.filter(e => e.runId === run.id)).total;
|
|
146
|
-
const blocks = [`Task: ${run.task}`, `Directory: ${run.cwd}`, `Model: ${run.model} · effort ${run.thinking}`, `Depth: ${run.depth}/3 · parent: ${run.parentId ?? 'main agent'}`,
|
|
147
|
-
`Usage: ${count(usage.totalTokens)} tokens · ${count(usage.input)} input · ${count(usage.output)} output · ${count(usage.cacheRead)}/${count(usage.cacheWrite)} cache read/write · $${usage.cost.total.toFixed(4)} API-equivalent`];
|
|
148
|
-
let initialUser = true;
|
|
149
|
-
for (const message of messages) {
|
|
150
|
-
if (message.role === 'user') {
|
|
151
|
-
if (initialUser) { initialUser = false; continue; } // The initial memory view is context, not work output.
|
|
152
|
-
blocks.push(`You / manager: ${textContent(message.content)}`);
|
|
153
|
-
} else if (message.role === 'assistant') {
|
|
154
|
-
for (const part of message.content) {
|
|
155
|
-
if (part.type === 'text') blocks.push(part.text);
|
|
156
|
-
else if (part.type === 'toolCall') blocks.push(`Tool: ${part.name}${this.details ? `\n${JSON.stringify(part.arguments, null, 2)}` : ''}`);
|
|
157
|
-
}
|
|
158
|
-
if (message.errorMessage) blocks.push(`Error: ${message.errorMessage}`);
|
|
159
|
-
} else if (message.role === 'toolResult') {
|
|
160
|
-
const output = textContent(message.content);
|
|
161
|
-
blocks.push(`${message.isError ? 'Error' : 'Result'}: ${message.toolName}\n${this.details ? output : `${oneLine(output).slice(0, 160)}${output.length > 160 ? '… [t expands]' : ''}`}`);
|
|
162
|
-
}
|
|
163
|
-
}
|
|
164
|
-
for (const tool of live?.tools.values() ?? []) {
|
|
165
|
-
blocks.push(`Running: ${tool.name} · ${elapsed(Date.now() - tool.started)}\n${JSON.stringify(tool.args)}`);
|
|
166
|
-
if (tool.output) {
|
|
167
|
-
const output = record(tool.output) ? textContent(tool.output.content) : String(tool.output);
|
|
168
|
-
blocks.push(this.details ? output : output.slice(-500));
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
if (run.report && !live) blocks.push(`Final report: ${run.report}`);
|
|
172
|
-
for (const g of run.guidance) if (g.state !== 'delivered') blocks.push(`Message ${g.state}: ${g.text}`);
|
|
173
|
-
return blocks.filter(Boolean).map(clean).join('\n\n');
|
|
174
|
-
}
|
|
175
99
|
private usageLines() {
|
|
176
100
|
const { usage, session, context } = this.options;
|
|
177
101
|
const entries = usage.select(this.range, session);
|
|
@@ -194,18 +118,14 @@ export class Inspector implements Component, Focusable {
|
|
|
194
118
|
render(width: number): string[] {
|
|
195
119
|
const { color, children, profile } = this.options;
|
|
196
120
|
const inner = Math.max(1, width - 2);
|
|
197
|
-
|
|
198
|
-
let title = `OptChat · ${profile} · ${inspected ? `${inspected.state}: ${oneLine(inspected.task)}` : this.page === 'usage' ? 'Usage' : 'Agents'}`;
|
|
121
|
+
let title = `OptChat · ${profile} · ${this.page === 'usage' ? 'Usage' : 'Agents'}`;
|
|
199
122
|
let info: string, body: string[], hint: string;
|
|
200
|
-
if (this.page === 'usage'
|
|
201
|
-
const
|
|
202
|
-
const text = this.page === 'usage' ? this.usageLines() : run ? `${run.state} · ${elapsed((run.ended ?? Date.now()) - run.started)} · ${run.id}\n\n${this.transcript(run)}` : 'Run unavailable.';
|
|
203
|
-
const lines = wrapTextWithAnsi(clean(text), inner); this.lineCount = lines.length;
|
|
204
|
-
if (this.opened && this.follow) this.scroll = Math.max(0, lines.length - this.height);
|
|
123
|
+
if (this.page === 'usage') {
|
|
124
|
+
const lines = wrapTextWithAnsi(clean(this.usageLines()), inner); this.lineCount = lines.length;
|
|
205
125
|
this.scroll = Math.max(0, Math.min(this.scroll, lines.length - this.height));
|
|
206
126
|
body = lines.slice(this.scroll, this.scroll + this.height);
|
|
207
|
-
info = `${this.scroll + 1}–${Math.min(this.scroll + this.height, lines.length)} / ${lines.length}
|
|
208
|
-
hint =
|
|
127
|
+
info = `${this.scroll + 1}–${Math.min(this.scroll + this.height, lines.length)} / ${lines.length}`;
|
|
128
|
+
hint = '←→ period · ↑↓/PgUp/PgDn scroll · Tab agents · Esc close';
|
|
209
129
|
} else {
|
|
210
130
|
const list = children.history.list();
|
|
211
131
|
if (!this.selected) this.selected = list[0]?.id;
|
|
@@ -231,11 +151,10 @@ export class Inspector implements Component, Focusable {
|
|
|
231
151
|
});
|
|
232
152
|
if (!body.length) body.push(color('muted', 'No agents yet. Ask the main agent to delegate a task.'));
|
|
233
153
|
info = `${list.filter(isActiveRun).length} active · ${list.length} saved${list.length ? ` · ${cursor + 1}/${list.length}` : ''}`;
|
|
234
|
-
hint = '↑↓ select · Enter
|
|
154
|
+
hint = '↑↓ select · Enter open · m model · Tab usage · Esc close';
|
|
235
155
|
}
|
|
236
|
-
if (this.composer) { this.composer.focused = this.focused; body.push(...this.composer.render(inner)); hint = 'Enter sends guidance · Esc cancels message'; }
|
|
237
156
|
title = fit(title, Math.max(1, inner - visibleWidth(info) - 2));
|
|
238
|
-
const footer = wrapTextWithAnsi(
|
|
157
|
+
const footer = wrapTextWithAnsi(hint, inner).map(line => color('dim', line));
|
|
239
158
|
this.hintLines = footer.length;
|
|
240
159
|
const rule = color('border', '─'.repeat(Math.max(1, width)));
|
|
241
160
|
// Same layout as Pi's own selectors: rules above and below, content indented by one column.
|
|
@@ -249,7 +168,7 @@ let showing = false;
|
|
|
249
168
|
export const inspectorShowing = () => showing;
|
|
250
169
|
/** Takes the editor's place, like Pi's own selectors; Pi restores the editor and its draft on close. */
|
|
251
170
|
export function showInspector(ctx: ExtensionContext, options: Omit<Options, 'rows' | 'redraw' | 'done' | 'color' | 'context'>) {
|
|
252
|
-
return ctx.ui.custom<
|
|
171
|
+
return ctx.ui.custom<InspectorAction | undefined>((tui, theme, _keys, done) => {
|
|
253
172
|
showing = true;
|
|
254
173
|
return new Inspector({ ...options,
|
|
255
174
|
rows: () => tui.terminal.rows, redraw: () => tui.requestRender(), done: action => { showing = false; done(action); },
|
package/src/memory.ts
CHANGED
|
@@ -6,7 +6,7 @@ export const NODE = 512;
|
|
|
6
6
|
export const VIEW = 128_000;
|
|
7
7
|
export const CAP = 30_000;
|
|
8
8
|
export type Kind = 'user' | 'talk' | 'tool' | 'echo' | 'note';
|
|
9
|
-
export interface Origin { source: 'claude' | 'codex' | 'chatgpt'; conversation: string; message: string; title: string; project?: string }
|
|
9
|
+
export interface Origin { source: 'claude' | 'claude-memory' | 'codex' | 'chatgpt'; conversation: string; message: string; title: string; project?: string }
|
|
10
10
|
export interface Entry { i: number; kind: Kind; text: string; size: number; date: string; receipt?: string; origin?: Origin }
|
|
11
11
|
export interface Part { l: number; i: number }
|
|
12
12
|
export interface Summary extends Part { text: string; size: number }
|
package/src/runs.ts
CHANGED
|
@@ -16,7 +16,8 @@ export interface RunInfo {
|
|
|
16
16
|
state: RunState; report?: string;
|
|
17
17
|
connected?: boolean;
|
|
18
18
|
handoff?: { reason: FinishReason; text?: string; delivered?: boolean };
|
|
19
|
-
|
|
19
|
+
/** `from` is missing on runs saved before senders were recorded. */
|
|
20
|
+
guidance: { text: string; date: number; state: 'queued' | 'delivered' | 'undelivered'; from?: 'user' | 'manager' }[];
|
|
20
21
|
}
|
|
21
22
|
export const isActiveRun = (run: RunInfo) => run.state === 'running' || run.state === 'waiting' || run.state === 'stopping';
|
|
22
23
|
function isRun(value: unknown): value is RunInfo {
|
|
@@ -32,7 +33,7 @@ function isRun(value: unknown): value is RunInfo {
|
|
|
32
33
|
&& (value.handoff.delivered === undefined || typeof value.handoff.delivered === 'boolean'))
|
|
33
34
|
&& typeof value.depth === 'number' && Number.isInteger(value.depth) && value.depth >= 1 && value.depth <= 3
|
|
34
35
|
&& (value.parentId === undefined || typeof value.parentId === 'string')
|
|
35
|
-
&& Array.isArray(value.guidance) && value.guidance.every(g => record(g) && typeof g.text === 'string' && typeof g.date === 'number' && ['queued', 'delivered', 'undelivered'].includes(String(g.state)));
|
|
36
|
+
&& Array.isArray(value.guidance) && value.guidance.every(g => record(g) && typeof g.text === 'string' && typeof g.date === 'number' && ['queued', 'delivered', 'undelivered'].includes(String(g.state)) && (g.from === undefined || g.from === 'user' || g.from === 'manager'));
|
|
36
37
|
}
|
|
37
38
|
export function sessionMessages(file: string): AgentMessage[] {
|
|
38
39
|
return SessionManager.open(file).getEntries().flatMap(e => e.type === 'message' ? [e.message] : []);
|