@rol1n/pi-kit 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +98 -2
- package/extensions/ask-u-questions/README.md +32 -0
- package/extensions/ask-u-questions/answers.ts +53 -0
- package/extensions/ask-u-questions/dialog-ui.ts +57 -0
- package/extensions/ask-u-questions/index.ts +88 -0
- package/extensions/ask-u-questions/multi-choice.ts +260 -0
- package/extensions/ask-u-questions/results.ts +83 -0
- package/extensions/ask-u-questions/schema.ts +17 -0
- package/extensions/ask-u-questions/single-choice.ts +182 -0
- package/extensions/ask-u-questions/tool-renderers.ts +69 -0
- package/extensions/ask-u-questions/types.ts +45 -0
- package/extensions/ask-u-questions/ui-lock.ts +24 -0
- package/extensions/continue-signal/README.md +28 -0
- package/extensions/continue-signal/index.ts +51 -0
- package/extensions/continue-signal/renderer.ts +21 -0
- package/extensions/custom-providers/README.md +28 -0
- package/extensions/custom-providers/asr/handlers/dashscope.ts +154 -0
- package/extensions/custom-providers/asr/index.ts +37 -0
- package/extensions/custom-providers/asr/models.ts +18 -0
- package/extensions/custom-providers/asr/types.ts +20 -0
- package/extensions/custom-providers/chat/index.ts +33 -0
- package/extensions/custom-providers/chat/magpie.ts +258 -0
- package/extensions/custom-providers/chat/models.ts +111 -0
- package/extensions/custom-providers/classifier/index.ts +6 -0
- package/extensions/custom-providers/classifier/models.ts +1 -0
- package/extensions/custom-providers/image/handlers/dashscope.ts +240 -0
- package/extensions/custom-providers/image/handlers/openrouter.ts +185 -0
- package/extensions/custom-providers/image/index.ts +96 -0
- package/extensions/custom-providers/image/models.ts +71 -0
- package/extensions/custom-providers/image/types.ts +22 -0
- package/extensions/custom-providers/index.ts +50 -0
- package/extensions/custom-providers/types.ts +17 -0
- package/extensions/image-generate/README.md +29 -0
- package/extensions/image-generate/files.ts +49 -0
- package/extensions/image-generate/index.ts +200 -0
- package/extensions/image-generate/model-selector.ts +150 -0
- package/extensions/image-generate/models.ts +19 -0
- package/extensions/memory-log/README.md +54 -0
- package/extensions/memory-log/agent/consolidator/prompt.ts +47 -0
- package/extensions/memory-log/agent/consolidator/tools.ts +160 -0
- package/extensions/memory-log/agent/cost.ts +32 -0
- package/extensions/memory-log/agent/index.ts +42 -0
- package/extensions/memory-log/agent/observer/prompt.ts +73 -0
- package/extensions/memory-log/agent/observer/tool.ts +73 -0
- package/extensions/memory-log/commands/compact.ts +35 -0
- package/extensions/memory-log/commands/consolidate.ts +47 -0
- package/extensions/memory-log/commands/status.ts +50 -0
- package/extensions/memory-log/config.ts +253 -0
- package/extensions/memory-log/debug-log.ts +76 -0
- package/extensions/memory-log/hooks/compaction-hook.ts +161 -0
- package/extensions/memory-log/hooks/compaction-trigger.ts +160 -0
- package/extensions/memory-log/hooks/consolidator-trigger.ts +143 -0
- package/extensions/memory-log/hooks/observer-trigger.ts +176 -0
- package/extensions/memory-log/ids.ts +78 -0
- package/extensions/memory-log/index.ts +149 -0
- package/extensions/memory-log/ledger/fold.ts +77 -0
- package/extensions/memory-log/ledger/index.ts +7 -0
- package/extensions/memory-log/ledger/pool.ts +38 -0
- package/extensions/memory-log/ledger/progress.ts +181 -0
- package/extensions/memory-log/ledger/projection.ts +115 -0
- package/extensions/memory-log/ledger/render.ts +38 -0
- package/extensions/memory-log/ledger/serialize.ts +161 -0
- package/extensions/memory-log/ledger/types.ts +201 -0
- package/extensions/memory-log/memory/index-render.ts +45 -0
- package/extensions/memory-log/memory/paths.ts +120 -0
- package/extensions/memory-log/memory/session.ts +64 -0
- package/extensions/memory-log/runtime.ts +127 -0
- package/extensions/memory-log/spawn/launch.ts +133 -0
- package/extensions/memory-log/spawn/runs.ts +83 -0
- package/extensions/memory-log/tokens.ts +66 -0
- package/extensions/memory-log/ui/status-controller.ts +225 -0
- package/extensions/memory-log/ui/timeline.ts +103 -0
- package/extensions/model-vision/README.md +28 -0
- package/extensions/multi-harness/README.md +63 -0
- package/extensions/multi-harness/adapters.mjs +72 -0
- package/extensions/multi-harness/harness-done.mjs +14 -0
- package/extensions/multi-harness/index.ts +375 -0
- package/extensions/multi-harness/ipc.mjs +37 -0
- package/extensions/multi-harness/opencode-plugin.mjs +99 -0
- package/extensions/multi-harness/process-runner.mjs +115 -0
- package/extensions/multi-harness/turn-hook.mjs +29 -0
- package/extensions/multi-harness/worker-bridge.ts +52 -0
- package/extensions/oai-subquota/README.md +30 -0
- package/extensions/oai-subquota/api.ts +27 -0
- package/extensions/oai-subquota/auth.ts +34 -0
- package/extensions/oai-subquota/cache.ts +30 -0
- package/extensions/oai-subquota/index.ts +276 -0
- package/extensions/oai-subquota/snapshot.ts +167 -0
- package/extensions/oai-subquota/types.ts +40 -0
- package/extensions/oai-subquota/ui.ts +183 -0
- package/extensions/prompt-snipaste/README.md +33 -0
- package/extensions/prompt-snipaste/index.ts +143 -0
- package/extensions/prompt-snipaste/menu.ts +159 -0
- package/extensions/prompt-snipaste/renderers.ts +88 -0
- package/extensions/prompt-snipaste/snippets.ts +203 -0
- package/extensions/prompt-snipaste/types.ts +19 -0
- package/extensions/screenshot/README.md +25 -0
- package/extensions/srp-theme/README.md +24 -0
- package/extensions/srp-theme/footer.ts +194 -0
- package/extensions/srp-theme/index.ts +172 -0
- package/extensions/srp-theme/tps-meter.ts +442 -0
- package/extensions/subagent/README.md +35 -0
- package/extensions/subagent/bridge.ts +171 -0
- package/extensions/subagent/index.ts +590 -0
- package/extensions/subagent/mux.ts +621 -0
- package/extensions/subagent/session.ts +166 -0
- package/extensions/subagent/skills/subagent/SKILL.md +70 -0
- package/extensions/subagent/ui.ts +100 -0
- package/extensions/tui-asr/README.md +28 -0
- package/extensions/tui-asr/audio.ts +40 -0
- package/extensions/tui-asr/clipboard.ts +30 -0
- package/extensions/tui-asr/dictation.ts +205 -0
- package/extensions/tui-asr/index.ts +181 -0
- package/extensions/tui-asr/input.ts +58 -0
- package/extensions/tui-asr/model-selector.ts +163 -0
- package/extensions/tui-asr/providers.ts +25 -0
- package/extensions/tui-asr/status.ts +79 -0
- package/extensions/web-reach/README.md +37 -0
- package/extensions/web-reach/html.ts +83 -0
- package/extensions/web-reach/index.ts +82 -0
- package/extensions/web-reach/page.ts +132 -0
- package/extensions/web-reach/pdf.ts +42 -0
- package/extensions/web-reach/reader.ts +42 -0
- package/extensions/web-reach/rsc.ts +161 -0
- package/extensions/web-reach/search.ts +85 -0
- package/extensions/web-reach/transport.ts +35 -0
- package/extensions/windows-wheel-fix/README.md +21 -0
- package/extensions/windows-wheel-fix/index.ts +44 -0
- package/package.json +93 -4
- package/prompts/ask-questions.md +8 -0
- package/prompts/delegate-exploration.md +7 -0
- package/prompts/diagnose-report.md +7 -0
- package/prompts/frontend-tech-preset.md +18 -0
- package/prompts/orchestrator-mode.md +7 -0
- package/prompts/session-kickoff.md +7 -0
- package/prompts/verify-not-assume.md +7 -0
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* image-generate — Image generation tool and model selector.
|
|
3
|
+
*
|
|
4
|
+
* Provides:
|
|
5
|
+
* 1. Tool `image_generate`: Tool call for generating images with local disk persistence.
|
|
6
|
+
* Delegates generation to adapters in custom-providers/image (DashScope and OpenRouter).
|
|
7
|
+
* 2. Command `/image-generate model`: Interactive model picker matching Pi's native model selector UI.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { type ExtensionAPI, type ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
11
|
+
import { Text, type AutocompleteItem } from "@earendil-works/pi-tui";
|
|
12
|
+
import { Type } from "typebox";
|
|
13
|
+
|
|
14
|
+
import {
|
|
15
|
+
fetchAllAvailableImageModels,
|
|
16
|
+
generateImage,
|
|
17
|
+
resolveImageModel,
|
|
18
|
+
type ImageModelDefinition,
|
|
19
|
+
} from "../custom-providers/image/index.ts";
|
|
20
|
+
import { saveImageAtomically } from "./files.ts";
|
|
21
|
+
import { DEFAULT_MODEL, registryImageModels, resolveProviderId } from "./models.ts";
|
|
22
|
+
import { SearchableImageModelSelectorComponent } from "./model-selector.ts";
|
|
23
|
+
|
|
24
|
+
const DEFAULT_TIMEOUT_MS = 120_000;
|
|
25
|
+
|
|
26
|
+
let currentModel = DEFAULT_MODEL;
|
|
27
|
+
|
|
28
|
+
// ============================ Extension Entrypoint ============================
|
|
29
|
+
|
|
30
|
+
export default function imageGenerate(pi: ExtensionAPI): void {
|
|
31
|
+
// 1. Slash command: /image-generate model [name]
|
|
32
|
+
pi.registerCommand("image-generate", {
|
|
33
|
+
description: "Switch default image generation model (/image-generate model [name])",
|
|
34
|
+
getArgumentCompletions: (prefix: string): AutocompleteItem[] | null => {
|
|
35
|
+
const trimmed = prefix.trimStart();
|
|
36
|
+
if (!trimmed || "model".startsWith(trimmed)) {
|
|
37
|
+
return [{ value: "model", label: "model", description: "Select image generation model in TUI" }];
|
|
38
|
+
}
|
|
39
|
+
return null;
|
|
40
|
+
},
|
|
41
|
+
handler: async (args: string, ctx: ExtensionCommandContext) => {
|
|
42
|
+
const parts = args.trim().split(/\s+/).filter(Boolean);
|
|
43
|
+
const sub = (parts[0] || "").toLowerCase();
|
|
44
|
+
|
|
45
|
+
const models = await fetchAllAvailableImageModels(registryImageModels(ctx), ctx.signal);
|
|
46
|
+
|
|
47
|
+
// Case: direct model slug provided
|
|
48
|
+
if (sub === "model" && parts[1]) {
|
|
49
|
+
const resolved = resolveImageModel(parts.slice(1).join(" "), models);
|
|
50
|
+
currentModel = resolved;
|
|
51
|
+
ctx.ui.notify(`Default image model set to: ${resolved}`, "info");
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Case: bare command or /image-generate model -> open interactive selector
|
|
56
|
+
if (sub === "model" || parts.length === 0) {
|
|
57
|
+
// Detect login status for each provider
|
|
58
|
+
const loginStatusMap = new Map<string, boolean>();
|
|
59
|
+
for (const m of models) {
|
|
60
|
+
if (!loginStatusMap.has(m.provider)) {
|
|
61
|
+
const key = await ctx.modelRegistry.getApiKeyForProvider(m.provider);
|
|
62
|
+
loginStatusMap.set(
|
|
63
|
+
m.provider,
|
|
64
|
+
Boolean(key) || Boolean(process.env[`${m.provider.toUpperCase()}_API_KEY`]),
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const chosenModel = await ctx.ui.custom<ImageModelDefinition | undefined>((tui, theme, _kb, done) => {
|
|
70
|
+
return new SearchableImageModelSelectorComponent(
|
|
71
|
+
tui,
|
|
72
|
+
theme,
|
|
73
|
+
"Select Image Generation Model",
|
|
74
|
+
models,
|
|
75
|
+
currentModel,
|
|
76
|
+
(model) => done(model),
|
|
77
|
+
() => done(undefined),
|
|
78
|
+
(provider) => loginStatusMap.get(provider) ?? false,
|
|
79
|
+
);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
if (!chosenModel) return;
|
|
83
|
+
|
|
84
|
+
currentModel = chosenModel.id;
|
|
85
|
+
const isLogged = loginStatusMap.get(chosenModel.provider);
|
|
86
|
+
const extra = isLogged ? "" : ` (No key detected: please run /login ${chosenModel.provider})`;
|
|
87
|
+
ctx.ui.notify(`Default image model set to: ${chosenModel.name} (${chosenModel.id})${extra}`, "info");
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Unknown arguments: report usage instead of silently doing nothing
|
|
92
|
+
ctx.ui.notify(
|
|
93
|
+
`Unknown argument: ${parts.join(" ")}. Usage: /image-generate [model] [name]`,
|
|
94
|
+
"warning",
|
|
95
|
+
);
|
|
96
|
+
},
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
// 2. Tool: image_generate (English Schema)
|
|
100
|
+
pi.registerTool({
|
|
101
|
+
name: "image_generate",
|
|
102
|
+
description:
|
|
103
|
+
"Generate an image from a text prompt using OpenRouter or DashScope. Saves the generated image to local disk and returns the file path.",
|
|
104
|
+
parameters: Type.Object({
|
|
105
|
+
prompt: Type.String({
|
|
106
|
+
description: "The text prompt describing the image to generate.",
|
|
107
|
+
}),
|
|
108
|
+
model: Type.Optional(
|
|
109
|
+
Type.String({
|
|
110
|
+
description:
|
|
111
|
+
"Optional model slug (e.g. 'google/gemini-3.1-flash-image', 'qwen-image-3.0-pro', 'black-forest-labs/flux.2-pro'). Defaults to current default model.",
|
|
112
|
+
}),
|
|
113
|
+
),
|
|
114
|
+
aspectRatio: Type.Optional(
|
|
115
|
+
Type.String({
|
|
116
|
+
description: "Optional aspect ratio for the image (e.g., '1:1', '16:9', '9:16', '4:3', '3:4').",
|
|
117
|
+
}),
|
|
118
|
+
),
|
|
119
|
+
image: Type.Optional(
|
|
120
|
+
Type.String({
|
|
121
|
+
description: "Optional local file path or remote image URL for image-to-image reference.",
|
|
122
|
+
}),
|
|
123
|
+
),
|
|
124
|
+
}),
|
|
125
|
+
execute: async (_toolCallId, params, signal, ctx) => {
|
|
126
|
+
const targetModel = params.model
|
|
127
|
+
? resolveImageModel(params.model, registryImageModels(ctx))
|
|
128
|
+
: currentModel;
|
|
129
|
+
const timeoutSig = AbortSignal.any([AbortSignal.timeout(DEFAULT_TIMEOUT_MS), ...(signal ? [signal] : [])]);
|
|
130
|
+
|
|
131
|
+
const providerId = resolveProviderId(ctx, targetModel);
|
|
132
|
+
const apiKey =
|
|
133
|
+
(await ctx.modelRegistry.getApiKeyForProvider(providerId)) ||
|
|
134
|
+
process.env[`${providerId.toUpperCase()}_API_KEY`];
|
|
135
|
+
|
|
136
|
+
if (!apiKey) {
|
|
137
|
+
return {
|
|
138
|
+
content: [
|
|
139
|
+
{
|
|
140
|
+
type: "text",
|
|
141
|
+
text: `Error: No ${providerId} API key found. Please run '/login ${providerId}' or set ${providerId.toUpperCase()}_API_KEY environment variable.`,
|
|
142
|
+
},
|
|
143
|
+
],
|
|
144
|
+
isError: true,
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
try {
|
|
149
|
+
const res = await generateImage(
|
|
150
|
+
{
|
|
151
|
+
prompt: params.prompt,
|
|
152
|
+
model: targetModel,
|
|
153
|
+
aspectRatio: params.aspectRatio,
|
|
154
|
+
image: params.image,
|
|
155
|
+
cwd: ctx.cwd,
|
|
156
|
+
},
|
|
157
|
+
{ apiKey, provider: providerId, signal: timeoutSig, cwd: ctx.cwd },
|
|
158
|
+
);
|
|
159
|
+
|
|
160
|
+
const savedPath = await saveImageAtomically(ctx.cwd, res.buffer, res.mimeType);
|
|
161
|
+
|
|
162
|
+
return {
|
|
163
|
+
content: [
|
|
164
|
+
{
|
|
165
|
+
type: "text",
|
|
166
|
+
text: `Image successfully generated using '${res.model}'.\nSaved to: ${savedPath}`,
|
|
167
|
+
},
|
|
168
|
+
],
|
|
169
|
+
details: {
|
|
170
|
+
model: res.model,
|
|
171
|
+
provider: res.provider,
|
|
172
|
+
savedPath,
|
|
173
|
+
prompt: params.prompt,
|
|
174
|
+
revisedPrompt: res.revisedPrompt,
|
|
175
|
+
},
|
|
176
|
+
};
|
|
177
|
+
} catch (err: any) {
|
|
178
|
+
return {
|
|
179
|
+
content: [
|
|
180
|
+
{
|
|
181
|
+
type: "text",
|
|
182
|
+
text: `Image generation failed: ${err?.message ?? String(err)}`,
|
|
183
|
+
},
|
|
184
|
+
],
|
|
185
|
+
isError: true,
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
},
|
|
189
|
+
renderCall(args, theme) {
|
|
190
|
+
const { prompt, model } = args as { prompt?: string; model?: string };
|
|
191
|
+
const displayModel = model || currentModel;
|
|
192
|
+
const preview = prompt ? (prompt.length > 50 ? prompt.slice(0, 47) + "..." : prompt) : "";
|
|
193
|
+
return new Text(
|
|
194
|
+
theme.fg("toolTitle", theme.bold("generate_image ")) +
|
|
195
|
+
theme.fg("dim", `[${displayModel}] `) +
|
|
196
|
+
theme.fg("accent", `"${preview}"`),
|
|
197
|
+
);
|
|
198
|
+
},
|
|
199
|
+
});
|
|
200
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { Container, Input, Spacer, Text, fuzzyFilter, getKeybindings } from "@earendil-works/pi-tui";
|
|
2
|
+
import type { ImageModelDefinition } from "../custom-providers/image/index.ts";
|
|
3
|
+
|
|
4
|
+
export class SearchableImageModelSelectorComponent extends Container {
|
|
5
|
+
private searchInput: Input;
|
|
6
|
+
private listContainer: Container;
|
|
7
|
+
private selectedIndex = 0;
|
|
8
|
+
private filteredModels: ImageModelDefinition[] = [];
|
|
9
|
+
private _focused = true;
|
|
10
|
+
|
|
11
|
+
get focused() {
|
|
12
|
+
return this._focused;
|
|
13
|
+
}
|
|
14
|
+
set focused(value: boolean) {
|
|
15
|
+
this._focused = value;
|
|
16
|
+
this.searchInput.focused = value;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
constructor(
|
|
20
|
+
private tui: any,
|
|
21
|
+
private theme: any,
|
|
22
|
+
private title: string,
|
|
23
|
+
private models: ImageModelDefinition[],
|
|
24
|
+
private currentModelId: string,
|
|
25
|
+
private onSelect: (model: ImageModelDefinition) => void,
|
|
26
|
+
private onCancel: () => void,
|
|
27
|
+
private getLoginStatus?: (provider: string) => boolean,
|
|
28
|
+
) {
|
|
29
|
+
super();
|
|
30
|
+
this.filteredModels = [...models];
|
|
31
|
+
const curIdx = models.findIndex((m) => m.id === currentModelId);
|
|
32
|
+
this.selectedIndex = curIdx >= 0 ? curIdx : 0;
|
|
33
|
+
|
|
34
|
+
this.searchInput = new Input();
|
|
35
|
+
this.searchInput.focused = true;
|
|
36
|
+
this.listContainer = new Container();
|
|
37
|
+
|
|
38
|
+
this.updateList();
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
filterModels(query: string) {
|
|
42
|
+
const q = query.trim().toLowerCase();
|
|
43
|
+
if (q) {
|
|
44
|
+
this.filteredModels = fuzzyFilter(
|
|
45
|
+
this.models,
|
|
46
|
+
q,
|
|
47
|
+
(m) => `${m.id} ${m.name} ${m.provider} ${m.description}`,
|
|
48
|
+
);
|
|
49
|
+
} else {
|
|
50
|
+
this.filteredModels = [...this.models];
|
|
51
|
+
}
|
|
52
|
+
this.selectedIndex = q ? 0 : Math.min(this.selectedIndex, Math.max(0, this.filteredModels.length - 1));
|
|
53
|
+
this.updateList();
|
|
54
|
+
this.tui.requestRender?.();
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
updateList() {
|
|
58
|
+
this.listContainer.clear();
|
|
59
|
+
const maxVisible = 6;
|
|
60
|
+
const total = this.filteredModels.length;
|
|
61
|
+
|
|
62
|
+
if (total === 0) {
|
|
63
|
+
this.listContainer.addChild(new Text(this.theme.fg("muted", " No matching models"), 0, 0));
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const startIndex = Math.max(0, Math.min(this.selectedIndex - Math.floor(maxVisible / 2), total - maxVisible));
|
|
68
|
+
const endIndex = Math.min(startIndex + maxVisible, total);
|
|
69
|
+
|
|
70
|
+
for (let i = startIndex; i < endIndex; i++) {
|
|
71
|
+
const item = this.filteredModels[i];
|
|
72
|
+
const isSelected = i === this.selectedIndex;
|
|
73
|
+
const isCurrent = item.id === this.currentModelId;
|
|
74
|
+
|
|
75
|
+
const cursor = isSelected ? this.theme.fg("accent", "→ ") : " ";
|
|
76
|
+
const check = isCurrent ? this.theme.fg("accent", "✓ ") : " ";
|
|
77
|
+
const modelText = isSelected
|
|
78
|
+
? this.theme.fg("accent", this.theme.bold ? this.theme.bold(item.id) : item.id)
|
|
79
|
+
: this.theme.fg("text", item.id);
|
|
80
|
+
const providerBadge = this.theme.fg("muted", `[${item.provider}]`);
|
|
81
|
+
|
|
82
|
+
let authBadge = "";
|
|
83
|
+
if (this.getLoginStatus) {
|
|
84
|
+
const loggedIn = this.getLoginStatus(item.provider);
|
|
85
|
+
authBadge = loggedIn
|
|
86
|
+
? this.theme.fg("dim", " · logged in")
|
|
87
|
+
: this.theme.fg("warning", ` · not logged in: /login ${item.provider}`);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const line = `${cursor}${check}${modelText} ${providerBadge}${authBadge}`;
|
|
91
|
+
this.listContainer.addChild(new Text(line, 0, 0));
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
if (startIndex > 0 || endIndex < total) {
|
|
95
|
+
const scrollInfo = this.theme.fg("muted", ` (${this.selectedIndex + 1}/${total})`);
|
|
96
|
+
this.listContainer.addChild(new Text(scrollInfo, 0, 0));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const selected = this.filteredModels[this.selectedIndex];
|
|
100
|
+
if (selected) {
|
|
101
|
+
this.listContainer.addChild(new Spacer(1));
|
|
102
|
+
this.listContainer.addChild(
|
|
103
|
+
new Text(this.theme.fg("muted", ` Model: ${selected.name} — ${selected.description}`), 0, 0),
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
render(width: number): string[] {
|
|
109
|
+
this.clear();
|
|
110
|
+
const border = this.theme.fg("accent", "─".repeat(Math.max(10, width)));
|
|
111
|
+
|
|
112
|
+
this.addChild(new Text(border, 0, 0));
|
|
113
|
+
this.addChild(new Spacer(1));
|
|
114
|
+
this.addChild(new Text(this.theme.fg("accent", this.theme.bold ? this.theme.bold(` ${this.title}`) : ` ${this.title}`), 0, 0));
|
|
115
|
+
this.addChild(new Spacer(1));
|
|
116
|
+
this.addChild(this.searchInput);
|
|
117
|
+
this.addChild(new Spacer(1));
|
|
118
|
+
this.addChild(this.listContainer);
|
|
119
|
+
this.addChild(new Spacer(1));
|
|
120
|
+
this.addChild(new Text(this.theme.fg("dim", " Enter to select · Escape to cancel"), 0, 0));
|
|
121
|
+
this.addChild(new Text(border, 0, 0));
|
|
122
|
+
|
|
123
|
+
return super.render(width);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
handleInput(keyData: string) {
|
|
127
|
+
const kb = getKeybindings();
|
|
128
|
+
if (kb.matches(keyData, "tui.select.up") || keyData === "k") {
|
|
129
|
+
if (this.filteredModels.length === 0) return;
|
|
130
|
+
this.selectedIndex = this.selectedIndex === 0 ? this.filteredModels.length - 1 : this.selectedIndex - 1;
|
|
131
|
+
this.updateList();
|
|
132
|
+
this.tui.requestRender?.();
|
|
133
|
+
} else if (kb.matches(keyData, "tui.select.down") || keyData === "j") {
|
|
134
|
+
if (this.filteredModels.length === 0) return;
|
|
135
|
+
this.selectedIndex = this.selectedIndex === this.filteredModels.length - 1 ? 0 : this.selectedIndex + 1;
|
|
136
|
+
this.updateList();
|
|
137
|
+
this.tui.requestRender?.();
|
|
138
|
+
} else if (kb.matches(keyData, "tui.select.confirm") || keyData === "\n" || keyData === "\r") {
|
|
139
|
+
const selected = this.filteredModels[this.selectedIndex];
|
|
140
|
+
if (selected) {
|
|
141
|
+
this.onSelect(selected);
|
|
142
|
+
}
|
|
143
|
+
} else if (kb.matches(keyData, "tui.select.cancel") || keyData === "\x1b" || keyData === "\x03") {
|
|
144
|
+
this.onCancel();
|
|
145
|
+
} else {
|
|
146
|
+
this.searchInput.handleInput(keyData);
|
|
147
|
+
this.filterModels(this.searchInput.getValue());
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** Image catalog lookup and provider selection. */
|
|
2
|
+
|
|
3
|
+
export const DEFAULT_MODEL = "google/gemini-3.1-flash-image";
|
|
4
|
+
|
|
5
|
+
/** Image models known to Pi: OpenRouter's built-in catalog plus our DashScope registration. */
|
|
6
|
+
export function registryImageModels(ctx: { modelRegistry: { getModelsOfType(type: string): readonly any[] } }) {
|
|
7
|
+
return ctx.modelRegistry.getModelsOfType("image") as readonly { id: string; name?: string; provider: string }[];
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** Resolve which provider owns a model id, preferring the Pi registry over heuristics. */
|
|
11
|
+
export function resolveProviderId(
|
|
12
|
+
ctx: { modelRegistry: { getModelsOfType(type: string): readonly any[] } },
|
|
13
|
+
modelId: string,
|
|
14
|
+
): string {
|
|
15
|
+
const lower = modelId.toLowerCase();
|
|
16
|
+
const known = registryImageModels(ctx).find((m) => m.id.toLowerCase() === lower);
|
|
17
|
+
if (known) return known.provider;
|
|
18
|
+
return lower.startsWith("qwen-image") ? "dashscope" : "openrouter";
|
|
19
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
# memory-log
|
|
2
|
+
|
|
3
|
+
Observational memory for long Pi sessions: background observers distill conversation chunks, a ledger records observations, and a consolidator writes durable project memory. Compaction rebuilds context from the recorded memory and recent conversation.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
pi install npm:@rol1n/memory-log
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Also included in `@rol1n/pi-kit`. The extension loads with new-session memory disabled by default.
|
|
12
|
+
|
|
13
|
+
## Commands
|
|
14
|
+
|
|
15
|
+
| Command | Action |
|
|
16
|
+
|---|---|
|
|
17
|
+
| `/mem-log on` / `/mem-log off` | Set the current session's memory gate |
|
|
18
|
+
| `/mem-log status` or `/mem-log:status` | Inspect observation progress, workers, memory, and costs |
|
|
19
|
+
| `/mem-log compact` or `/mem-log:compact` | Request compaction |
|
|
20
|
+
| `/mem-log consolidate` or `/mem-log:consolidate` | Consolidate the observation pool |
|
|
21
|
+
|
|
22
|
+
## Settings
|
|
23
|
+
|
|
24
|
+
Add `memoryLog` to personal or project Pi settings. Project values override personal values:
|
|
25
|
+
|
|
26
|
+
```json
|
|
27
|
+
{
|
|
28
|
+
"memoryLog": {
|
|
29
|
+
"defaultEnabled": false,
|
|
30
|
+
"chunkTokens": 10000,
|
|
31
|
+
"poolTargetTokens": 10000,
|
|
32
|
+
"consolidateAtPoolTokens": 15000,
|
|
33
|
+
"compactAtContextTokens": 150000,
|
|
34
|
+
"tailTokens": 20000,
|
|
35
|
+
"journeyTargetTokens": 1000,
|
|
36
|
+
"observerConcurrency": 4,
|
|
37
|
+
"resumeAfterMidRunCompaction": true,
|
|
38
|
+
"passive": false,
|
|
39
|
+
"debugLog": false,
|
|
40
|
+
"models": {
|
|
41
|
+
"observer": { "thinking": "low" },
|
|
42
|
+
"consolidator": { "thinking": "medium" }
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Observer and consolidator model objects accept `provider`, `id`, and `thinking`. An explicitly configured model takes priority over the session model, followed by Pi's configured default model. `chunkOverlapTokens` defaults to zero.
|
|
49
|
+
|
|
50
|
+
Environment overrides are `PI_OM_PASSIVE`, `PI_OM_OBSERVER_PROVIDER`, `PI_OM_OBSERVER_MODEL`, `PI_OM_OBSERVER_THINKING`, and the corresponding `PI_OM_CONSOLIDATOR_*` values. Passive mode disables automatic triggers separately from the session gate.
|
|
51
|
+
|
|
52
|
+
## Storage and requirements
|
|
53
|
+
|
|
54
|
+
Durable files live under `.memory/<session-id>/` in the working project, including topic files and `JOURNEY.md`. Gate changes and observation history are recorded in the Pi session ledger. Observer and consolidator workers require the `pi` executable and model credentials; they make additional model requests. Disabling memory aborts active background workers.
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
export const CONSOLIDATOR_SYSTEM = `You are the consolidation agent for a coding assistant's long-term memory.
|
|
2
|
+
|
|
3
|
+
Your job: take a batch of older observations (timestamped facts distilled from earlier conversation) and fold them into durable topic files under .memory/. These topic files are the assistant's permanent, cross-session memory of this project. The observations you are given are about to be deleted from the short-term buffer, so anything worth keeping that you fail to record here is forgotten forever.
|
|
4
|
+
|
|
5
|
+
You operate entirely on .memory/. You have scoped tools: read, write, edit, ls, grep — all confined to the .memory/ directory. You CANNOT touch anything outside .memory/. Do NOT create or edit INDEX.md; it is generated automatically from your topic files' front-matter — your job is the <topic>.md files plus JOURNEY.md (described below).
|
|
6
|
+
|
|
7
|
+
How you work:
|
|
8
|
+
1. Run ls to see existing topic files, and read the ones relevant to the incoming observations.
|
|
9
|
+
2. For each incoming observation, decide where it belongs: an existing topic file, or a new one.
|
|
10
|
+
3. Write/edit topic files so each holds clean, current-state prose about its topic.
|
|
11
|
+
4. Update JOURNEY.md (see below) with a short segment covering this batch.
|
|
12
|
+
5. When every incoming observation has been folded in (or deliberately discarded as low-value/noise), emit a one-sentence confirmation and stop.
|
|
13
|
+
|
|
14
|
+
Topic routing (start conservative — prefer fewer, larger topics; split only when a file clearly covers two unrelated subjects):
|
|
15
|
+
- Create a topic when the observations introduce a genuinely new subject with no existing home.
|
|
16
|
+
- Merge into an existing topic when the observations extend or update it.
|
|
17
|
+
- Split a topic only when it has grown to cover clearly distinct subjects.
|
|
18
|
+
|
|
19
|
+
Writing topic files:
|
|
20
|
+
- Write current-state prose, not a changelog. If an observation supersedes an existing fact, REWRITE the file to reflect the new truth and delete the obsolete statement. Do not leave "was X, now Y" cruft or tombstones.
|
|
21
|
+
- Preserve distinguishing detail: file paths, identifiers, package/function names, error codes, exact numbers, the user's own terminology (quote unusual terms verbatim).
|
|
22
|
+
- Keep prose tight and skimmable. Headings and short paragraphs or bullet lists are fine. This is reference material the assistant will read later.
|
|
23
|
+
- Preserve the authoritative/assertion vs question distinction the observations carry. User assertions are authoritative.
|
|
24
|
+
|
|
25
|
+
JOURNEY.md — the running project history (orientation, not a topic file):
|
|
26
|
+
- Purpose: ONE brief, free-form narrative of how this project/work reached its current state, so a future reader can orient to the rough arc of how we got here. Its current contents are provided in your prompt; you rewrite the whole file with the write tool. It has NO front-matter and is not a topic file.
|
|
27
|
+
- STRICTLY DESCRIPTIVE. Write only what happened, in the past tense. Do NOT include recommendations, next steps, TODOs, plans, advice, warnings, predictions, open questions framed as tasks, or evaluative judgement. No "should", "needs to", "the goal is", "next we". If you catch yourself steering future behaviour, delete that sentence. It exists purely to orient, never to instruct.
|
|
28
|
+
- Keep it ROUGH and high-level: the shape of the journey, not a detailed log. Topic files already hold the details.
|
|
29
|
+
- APPEND-MOSTLY: add one short dated segment (2-5 sentences) describing the arc that THIS batch of observations represents, using a '## <date>' heading and the current time from your prompt. Leave existing recent segments intact — do not rewrite them.
|
|
30
|
+
- THIS BATCH IS NOT THE END OF THE SESSION. The session was still running when you were invoked — these observations are an early or mid-session slice; newer conversation exists beyond this batch that has not been consolidated yet. Never write as if this batch edge is the current moment. Forbidden phrases: "by session end", "at the end of the session", "the session concluded", "work remaining", or anything framed as the present state. Use past-arc language instead: "during this period", "by this point", "at this stage of the session".
|
|
31
|
+
- COMPRESS THE OLD TAIL ONLY WHEN OVER SIZE: if the file would exceed the token budget given in your prompt, condense the OLDEST segments into a tighter summary at the top, preserving the most recent segments in more detail. Recent history stays detailed; the distant past gets condensed. Never grow the file unbounded.
|
|
32
|
+
- Order chronologically, oldest first (a compressed early-history summary may lead).
|
|
33
|
+
|
|
34
|
+
Front-matter (REQUIRED at the top of every topic file you write):
|
|
35
|
+
---
|
|
36
|
+
id: <stable-slug> # matches the filename without .md, e.g. "auth" for auth.md
|
|
37
|
+
title: <short human title>
|
|
38
|
+
summary: <one line, <= 140 chars; what this file covers — this is what the assistant sees in the index>
|
|
39
|
+
updated: <the current date/time provided in your prompt>
|
|
40
|
+
---
|
|
41
|
+
Maintain these fields whenever you write a file. The summary is load-bearing: it is the ONLY thing the assistant sees about this file until it opens it, so make it specific.
|
|
42
|
+
|
|
43
|
+
Filenames: lowercase kebab-case slugs ending in .md (e.g. auth.md, deploy-pipeline.md, user-preferences.md). The id must equal the filename without .md.
|
|
44
|
+
|
|
45
|
+
Completion:
|
|
46
|
+
- When done, emit a one-sentence plain-text confirmation and stop. The run ends on its own.
|
|
47
|
+
- The whole incoming batch leaves the short-term buffer once you finish, whether you filed it or judged it not worth keeping — you do not report back. So make sure everything worth keeping has been written to a file before you stop. Discarding clear noise is fine and expected; dropping a genuine fact you meant to keep is the failure to avoid.`;
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
2
|
+
import { join, relative, resolve } from "node:path";
|
|
3
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
import { Type } from "typebox";
|
|
5
|
+
import type { Static } from "typebox";
|
|
6
|
+
import { atomicWrite } from "../../memory/paths.ts";
|
|
7
|
+
|
|
8
|
+
type ToolText = { content: { type: "text"; text: string }[]; details: unknown };
|
|
9
|
+
|
|
10
|
+
function ok(text: string, details: unknown = {}): ToolText {
|
|
11
|
+
return { content: [{ type: "text" as const, text }], details };
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function fail(text: string): ToolText {
|
|
15
|
+
return { content: [{ type: "text" as const, text: `Error: ${text}` }], details: { error: true } };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function scoped(root: string, requested: string): string | undefined {
|
|
19
|
+
const abs = resolve(root, requested);
|
|
20
|
+
const rel = relative(root, abs);
|
|
21
|
+
if (rel === "") return abs;
|
|
22
|
+
if (rel.startsWith("..")) return undefined;
|
|
23
|
+
return abs;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const ReadSchema = Type.Object({
|
|
27
|
+
path: Type.String({ description: "Path inside .memory/, e.g. 'auth.md' or '.memory/auth.md'." }),
|
|
28
|
+
});
|
|
29
|
+
const WriteSchema = Type.Object({
|
|
30
|
+
path: Type.String({ description: "Path inside .memory/ to (over)write, e.g. 'auth.md'." }),
|
|
31
|
+
content: Type.String({ description: "Full file content, including YAML front-matter." }),
|
|
32
|
+
});
|
|
33
|
+
const EditSchema = Type.Object({
|
|
34
|
+
path: Type.String({ description: "Path inside .memory/ to edit." }),
|
|
35
|
+
oldText: Type.String({ description: "Exact text to replace (must occur exactly once)." }),
|
|
36
|
+
newText: Type.String({ description: "Replacement text." }),
|
|
37
|
+
});
|
|
38
|
+
const LsSchema = Type.Object({
|
|
39
|
+
path: Type.Optional(Type.String({ description: "Subdirectory inside .memory/. Defaults to .memory/ root." })),
|
|
40
|
+
});
|
|
41
|
+
const GrepSchema = Type.Object({
|
|
42
|
+
pattern: Type.String({ description: "JavaScript regular expression to search for." }),
|
|
43
|
+
path: Type.Optional(Type.String({ description: "Restrict to this file/subdir inside .memory/." })),
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
type ReadInput = Static<typeof ReadSchema>;
|
|
47
|
+
type WriteInput = Static<typeof WriteSchema>;
|
|
48
|
+
type EditInput = Static<typeof EditSchema>;
|
|
49
|
+
type LsInput = Static<typeof LsSchema>;
|
|
50
|
+
type GrepInput = Static<typeof GrepSchema>;
|
|
51
|
+
|
|
52
|
+
function listFilesRecursive(dir: string): string[] {
|
|
53
|
+
const out: string[] = [];
|
|
54
|
+
for (const name of readdirSync(dir)) {
|
|
55
|
+
if (name.startsWith(".")) continue;
|
|
56
|
+
const full = join(dir, name);
|
|
57
|
+
if (statSync(full).isDirectory()) out.push(...listFilesRecursive(full));
|
|
58
|
+
else out.push(full);
|
|
59
|
+
}
|
|
60
|
+
return out;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function registerConsolidatorTools(pi: ExtensionAPI, memoryRoot: string): void {
|
|
64
|
+
const root = resolve(memoryRoot);
|
|
65
|
+
|
|
66
|
+
pi.registerTool({
|
|
67
|
+
name: "read",
|
|
68
|
+
label: "Read memory file",
|
|
69
|
+
description: "Read a topic file under .memory/.",
|
|
70
|
+
parameters: ReadSchema,
|
|
71
|
+
async execute(_id: string, params: ReadInput): Promise<ToolText> {
|
|
72
|
+
const abs = scoped(root, params.path);
|
|
73
|
+
if (!abs) return fail("path escapes .memory/");
|
|
74
|
+
if (!existsSync(abs)) return fail(`no such file: ${params.path}`);
|
|
75
|
+
return ok(readFileSync(abs, "utf-8"));
|
|
76
|
+
},
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
pi.registerTool({
|
|
80
|
+
name: "write",
|
|
81
|
+
label: "Write memory file",
|
|
82
|
+
description: "Create or overwrite a topic file under .memory/ (atomic). Do not write INDEX.md.",
|
|
83
|
+
parameters: WriteSchema,
|
|
84
|
+
async execute(_id: string, params: WriteInput): Promise<ToolText> {
|
|
85
|
+
const abs = scoped(root, params.path);
|
|
86
|
+
if (!abs) return fail("path escapes .memory/");
|
|
87
|
+
if (/(^|\/)INDEX\.md$/i.test(params.path)) return fail("INDEX.md is generated automatically; do not write it");
|
|
88
|
+
atomicWrite(abs, params.content);
|
|
89
|
+
return ok(`Wrote ${params.path} (${params.content.length} bytes).`);
|
|
90
|
+
},
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
pi.registerTool({
|
|
94
|
+
name: "edit",
|
|
95
|
+
label: "Edit memory file",
|
|
96
|
+
description: "Replace an exact substring in a topic file under .memory/ (atomic).",
|
|
97
|
+
parameters: EditSchema,
|
|
98
|
+
async execute(_id: string, params: EditInput): Promise<ToolText> {
|
|
99
|
+
const abs = scoped(root, params.path);
|
|
100
|
+
if (!abs) return fail("path escapes .memory/");
|
|
101
|
+
if (/(^|\/)INDEX\.md$/i.test(params.path)) return fail("INDEX.md is generated automatically; do not edit it");
|
|
102
|
+
if (!existsSync(abs)) return fail(`no such file: ${params.path}`);
|
|
103
|
+
const current = readFileSync(abs, "utf-8");
|
|
104
|
+
const occurrences = current.split(params.oldText).length - 1;
|
|
105
|
+
if (occurrences === 0) return fail("oldText not found");
|
|
106
|
+
if (occurrences > 1) return fail(`oldText is ambiguous (${occurrences} matches); add more context`);
|
|
107
|
+
atomicWrite(abs, current.replace(params.oldText, params.newText));
|
|
108
|
+
return ok(`Edited ${params.path}.`);
|
|
109
|
+
},
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
pi.registerTool({
|
|
113
|
+
name: "ls",
|
|
114
|
+
label: "List memory files",
|
|
115
|
+
description: "List files under .memory/.",
|
|
116
|
+
parameters: LsSchema,
|
|
117
|
+
async execute(_id: string, params: LsInput): Promise<ToolText> {
|
|
118
|
+
const targetDir = params.path ? scoped(root, params.path) : root;
|
|
119
|
+
if (!targetDir) return fail("path escapes .memory/");
|
|
120
|
+
if (!existsSync(targetDir)) return fail(`no such directory: ${params.path ?? "."}`);
|
|
121
|
+
const files = listFilesRecursive(targetDir).map((p) => relative(root, p));
|
|
122
|
+
return ok(files.length > 0 ? files.join("\n") : "(empty directory)");
|
|
123
|
+
},
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
pi.registerTool({
|
|
127
|
+
name: "grep",
|
|
128
|
+
label: "Search memory files",
|
|
129
|
+
description: "Search topic files under .memory/ using a regular expression.",
|
|
130
|
+
parameters: GrepSchema,
|
|
131
|
+
async execute(_id: string, params: GrepInput): Promise<ToolText> {
|
|
132
|
+
let re: RegExp;
|
|
133
|
+
try {
|
|
134
|
+
re = new RegExp(params.pattern);
|
|
135
|
+
} catch (error) {
|
|
136
|
+
return fail(`invalid regex: ${error instanceof Error ? error.message : String(error)}`);
|
|
137
|
+
}
|
|
138
|
+
const target = params.path ? scoped(root, params.path) : root;
|
|
139
|
+
if (!target) return fail("path escapes .memory/");
|
|
140
|
+
if (!existsSync(target)) return fail(`no such file/directory: ${params.path ?? "."}`);
|
|
141
|
+
|
|
142
|
+
const files = statSync(target).isDirectory() ? listFilesRecursive(target) : [target];
|
|
143
|
+
const matches: string[] = [];
|
|
144
|
+
for (const file of files) {
|
|
145
|
+
const rel = relative(root, file);
|
|
146
|
+
let content: string;
|
|
147
|
+
try {
|
|
148
|
+
content = readFileSync(file, "utf-8");
|
|
149
|
+
} catch {
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
const lines = content.split("\n");
|
|
153
|
+
for (let i = 0; i < lines.length; i++) {
|
|
154
|
+
if (re.test(lines[i])) matches.push(`${rel}:${i + 1}: ${lines[i]}`);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
return ok(matches.length > 0 ? matches.join("\n") : "(no matches)");
|
|
158
|
+
},
|
|
159
|
+
});
|
|
160
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { writeWorkerCost } from "../spawn/runs.ts";
|
|
3
|
+
|
|
4
|
+
type CostUsage = { cost?: { total?: unknown } };
|
|
5
|
+
type MaybeAssistantMessage = { role?: string; usage?: CostUsage };
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Register shared cost accumulation for subprocess workers.
|
|
9
|
+
*/
|
|
10
|
+
export function trackWorkerCost(pi: ExtensionAPI): void {
|
|
11
|
+
const costPath = process.env.OM_COST_PATH;
|
|
12
|
+
if (!costPath) return;
|
|
13
|
+
|
|
14
|
+
let costUsd = 0;
|
|
15
|
+
|
|
16
|
+
pi.on("message_end", async (event: { message?: MaybeAssistantMessage }) => {
|
|
17
|
+
const message = event?.message;
|
|
18
|
+
if (message?.role !== "assistant") return;
|
|
19
|
+
const total = message.usage?.cost?.total;
|
|
20
|
+
if (typeof total === "number" && Number.isFinite(total) && total > 0) {
|
|
21
|
+
costUsd += total;
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
pi.on("agent_end", async () => {
|
|
26
|
+
try {
|
|
27
|
+
writeWorkerCost(costPath, { costUsd });
|
|
28
|
+
} catch {
|
|
29
|
+
// ignore — cost is non-critical telemetry
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
}
|