omp-superagent 0.1.7 → 0.1.8
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/DESIGN.md +21 -14
- package/README.ko.md +33 -15
- package/README.md +35 -14
- package/THIRD_PARTY_NOTICES.md +3 -3
- package/config.example.json +2 -1
- package/docs/OPERATIONS.md +232 -74
- package/docs/design/execution.md +54 -10
- package/docs/design/messaging.md +177 -43
- package/docs/discord-voice.md +8 -4
- package/docs/releases/0.1.8.md +21 -0
- package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
- package/gateway/bin/omp-gateway-darwin-x64 +0 -0
- package/gateway/bin/omp-gateway-linux-arm64 +0 -0
- package/gateway/bin/omp-gateway-linux-x64 +0 -0
- package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
- package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
- package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
- package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
- package/package.json +8 -8
- package/scripts/ci.ts +3 -3
- package/scripts/test-omp.sh +2 -1
- package/src/cli.ts +3 -0
- package/src/config.ts +5 -0
- package/src/contracts.ts +26 -5
- package/src/cron-jobs.ts +443 -19
- package/src/cron-pr-intake.ts +257 -0
- package/src/discord-markdown.ts +350 -123
- package/src/extension.ts +9 -1
- package/src/head-quota.ts +80 -0
- package/src/head-recovery.ts +40 -1
- package/src/host-extension.ts +120 -4
- package/src/host-protocol.ts +11 -0
- package/src/host-sdk-helper.ts +105 -10
- package/src/host.ts +111 -29
- package/src/installed-omp.ts +116 -4
- package/src/managed-ulw.ts +137 -24
- package/src/messenger-command-catalog.json +1 -1
- package/src/native-presets.ts +32 -5
- package/src/omp-usage.ts +254 -36
- package/src/pr-github.ts +4 -2
- package/src/pr-intake-automation.ts +316 -0
- package/src/pr-intake-comment.ts +226 -0
- package/src/pr-intake-fix.ts +233 -0
- package/src/pr-intake-github.ts +480 -0
- package/src/pr-intake-material.ts +230 -0
- package/src/pr-intake-mode.ts +59 -0
- package/src/pr-intake-review.ts +397 -0
- package/src/pr-intake-tree.ts +69 -0
- package/src/pr-intake-work.ts +29 -0
- package/src/runtime.ts +1504 -192
- package/src/store.ts +249 -49
- package/src/topic-history.ts +30 -17
package/src/native-presets.ts
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
|
+
import { homedir } from "node:os";
|
|
2
|
+
import { join, resolve } from "node:path";
|
|
1
3
|
import type { ExtensionContext } from "@oh-my-pi/pi-coding-agent";
|
|
4
|
+
import { getProjectAgentDir, MAIN_CONFIG_FILENAMES, normalizePathForComparison } from "@oh-my-pi/pi-utils/dirs";
|
|
2
5
|
import { IsStandardObject as isRecord } from "@sinclair/typebox/value";
|
|
3
6
|
import { acquireModelRoleMutation, getModelPreset, getModelPresetNames, isValidModelPresetName } from "@oh-my-pi/pi-coding-agent/config/model-presets";
|
|
4
7
|
import { pickDefaultAvailableModel, resolveModelRoleValue } from "@oh-my-pi/pi-coding-agent/config/model-resolver";
|
|
@@ -10,6 +13,7 @@ import { editNativeGlobalConfig, hasUnresolvedNativeLegacy, readNativeSettings }
|
|
|
10
13
|
|
|
11
14
|
export type NativeModel = Awaited<ReturnType<ExtensionContext["models"]["list"]>>[number];
|
|
12
15
|
export type BootstrapName = (typeof MODEL_PRESET_NAMES)[number];
|
|
16
|
+
export type PresetSyncOutcome = "applied" | "deferred";
|
|
13
17
|
type PresetSource = "runtime" | "overlay" | "project" | "global";
|
|
14
18
|
export type NativePresetChoices = Partial<Record<BootstrapName, { model: LaneModel; reason: string }>>;
|
|
15
19
|
const followingRoles = { high: "slow", middle: "default", low: "smol" } as const;
|
|
@@ -69,6 +73,24 @@ export class NativePresetManager {
|
|
|
69
73
|
this.source = settings;
|
|
70
74
|
}
|
|
71
75
|
|
|
76
|
+
watchedPaths(): string[] {
|
|
77
|
+
const agentDir = this.settings.getAgentDir();
|
|
78
|
+
const paths = [
|
|
79
|
+
...MAIN_CONFIG_FILENAMES.map(filename => join(agentDir, filename)),
|
|
80
|
+
join(agentDir, "settings.json"),
|
|
81
|
+
];
|
|
82
|
+
const cwd = resolve(this.settings.getCwd());
|
|
83
|
+
if (normalizePathForComparison(cwd) !== normalizePathForComparison(homedir())) {
|
|
84
|
+
const projectDir = getProjectAgentDir(cwd);
|
|
85
|
+
paths.push(
|
|
86
|
+
...MAIN_CONFIG_FILENAMES.map(filename => join(projectDir, filename)),
|
|
87
|
+
join(projectDir, "settings.json"),
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
paths.push(...this.settings.getConfigFiles());
|
|
91
|
+
return [...new Set(paths)];
|
|
92
|
+
}
|
|
93
|
+
|
|
72
94
|
private async reload(): Promise<void> {
|
|
73
95
|
await this.source.reloadFromDisk();
|
|
74
96
|
this.settings = await readNativeSettings(this.source);
|
|
@@ -167,11 +189,11 @@ export class NativePresetManager {
|
|
|
167
189
|
|
|
168
190
|
/** Follow persistent native roles without changing the active native session. */
|
|
169
191
|
async syncRoles(store: Pick<StorePort, "getMeta" | "setMeta">, canWrite: () => boolean,
|
|
170
|
-
reloadCatalog?: () => Promise<void>): Promise<
|
|
192
|
+
reloadCatalog?: () => Promise<void>): Promise<PresetSyncOutcome> {
|
|
171
193
|
const release = await acquireModelRoleMutation();
|
|
172
194
|
try {
|
|
173
195
|
await this.reload();
|
|
174
|
-
if (!canWrite()) return;
|
|
196
|
+
if (!canWrite()) return "deferred";
|
|
175
197
|
const settings = this.settings;
|
|
176
198
|
const base = this.capture();
|
|
177
199
|
const before = store.getMeta(followedPresets);
|
|
@@ -195,10 +217,10 @@ export class NativePresetManager {
|
|
|
195
217
|
}
|
|
196
218
|
const roles = JSON.stringify(resolved.map(({ selector, defaultSelector }) => [selector ?? null, defaultSelector]));
|
|
197
219
|
// A temporarily unavailable configured role is not a new policy.
|
|
198
|
-
if (resolved.some(({ selector, defaultSelector }) => selector && !defaultSelector)) return;
|
|
220
|
+
if (resolved.some(({ selector, defaultSelector }) => selector && !defaultSelector)) return "deferred";
|
|
199
221
|
const edits: { name: BootstrapName; snapshot: LanePresetSnapshot }[] = [];
|
|
200
222
|
for (const { name, model, defaultSelector } of resolved) {
|
|
201
|
-
if (!canWrite())
|
|
223
|
+
if (!canWrite()) return "deferred";
|
|
202
224
|
const tracked = ownership[name];
|
|
203
225
|
if (tracked === null) continue; // A manual edit/deletion releases management.
|
|
204
226
|
const owned = settings.getOwnedModelPreset(name);
|
|
@@ -228,16 +250,21 @@ export class NativePresetManager {
|
|
|
228
250
|
if (Bun.deepEquals(preset, next)) ownership[name] = { preset, roles };
|
|
229
251
|
else edits.push({ name, snapshot: next });
|
|
230
252
|
}
|
|
253
|
+
let deferred = false;
|
|
231
254
|
if (edits.length) {
|
|
232
255
|
const applied = await editNativeGlobalConfig(settings, edits.map(({ name, snapshot }) => ({
|
|
233
256
|
path: `modelPresets.${name}`, value: snapshot,
|
|
234
257
|
})), actual => canWrite() && edits.every(({ name }) => actual.getOwnedModelPreset(name)?.source === "global")
|
|
235
258
|
&& Bun.deepEquals(actual.getModelRoles(), base.modelRoles)
|
|
236
259
|
&& cfgDefaultThinkingLevel.get(actual) === base.defaultThinkingLevel);
|
|
237
|
-
for (const [index, { name, snapshot }] of edits.entries())
|
|
260
|
+
for (const [index, { name, snapshot }] of edits.entries()) {
|
|
261
|
+
if (applied[index]) ownership[name] = { preset: snapshot, roles };
|
|
262
|
+
else deferred = true;
|
|
263
|
+
}
|
|
238
264
|
}
|
|
239
265
|
const saved = JSON.stringify(ownership);
|
|
240
266
|
if (saved !== (before ?? "{}")) store.setMeta(followedPresets, saved);
|
|
267
|
+
return deferred ? "deferred" : "applied";
|
|
241
268
|
} finally { release(); }
|
|
242
269
|
}
|
|
243
270
|
|
package/src/omp-usage.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { createHmac } from "node:crypto";
|
|
2
|
+
import { delimiter } from "node:path";
|
|
1
3
|
import { extractProfileFlags } from "@oh-my-pi/pi-coding-agent/cli/profile-bootstrap";
|
|
2
4
|
import { Type, type Static } from "@sinclair/typebox/type";
|
|
3
5
|
import { Value } from "@sinclair/typebox/value";
|
|
@@ -5,6 +7,18 @@ import { credentialEnvNames, type Config } from "./config";
|
|
|
5
7
|
|
|
6
8
|
// Parse only fields used from the CLI JSON. The stock extension loader does not
|
|
7
9
|
// resolve the SDK usage module's internal omptype import.
|
|
10
|
+
const scopeIdentityFields = {
|
|
11
|
+
accountId: Type.Optional(Type.Unknown()),
|
|
12
|
+
projectId: Type.Optional(Type.Unknown()),
|
|
13
|
+
orgId: Type.Optional(Type.Unknown()),
|
|
14
|
+
};
|
|
15
|
+
const identityFields = {
|
|
16
|
+
...scopeIdentityFields,
|
|
17
|
+
email: Type.Optional(Type.Unknown()),
|
|
18
|
+
orgName: Type.Optional(Type.Unknown()),
|
|
19
|
+
};
|
|
20
|
+
const identitySchema = Type.Object(identityFields);
|
|
21
|
+
const accountSchema = Type.Object({ provider: Type.String(), ...identityFields });
|
|
8
22
|
const limitSchema = Type.Object({
|
|
9
23
|
label: Type.String(),
|
|
10
24
|
amount: Type.Object({
|
|
@@ -21,30 +35,37 @@ const limitSchema = Type.Object({
|
|
|
21
35
|
resetsAt: Type.Optional(Type.Number()),
|
|
22
36
|
resetLabel: Type.Optional(Type.String()),
|
|
23
37
|
})),
|
|
38
|
+
scope: Type.Optional(Type.Object(scopeIdentityFields)),
|
|
24
39
|
status: Type.Optional(Type.String()),
|
|
25
40
|
});
|
|
26
41
|
const responseSchema = Type.Object({
|
|
27
42
|
generatedAt: Type.Optional(Type.Number()),
|
|
28
|
-
reports: Type.Array(Type.Object({
|
|
29
|
-
|
|
30
|
-
|
|
43
|
+
reports: Type.Array(Type.Object({
|
|
44
|
+
provider: Type.String(),
|
|
45
|
+
limits: Type.Array(limitSchema),
|
|
46
|
+
metadata: Type.Optional(identitySchema),
|
|
47
|
+
})),
|
|
48
|
+
accountsWithoutUsage: Type.Optional(Type.Array(accountSchema)),
|
|
49
|
+
disabledCredentials: Type.Optional(Type.Array(accountSchema)),
|
|
31
50
|
});
|
|
32
51
|
const number = new Intl.NumberFormat("en-US", { maximumFractionDigits: 1 });
|
|
33
52
|
const resetDay = new Intl.DateTimeFormat("ko-KR", { month: "numeric", day: "numeric", weekday: "short" });
|
|
34
53
|
const resetTime = new Intl.DateTimeFormat("ko-KR", { hour: "2-digit", minute: "2-digit", hourCycle: "h23" });
|
|
54
|
+
const quotaUnits = new Set(["tokens", "requests", "credits", "usd", "minutes", "bytes"]);
|
|
55
|
+
const quotaWindows = new Map([["5h", "5시간"], ["24h", "일간"], ["1d", "일간"], ["daily", "일간"],
|
|
56
|
+
["7d", "주간"], ["weekly", "주간"], ["30d", "월간"], ["monthly", "월간"]]);
|
|
57
|
+
const publicMeters = new Map([
|
|
58
|
+
["All models", "All models"], ["Credits", "Credits"], ["Claude Extra Usage", "Extra Usage"],
|
|
59
|
+
["Claude 7 Day (Opus)", "Opus"], ["Claude 7 Day (Sonnet)", "Sonnet"], ["Claude 7 Day (Fable)", "Fable"],
|
|
60
|
+
]);
|
|
35
61
|
|
|
36
|
-
function limitLine(limit: Static<typeof limitSchema>, today: string): string {
|
|
62
|
+
function limitLine(limit: Static<typeof limitSchema>, today: string, index: number): string {
|
|
37
63
|
const { amount, label, window } = limit;
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
const index = labelWithoutProvider.toLowerCase().indexOf(windowLabel.toLowerCase());
|
|
44
|
-
name = index >= 0
|
|
45
|
-
? `${labelWithoutProvider.slice(0, index)}${shortWindow}${labelWithoutProvider.slice(index + windowLabel.length)}`
|
|
46
|
-
: `${shortWindow} (${labelWithoutProvider})`;
|
|
47
|
-
}
|
|
64
|
+
// Native redaction does not cover provider-controlled display labels. Render
|
|
65
|
+
// only known meter categories or a numbered bucket, never provider free text.
|
|
66
|
+
const period = window && quotaWindows.get(window.id);
|
|
67
|
+
const meter = publicMeters.get(label);
|
|
68
|
+
const name = period && meter ? `${period} (${meter})` : period ?? meter ?? `사용량 항목 ${index + 1}`;
|
|
48
69
|
const remaining = amount.remaining ?? (amount.limit !== undefined && amount.used !== undefined
|
|
49
70
|
? Math.max(0, amount.limit - amount.used) : undefined);
|
|
50
71
|
let fraction = amount.remainingFraction;
|
|
@@ -58,7 +79,7 @@ function limitLine(limit: Static<typeof limitSchema>, today: string): string {
|
|
|
58
79
|
}
|
|
59
80
|
const parts: string[] = [];
|
|
60
81
|
if (fraction !== undefined && Number.isFinite(fraction)) parts.push(`${number.format(Math.max(0, fraction) * 100)}% 남음`);
|
|
61
|
-
if (remaining !== undefined &&
|
|
82
|
+
if (remaining !== undefined && quotaUnits.has(amount.unit)) {
|
|
62
83
|
parts.push(`${number.format(remaining)} ${amount.unit} 남음`);
|
|
63
84
|
}
|
|
64
85
|
if (limit.status === "exhausted") parts.push("한도 도달");
|
|
@@ -73,44 +94,241 @@ function limitLine(limit: Static<typeof limitSchema>, today: string): string {
|
|
|
73
94
|
return `• ${name} ${parts.join(" · ")}`;
|
|
74
95
|
}
|
|
75
96
|
|
|
76
|
-
|
|
77
|
-
|
|
97
|
+
async function runUsageCli(
|
|
98
|
+
config: Config,
|
|
99
|
+
invocation: { readonly args: readonly string[]; readonly timeout?: number; readonly captureReceipt?: boolean },
|
|
100
|
+
environment: NodeJS.ProcessEnv,
|
|
101
|
+
) {
|
|
78
102
|
const [executable, ...launchArgs] = config.command;
|
|
79
103
|
if (!executable) throw new Error("No configured OMP executable");
|
|
80
|
-
const { profile } = extractProfileFlags(launchArgs);
|
|
104
|
+
const { profile, argv } = extractProfileFlags(launchArgs);
|
|
105
|
+
const extensionFlags: string[] = [];
|
|
81
106
|
const env = { ...environment };
|
|
107
|
+
if (invocation.args[0] !== "--help") {
|
|
108
|
+
const { parseArgs } = await import("@oh-my-pi/pi-coding-agent/cli/args");
|
|
109
|
+
const { noExtensions, extensions, hooks, config: overlays, trustedExtensions } = parseArgs(argv);
|
|
110
|
+
if (trustedExtensions?.length) throw new Error("OMP usage does not expose trusted-extension mode");
|
|
111
|
+
// Stock usage loads overlays through PI_CONFIG_FILES. Native Settings
|
|
112
|
+
// applies inherited paths first, then --config paths in argument order.
|
|
113
|
+
if (overlays?.length) {
|
|
114
|
+
if (overlays.some(path => path.includes(delimiter))) throw new Error("OMP usage cannot encode a configured overlay path");
|
|
115
|
+
env.PI_CONFIG_FILES = [env.PI_CONFIG_FILES, ...overlays].filter(Boolean).join(delimiter);
|
|
116
|
+
}
|
|
117
|
+
if (noExtensions) extensionFlags.push("--no-extensions");
|
|
118
|
+
for (const path of [...(extensions ?? []), ...(hooks ?? [])]) extensionFlags.push(`--extension=${path}`);
|
|
119
|
+
}
|
|
82
120
|
for (const name of credentialEnvNames(config)) delete env[name];
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
cwd: config.headCwd, env, stdin: "ignore", stdout: "pipe", stderr: "
|
|
121
|
+
delete env.OMP_SUPERAGENT_GATEWAY_TOKEN;
|
|
122
|
+
const child = Bun.spawn([executable, ...(profile ? [`--profile=${profile}`] : []), "usage", ...invocation.args, ...extensionFlags], {
|
|
123
|
+
cwd: config.headCwd, env, stdin: "ignore", stdout: "pipe", stderr: invocation.captureReceipt ? "pipe" : "ignore",
|
|
124
|
+
timeout: invocation.timeout ?? 30_000, killSignal: "SIGKILL",
|
|
86
125
|
});
|
|
87
|
-
const [stdout, code] = await Promise.all([new Response(child.stdout).text(), child.exited
|
|
126
|
+
const [stdout, code, stderr] = await Promise.all([new Response(child.stdout).text(), child.exited,
|
|
127
|
+
child.stderr ? new Response(child.stderr).text() : ""]);
|
|
128
|
+
return { stdout, code, stderr };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function usageAccountLabel(
|
|
132
|
+
identity: Static<typeof identitySchema> | undefined,
|
|
133
|
+
limits: readonly Static<typeof limitSchema>[] = [],
|
|
134
|
+
): string {
|
|
135
|
+
// Accept only short OMP redaction masks, not raw emails, markup or provider diagnostics.
|
|
136
|
+
const mask = (value: unknown) => typeof value === "string"
|
|
137
|
+
&& /^[\p{L}\p{M}\p{N} ._+-]{1,12}\*(?:[\p{L}\p{M}\p{N} ._+-]{1,12}\*)?$/u.test(value)
|
|
138
|
+
? value.replaceAll("*", "…") : undefined;
|
|
139
|
+
const scopeMask = (key: keyof typeof scopeIdentityFields) => {
|
|
140
|
+
const scoped = new Set(limits.map(limit => limit.scope?.[key]).filter(value => value != null));
|
|
141
|
+
return scoped.size === 1 ? mask(scoped.values().next().value) : undefined;
|
|
142
|
+
};
|
|
143
|
+
const name = mask(identity?.email) ?? mask(identity?.accountId) ?? mask(identity?.projectId)
|
|
144
|
+
?? scopeMask("accountId") ?? scopeMask("projectId");
|
|
145
|
+
const organization = mask(identity?.orgName) ?? mask(identity?.orgId) ?? scopeMask("orgId");
|
|
146
|
+
return [name, organization === name ? undefined : organization].filter(Boolean).join(" / ");
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Use the configured stock OMP's profile and publish only the quota projection. */
|
|
150
|
+
export async function readOmpUsage(config: Config, environment: NodeJS.ProcessEnv = process.env): Promise<string> {
|
|
151
|
+
const { stdout, code } = await runUsageCli(config, { args: ["--json", "--redact"] }, environment);
|
|
88
152
|
if (code !== 0) throw new Error(`OMP usage exited with code ${code}`);
|
|
89
|
-
const response
|
|
153
|
+
const response = usageJson(stdout);
|
|
90
154
|
if (!Value.Check(responseSchema, response)) throw new Error("Unsupported OMP usage response");
|
|
91
155
|
|
|
92
156
|
const today = new Date(response.generatedAt ?? Date.now()).toDateString();
|
|
93
|
-
const accounts = new Map<string, string[][]>();
|
|
94
|
-
const addAccount = (provider: string, lines: string[]) => {
|
|
157
|
+
const accounts = new Map<string, { readonly label: string; readonly lines: readonly string[] }[]>();
|
|
158
|
+
const addAccount = (provider: string, label: string, lines: string[]) => {
|
|
95
159
|
const entries = accounts.get(provider) ?? [];
|
|
96
|
-
entries.push(lines);
|
|
160
|
+
entries.push({ label, lines });
|
|
97
161
|
accounts.set(provider, entries);
|
|
98
162
|
};
|
|
99
163
|
for (const report of response.reports) {
|
|
100
|
-
addAccount(report.provider, report.limits.length
|
|
101
|
-
? report.limits.map(limit => limitLine(limit, today)) : ["• 남은 한도 미확인"]);
|
|
164
|
+
addAccount(report.provider, usageAccountLabel(report.metadata, report.limits), report.limits.length
|
|
165
|
+
? report.limits.map((limit, index) => limitLine(limit, today, index)) : ["• 남은 한도 미확인"]);
|
|
102
166
|
}
|
|
103
|
-
for (const
|
|
104
|
-
addAccount(provider, ["• 남은 한도 미확인"]);
|
|
167
|
+
for (const account of response.accountsWithoutUsage ?? []) {
|
|
168
|
+
addAccount(account.provider, usageAccountLabel(account), ["• 남은 한도 미확인"]);
|
|
105
169
|
}
|
|
106
|
-
for (const
|
|
107
|
-
addAccount(provider, ["• 계정 비활성화됨"]);
|
|
170
|
+
for (const account of response.disabledCredentials ?? []) {
|
|
171
|
+
addAccount(account.provider, usageAccountLabel(account), ["• 계정 비활성화됨"]);
|
|
108
172
|
}
|
|
109
173
|
if (!accounts.size) return "OMP 사용량\n\n설정된 OMP 프로필에서 보고된 계정 한도가 없습니다.";
|
|
110
|
-
const sections = [...accounts].flatMap(([provider, entries]) => {
|
|
111
|
-
const name = provider === "openai-codex" ? "Codex" : provider === "anthropic" ? "Claude"
|
|
112
|
-
|
|
113
|
-
|
|
174
|
+
const sections = [...accounts].flatMap(([provider, entries], providerIndex) => {
|
|
175
|
+
const name = provider === "openai-codex" ? "Codex" : provider === "anthropic" ? "Claude"
|
|
176
|
+
: /^[a-z0-9][a-z0-9_-]{0,63}$/i.test(provider) ? provider : `OMP 제공자 ${providerIndex + 1}`;
|
|
177
|
+
return entries.map(({ label, lines }, index) =>
|
|
178
|
+
[[name, entries.length > 1 ? `계정 ${index + 1}` : "", label].filter(Boolean).join(" · "), ...lines].join("\n"));
|
|
114
179
|
});
|
|
115
180
|
return `OMP 사용량 · ${resetTime.resolvedOptions().timeZone}\n\n${sections.join("\n\n")}`;
|
|
116
181
|
}
|
|
182
|
+
|
|
183
|
+
function usageJson(stdout: string): unknown {
|
|
184
|
+
try { return JSON.parse(stdout); }
|
|
185
|
+
catch { throw new Error("Invalid JSON from OMP usage"); }
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function resetNameHint(value: string | undefined): string | undefined {
|
|
189
|
+
// Show at most two letters or numbers, and never the whole name or email.
|
|
190
|
+
const characters = Array.from(value?.trim() ?? "");
|
|
191
|
+
const prefix = characters.slice(0, Math.min(2, characters.length - 1)).join("");
|
|
192
|
+
return /^[\p{L}\p{N}]{1,2}$/u.test(prefix) ? `${prefix}…` : undefined;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const count = Type.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER });
|
|
196
|
+
const resetAccountsSchema = Type.Object({
|
|
197
|
+
accounts: Type.Array(Type.Object({
|
|
198
|
+
provider: Type.Union([Type.Literal("openai-codex"), Type.Literal("anthropic")]),
|
|
199
|
+
credentialId: Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER }),
|
|
200
|
+
availableCount: count,
|
|
201
|
+
redeemableCount: count,
|
|
202
|
+
nextCreditId: Type.Optional(Type.String()),
|
|
203
|
+
accountId: Type.Optional(Type.String()),
|
|
204
|
+
email: Type.Optional(Type.String()),
|
|
205
|
+
orgId: Type.Optional(Type.String()),
|
|
206
|
+
orgName: Type.Optional(Type.String()),
|
|
207
|
+
error: Type.Optional(Type.String()),
|
|
208
|
+
credits: Type.Array(Type.Object({
|
|
209
|
+
id: Type.Optional(Type.String()),
|
|
210
|
+
status: Type.Optional(Type.String()),
|
|
211
|
+
expiresAt: Type.Optional(Type.String()),
|
|
212
|
+
})),
|
|
213
|
+
})),
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
type ResetIdentity = Readonly<{ account?: string; email?: string; organization?: string }>;
|
|
217
|
+
|
|
218
|
+
export interface OmpResetAccount {
|
|
219
|
+
/** The public CLI's exact provider and local credential row selector, not a provider identity. */
|
|
220
|
+
readonly target: string;
|
|
221
|
+
readonly label: string;
|
|
222
|
+
readonly availableCount: number;
|
|
223
|
+
readonly redeemableCount: number;
|
|
224
|
+
readonly unavailable: boolean;
|
|
225
|
+
/** Stable across credential row replacement; never contains a printable account ID. */
|
|
226
|
+
readonly identity: ResetIdentity | null;
|
|
227
|
+
readonly offer: string;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
export class OmpResetUnsupported extends Error {}
|
|
231
|
+
|
|
232
|
+
export function couldMatchResetAccount(
|
|
233
|
+
previous: Pick<OmpResetAccount, "target" | "identity">,
|
|
234
|
+
current: Pick<OmpResetAccount, "target" | "identity">,
|
|
235
|
+
): boolean {
|
|
236
|
+
if (previous.target === current.target) return true;
|
|
237
|
+
const provider = previous.target.split("/", 1)[0];
|
|
238
|
+
if (current.target.split("/", 1)[0] !== provider) return false;
|
|
239
|
+
const a = previous.identity;
|
|
240
|
+
const b = current.identity;
|
|
241
|
+
if (!a || !b) return true;
|
|
242
|
+
if (a.organization && b.organization && a.organization !== b.organization) return false;
|
|
243
|
+
if (a.email && b.email && a.email === b.email) return true;
|
|
244
|
+
// Codex can share an upstream account lock across logins in a workspace.
|
|
245
|
+
if (a.account && b.account) return a.account === b.account;
|
|
246
|
+
if (a.email && b.email) return false;
|
|
247
|
+
// No overlapping fields that separate these accounts. Hold rather than
|
|
248
|
+
// spending again on a possible re-login with more or less identity metadata.
|
|
249
|
+
return true;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** Inspect the public installed CLI, not the SDK pin; a quota report is not a reset balance. */
|
|
253
|
+
export async function listOmpUsageResets(
|
|
254
|
+
config: Config, identityKey: string, environment: NodeJS.ProcessEnv = process.env,
|
|
255
|
+
): Promise<readonly OmpResetAccount[]> {
|
|
256
|
+
const help = await runUsageCli(config, { args: ["--help"] }, environment);
|
|
257
|
+
if (help.code !== 0) throw new Error("OMP usage help unavailable");
|
|
258
|
+
if (!/\busage\s+\[ACTION\]\s+\[TARGET\]/.test(help.stdout) ||
|
|
259
|
+
!/\busage reset\s+(?:codex|openai-codex|anthropic|claude)\/\d+\b/.test(help.stdout))
|
|
260
|
+
throw new OmpResetUnsupported("Installed OMP does not advertise exact-account usage reset");
|
|
261
|
+
// Native redaction aliases depend on which other accounts are present. Derive
|
|
262
|
+
// the stable fence from native identities in memory before returning any rows.
|
|
263
|
+
const { stdout, code } = await runUsageCli(config, { args: ["reset", "--json"] }, environment);
|
|
264
|
+
if (code !== 0) throw new Error("OMP saved resets unavailable");
|
|
265
|
+
const result = usageJson(stdout);
|
|
266
|
+
if (!Value.Check(resetAccountsSchema, result)) throw new Error("Unsupported OMP saved reset response");
|
|
267
|
+
const seen = new Set<string>();
|
|
268
|
+
const fingerprint = (values: readonly unknown[]) => createHmac("sha256", identityKey)
|
|
269
|
+
.update(JSON.stringify(values)).digest("hex");
|
|
270
|
+
return result.accounts.map(row => {
|
|
271
|
+
const target = `${row.provider}/${row.credentialId}`;
|
|
272
|
+
if (seen.has(target) || row.redeemableCount > row.availableCount) throw new Error("Inconsistent OMP saved reset response");
|
|
273
|
+
seen.add(target);
|
|
274
|
+
const hashAlias = (kind: string, value?: string) => {
|
|
275
|
+
const normalized = value?.trim().toLowerCase();
|
|
276
|
+
return normalized ? fingerprint([row.provider, kind, normalized]) : undefined;
|
|
277
|
+
};
|
|
278
|
+
const identity = (row.accountId ?? row.email)?.trim() ? {
|
|
279
|
+
account: hashAlias("account", row.accountId),
|
|
280
|
+
email: hashAlias("email", row.email),
|
|
281
|
+
organization: hashAlias("organization", row.orgId),
|
|
282
|
+
} : null;
|
|
283
|
+
const name = resetNameHint(row.email?.split("@", 1)[0]) ?? resetNameHint(row.orgName);
|
|
284
|
+
return {
|
|
285
|
+
target,
|
|
286
|
+
label: [row.provider === "openai-codex" ? "Codex" : "Claude", `계정 #${row.credentialId}`, name].filter(Boolean).join(" · "),
|
|
287
|
+
availableCount: row.availableCount,
|
|
288
|
+
redeemableCount: row.redeemableCount,
|
|
289
|
+
// Native refuses to spend without an account identity for its cross-process fence.
|
|
290
|
+
unavailable: row.error !== undefined || row.redeemableCount > 0 && identity === null,
|
|
291
|
+
identity,
|
|
292
|
+
// Match an unchanged offer before handoff without retaining provider identities or credit IDs.
|
|
293
|
+
offer: fingerprint([
|
|
294
|
+
identity, row.nextCreditId, row.availableCount, row.redeemableCount,
|
|
295
|
+
row.credits.map(credit => JSON.stringify([credit.id, credit.status, credit.expiresAt])).sort(),
|
|
296
|
+
]),
|
|
297
|
+
};
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** Only the caller's already durably claimed confirmation can invoke this one-shot CLI. */
|
|
302
|
+
export async function redeemOmpUsageReset(
|
|
303
|
+
config: Config, account: OmpResetAccount, environment: NodeJS.ProcessEnv = process.env,
|
|
304
|
+
): Promise<"reset" | "refused" | "unconfirmed"> {
|
|
305
|
+
if (!/^(?:openai-codex|anthropic)\/[1-9]\d*$/.test(account.target))
|
|
306
|
+
throw new Error("Invalid exact OMP saved reset target");
|
|
307
|
+
// Native lists, takes the provider/account fence, then attempts one spend.
|
|
308
|
+
// Its mutating form has a human receipt, not a JSON response body.
|
|
309
|
+
const { stdout, stderr, code } = await runUsageCli(config, {
|
|
310
|
+
args: ["reset", account.target, "--redact"], timeout: 60_000, captureReceipt: true,
|
|
311
|
+
}, environment);
|
|
312
|
+
const provider = account.target.startsWith("anthropic/") ? "Claude" : "Codex";
|
|
313
|
+
if (code === 0 && /^Reset applied for .+ \((Claude|Codex)\) — .+\.$/.exec(stdout.trim())?.[1] === provider)
|
|
314
|
+
return "reset";
|
|
315
|
+
if (code === 1 && !stdout) {
|
|
316
|
+
const line = stderr.replace(/\x1b\[[\d;]*m/g, "").trim();
|
|
317
|
+
// Split at the first native boundary before examining the reason.
|
|
318
|
+
// Unconfirmed receipts may carry arbitrary provider text after it.
|
|
319
|
+
const boundary = /^.{1,400}? (?:\((Claude|Codex)\)|\[(Claude|Codex)\]): /.exec(line);
|
|
320
|
+
if (boundary) {
|
|
321
|
+
const reason = line.slice(boundary[0].length);
|
|
322
|
+
if (boundary[1] === provider && (
|
|
323
|
+
reason === "nothing to reset right now — your covered limits aren't constrained, so no credit was spent."
|
|
324
|
+
|| reason === "the reset offer changed — nothing was spent; reopen /usage reset."
|
|
325
|
+
|| reason === "that reset was already redeemed."
|
|
326
|
+
|| reason === "couldn't load this account's saved resets (network/auth) — nothing was spent, try again."
|
|
327
|
+
|| /^another omp process (?:spent a saved reset on this account .+ ago, so this one was not spent\. Check `omp usage` before spending another|started spending a saved reset on this account .+ ago, so nothing was spent\. Try again in a minute)\.$/.test(reason)
|
|
328
|
+
)) return "refused";
|
|
329
|
+
if (boundary[2] === provider && /^(?:saved resets unavailable \(.+\), so nothing was spent|no saved resets usable right now(?: \(.+\))?)\.$/.test(reason))
|
|
330
|
+
return "refused";
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
return "unconfirmed";
|
|
334
|
+
}
|
package/src/pr-github.ts
CHANGED
|
@@ -43,12 +43,12 @@ export function prKey(ref: PrRef): string {
|
|
|
43
43
|
return `${parsed.owner}/${parsed.repo}#${parsed.number}`;
|
|
44
44
|
}
|
|
45
45
|
|
|
46
|
-
async function api<T extends TSchema>(endpoint: string, schema: T, signal: AbortSignal): Promise<Static<T>> {
|
|
46
|
+
async function api<T extends TSchema>(endpoint: string, schema: T, signal: AbortSignal, env?: NodeJS.ProcessEnv): Promise<Static<T>> {
|
|
47
47
|
if (signal.aborted) throw new PrReadError("aborted");
|
|
48
48
|
const output = await new Promise<string>((resolve, reject) => {
|
|
49
49
|
execFile("gh", ["api", "--hostname", "github.com", "--method", "GET", "--paginate", "--slurp",
|
|
50
50
|
"--header", "Accept: application/vnd.github+json", endpoint],
|
|
51
|
-
{ encoding: "utf8", timeout: 30_000, maxBuffer: 16 * 1024 * 1024, signal }, (error, stdout) => {
|
|
51
|
+
{ encoding: "utf8", timeout: 30_000, maxBuffer: 16 * 1024 * 1024, signal, env }, (error, stdout) => {
|
|
52
52
|
if (error) reject(new PrReadError(signal.aborted ? "aborted" : "request"));
|
|
53
53
|
else resolve(stdout);
|
|
54
54
|
});
|
|
@@ -57,6 +57,8 @@ async function api<T extends TSchema>(endpoint: string, schema: T, signal: Abort
|
|
|
57
57
|
return parseWire(schema, output);
|
|
58
58
|
}
|
|
59
59
|
|
|
60
|
+
export { api as readGitHubApi };
|
|
61
|
+
|
|
60
62
|
function fingerprint(value: unknown): string {
|
|
61
63
|
return createHash("sha256").update(JSON.stringify(value)).digest("hex").slice(0, 24);
|
|
62
64
|
}
|