omp-alamode 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/LICENSE +21 -0
- package/README.md +139 -2
- package/package.json +42 -4
- package/src/credit-balance.ts +237 -0
- package/src/flymode.ts +1 -0
- package/src/lemmeaskchat.ts +1 -0
- package/src/let-me-see.ts +1 -0
- package/src/tokenmunchers.ts +1 -0
- package/src/usage-awareness.ts +306 -0
- package/src/usage-knowledge.ts +714 -0
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
import type { ContextEvent, ExtensionAPI, ExtensionContext } from "@oh-my-pi/pi-coding-agent";
|
|
2
|
+
|
|
3
|
+
import { CreditBalances } from "./credit-balance";
|
|
4
|
+
import { getUsageKnowledge } from "./usage-knowledge";
|
|
5
|
+
|
|
6
|
+
const COMMAND_NAME = "usage-awareness";
|
|
7
|
+
const CUSTOM_TYPE = "alamode-usage-awareness";
|
|
8
|
+
const STATUS_KEY = "alamode-usage-awareness";
|
|
9
|
+
const STATUS_ON = "usage awareness: on";
|
|
10
|
+
const STATUS_LIMIT = 120;
|
|
11
|
+
const USAGE =
|
|
12
|
+
"Usage: /usage-awareness [on|off|status] | /usage-awareness balance <USD> [low-USD] | /usage-awareness balance clear";
|
|
13
|
+
const CREDIT_FALLBACK_NOTE =
|
|
14
|
+
"Scenario estimate only; a budget cannot be certified. Task/subagent charges are excluded from provider attribution, so actual remaining may be lower.";
|
|
15
|
+
const DECIMAL_USD = /^(?:\d+(?:\.\d+)?|\.\d+)$/;
|
|
16
|
+
|
|
17
|
+
type ContextMessage = ContextEvent["messages"][number];
|
|
18
|
+
type OwnMessage = Extract<ContextMessage, { role: "custom" }>;
|
|
19
|
+
type KnowledgeReader = typeof getUsageKnowledge;
|
|
20
|
+
|
|
21
|
+
interface CreditDescription {
|
|
22
|
+
text: string;
|
|
23
|
+
reminder?: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
interface CreditBalanceSource {
|
|
27
|
+
set(ctx: ExtensionContext, balance: number, lowThreshold?: number): void;
|
|
28
|
+
clear(provider?: string): void;
|
|
29
|
+
describe(ctx: ExtensionContext): CreditDescription | undefined;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function isOwnMessage(message: ContextMessage): message is OwnMessage {
|
|
33
|
+
return message.role === "custom" && message.customType === CUSTOM_TYPE;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Footer text is one line; prefer the context line when the knowledge provides one. */
|
|
37
|
+
function compactStatus(knowledge: string): string {
|
|
38
|
+
const lines = knowledge
|
|
39
|
+
.split(/\r?\n/)
|
|
40
|
+
.map(line => line.trim())
|
|
41
|
+
.filter(line => line.length > 0);
|
|
42
|
+
const first =
|
|
43
|
+
lines.find(line => line.startsWith("Context:")) ??
|
|
44
|
+
lines.find(line => !line.startsWith("Usage awareness")) ??
|
|
45
|
+
"";
|
|
46
|
+
if (!first) return STATUS_ON;
|
|
47
|
+
const prefix = "usage: ";
|
|
48
|
+
const available = STATUS_LIMIT - prefix.length;
|
|
49
|
+
return first.length <= available ? `${prefix}${first}` : `${prefix}${first.slice(0, available - 3)}...`;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function parseUsd(value: string): number | undefined {
|
|
53
|
+
if (!DECIMAL_USD.test(value)) return undefined;
|
|
54
|
+
const amount = Number(value);
|
|
55
|
+
return Number.isFinite(amount) && amount >= 0 ? amount : undefined;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Match CreditBalances precision: tiny non-zero balances must not render as $0.00. */
|
|
59
|
+
function formatUsd(value: number): string {
|
|
60
|
+
if (!Number.isFinite(value)) return "$?";
|
|
61
|
+
if (value === 0) return "$0.00";
|
|
62
|
+
if (value >= 1) return `$${value.toFixed(2)}`;
|
|
63
|
+
const digits = Math.min(10, Math.max(2, 3 - Math.floor(Math.log10(value))));
|
|
64
|
+
const fixed = value.toFixed(digits);
|
|
65
|
+
if (Number(fixed) === 0) return `$${value.toExponential(2)}`;
|
|
66
|
+
const fraction = fixed.split(".")[1] ?? "";
|
|
67
|
+
return `$${fixed.split(".")[0]}.${fraction.replace(/0+$/, "").padEnd(2, "0")}`;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export default function usageAwareness(
|
|
71
|
+
pi: ExtensionAPI,
|
|
72
|
+
readKnowledge: KnowledgeReader = getUsageKnowledge,
|
|
73
|
+
credits: CreditBalanceSource = new CreditBalances(),
|
|
74
|
+
): void {
|
|
75
|
+
let enabled = false;
|
|
76
|
+
/** Bumped whenever an async read's result may no longer apply. */
|
|
77
|
+
let transition = 0;
|
|
78
|
+
/** Newest user-facing read wins; an older notification must not overwrite it. */
|
|
79
|
+
let uiRequest = 0;
|
|
80
|
+
let statusShown = false;
|
|
81
|
+
|
|
82
|
+
function showStatus(ctx: ExtensionContext, text: string): void {
|
|
83
|
+
statusShown = true;
|
|
84
|
+
ctx.ui.setStatus(STATUS_KEY, text);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function clearStatus(ctx: ExtensionContext): void {
|
|
88
|
+
if (!statusShown) return;
|
|
89
|
+
statusShown = false;
|
|
90
|
+
ctx.ui.setStatus(STATUS_KEY, undefined);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async function load(ctx: ExtensionContext): Promise<string | undefined> {
|
|
94
|
+
try {
|
|
95
|
+
const knowledge = await readKnowledge(ctx);
|
|
96
|
+
if (typeof knowledge !== "string") return undefined;
|
|
97
|
+
const trimmed = knowledge.trim();
|
|
98
|
+
return trimmed.length > 0 ? trimmed : undefined;
|
|
99
|
+
} catch {
|
|
100
|
+
// Error text can carry provider or credential detail; never surface it here.
|
|
101
|
+
return undefined;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Local session estimate only; callers must have established that awareness is enabled. */
|
|
106
|
+
function describeCredits(ctx: ExtensionContext): CreditDescription | undefined {
|
|
107
|
+
try {
|
|
108
|
+
const description = credits.describe(ctx);
|
|
109
|
+
if (description?.reminder) ctx.ui.notify(description.reminder, "warning");
|
|
110
|
+
return description;
|
|
111
|
+
} catch {
|
|
112
|
+
return undefined;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
async function display(ctx: ExtensionContext): Promise<void> {
|
|
117
|
+
const request = ++uiRequest;
|
|
118
|
+
const startedAt = transition;
|
|
119
|
+
const knowledge = await load(ctx);
|
|
120
|
+
if (!enabled || transition !== startedAt || uiRequest !== request) return;
|
|
121
|
+
|
|
122
|
+
const credit = describeCredits(ctx)?.text?.trim();
|
|
123
|
+
const text = knowledge ? (credit ? `${knowledge}\n\n${credit}` : knowledge) : credit;
|
|
124
|
+
if (!text) {
|
|
125
|
+
ctx.ui.notify("Usage awareness is on, but current usage knowledge is unavailable.", "warning");
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
showStatus(ctx, compactStatus(text));
|
|
129
|
+
if (knowledge) {
|
|
130
|
+
ctx.ui.notify(text, "info");
|
|
131
|
+
} else {
|
|
132
|
+
ctx.ui.notify(
|
|
133
|
+
`Usage awareness is on, but current usage and quota knowledge is unavailable.\n\n${text}`,
|
|
134
|
+
"warning",
|
|
135
|
+
);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function disable(ctx: ExtensionContext, announce: boolean): void {
|
|
140
|
+
enabled = false;
|
|
141
|
+
transition++;
|
|
142
|
+
uiRequest++;
|
|
143
|
+
clearStatus(ctx);
|
|
144
|
+
if (announce) ctx.ui.notify("Usage awareness off.", "info");
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async function enable(ctx: ExtensionContext): Promise<void> {
|
|
148
|
+
if (!enabled) {
|
|
149
|
+
enabled = true;
|
|
150
|
+
showStatus(ctx, STATUS_ON);
|
|
151
|
+
}
|
|
152
|
+
await display(ctx);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function reset(ctx: ExtensionContext): void {
|
|
156
|
+
enabled = false;
|
|
157
|
+
transition++;
|
|
158
|
+
uiRequest++;
|
|
159
|
+
clearStatus(ctx);
|
|
160
|
+
try {
|
|
161
|
+
credits.clear();
|
|
162
|
+
} catch {
|
|
163
|
+
// Session transitions must still complete when a credit estimate cannot be cleared.
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function setBalance(tokens: string[], ctx: ExtensionContext): void {
|
|
168
|
+
const provider = ctx.model?.provider;
|
|
169
|
+
if (!provider) {
|
|
170
|
+
ctx.ui.notify("Usage awareness: no active model provider; credit balance unchanged.", "warning");
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
if (tokens.length === 1 && tokens[0]?.toLowerCase() === "clear") {
|
|
175
|
+
try {
|
|
176
|
+
credits.clear(provider);
|
|
177
|
+
ctx.ui.notify(`Usage awareness: cleared the session credit estimate for ${provider}.`, "info");
|
|
178
|
+
} catch {
|
|
179
|
+
ctx.ui.notify("Usage awareness: could not clear the credit estimate.", "warning");
|
|
180
|
+
}
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
if (tokens.length < 1 || tokens.length > 2) {
|
|
185
|
+
ctx.ui.notify(USAGE, "warning");
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
const starting = parseUsd(tokens[0] ?? "");
|
|
189
|
+
const lowThreshold = tokens.length === 2 ? parseUsd(tokens[1] ?? "") : undefined;
|
|
190
|
+
if (starting === undefined || (tokens.length === 2 && lowThreshold === undefined)) {
|
|
191
|
+
ctx.ui.notify(USAGE, "warning");
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const threshold = lowThreshold ?? starting * 0.1;
|
|
196
|
+
try {
|
|
197
|
+
credits.set(ctx, starting, lowThreshold);
|
|
198
|
+
} catch {
|
|
199
|
+
ctx.ui.notify("Usage awareness: could not record the credit balance estimate.", "warning");
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
let described: CreditDescription | undefined;
|
|
204
|
+
if (enabled) {
|
|
205
|
+
described = describeCredits(ctx);
|
|
206
|
+
}
|
|
207
|
+
const describedText = described?.text?.trim();
|
|
208
|
+
const estimate =
|
|
209
|
+
describedText ||
|
|
210
|
+
`Estimated remaining: ${formatUsd(starting)} (baseline captured now; no later recorded cost applied yet).`;
|
|
211
|
+
const scope = describedText ? "" : ` ${CREDIT_FALLBACK_NOTE}`;
|
|
212
|
+
ctx.ui.notify(
|
|
213
|
+
`Usage awareness: starting balance ${formatUsd(starting)}, low-balance threshold ${formatUsd(threshold)} for ${provider}. ${estimate}${scope}`,
|
|
214
|
+
"info",
|
|
215
|
+
);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
pi.registerCommand(COMMAND_NAME, {
|
|
219
|
+
description:
|
|
220
|
+
"Include current context, token, cost, and provider quota knowledge in model calls, with optional credit estimates: /usage-awareness [on|off|status|balance]",
|
|
221
|
+
getArgumentCompletions: prefix => {
|
|
222
|
+
const value = prefix.trim().toLowerCase();
|
|
223
|
+
return ["on", "off", "status", "balance"]
|
|
224
|
+
.filter(option => option.startsWith(value))
|
|
225
|
+
.map(option => ({ value: option, label: option }));
|
|
226
|
+
},
|
|
227
|
+
handler: async (args, ctx) => {
|
|
228
|
+
const trimmed = args.trim();
|
|
229
|
+
const tokens = trimmed.length > 0 ? trimmed.split(/\s+/) : [];
|
|
230
|
+
const head = tokens[0]?.toLowerCase() ?? "";
|
|
231
|
+
|
|
232
|
+
if (tokens.length === 0) {
|
|
233
|
+
if (enabled) disable(ctx, true);
|
|
234
|
+
else await enable(ctx);
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
if (tokens.length === 1 && head === "on") {
|
|
238
|
+
await enable(ctx);
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
if (tokens.length === 1 && head === "off") {
|
|
242
|
+
disable(ctx, true);
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
if (tokens.length === 1 && head === "status") {
|
|
246
|
+
if (!enabled) {
|
|
247
|
+
ctx.ui.notify("Usage awareness is off.", "info");
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
await display(ctx);
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
if (head === "balance") {
|
|
254
|
+
setBalance(tokens.slice(1), ctx);
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
ctx.ui.notify(USAGE, "warning");
|
|
258
|
+
},
|
|
259
|
+
});
|
|
260
|
+
|
|
261
|
+
pi.on("context", async (event, ctx) => {
|
|
262
|
+
const hadOwn = event.messages.some(isOwnMessage);
|
|
263
|
+
const messages = hadOwn ? event.messages.filter(message => !isOwnMessage(message)) : event.messages;
|
|
264
|
+
|
|
265
|
+
// The off state must not read usage data at all.
|
|
266
|
+
if (!enabled) return hadOwn ? { messages } : undefined;
|
|
267
|
+
|
|
268
|
+
const startedAt = transition;
|
|
269
|
+
const knowledge = await load(ctx);
|
|
270
|
+
if (!enabled || transition !== startedAt) return hadOwn ? { messages } : undefined;
|
|
271
|
+
|
|
272
|
+
const credit = describeCredits(ctx)?.text?.trim();
|
|
273
|
+
const text = knowledge ? (credit ? `${knowledge}\n\n${credit}` : knowledge) : credit;
|
|
274
|
+
if (!text) return hadOwn ? { messages } : undefined;
|
|
275
|
+
showStatus(ctx, compactStatus(text));
|
|
276
|
+
|
|
277
|
+
// Ephemeral per-call projection only; never written to session history.
|
|
278
|
+
return {
|
|
279
|
+
messages: [
|
|
280
|
+
...messages,
|
|
281
|
+
{
|
|
282
|
+
role: "custom",
|
|
283
|
+
customType: CUSTOM_TYPE,
|
|
284
|
+
content: knowledge
|
|
285
|
+
? text
|
|
286
|
+
: `Usage awareness: current usage and quota knowledge is unavailable.\n\n${text}`,
|
|
287
|
+
display: false,
|
|
288
|
+
timestamp: Date.now(),
|
|
289
|
+
},
|
|
290
|
+
],
|
|
291
|
+
};
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
const resetSession = (_event: unknown, ctx: ExtensionContext): void => reset(ctx);
|
|
295
|
+
pi.on("session_start", resetSession);
|
|
296
|
+
pi.on("session_switch", resetSession);
|
|
297
|
+
pi.on("session_branch", resetSession);
|
|
298
|
+
|
|
299
|
+
// The context hook cannot see a threshold crossed by the final assistant response:
|
|
300
|
+
// there may be no next model call. Inspect the local ledger at settle, without
|
|
301
|
+
// provider quota reads. CreditBalances deduplicates a reminder it already emitted.
|
|
302
|
+
pi.on("agent_end", (_event, ctx) => {
|
|
303
|
+
if (!enabled) return;
|
|
304
|
+
describeCredits(ctx);
|
|
305
|
+
});
|
|
306
|
+
}
|