omp-superagent 0.1.7 → 0.1.9
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 +27 -16
- package/README.ko.md +40 -19
- package/README.md +43 -18
- package/THIRD_PARTY_NOTICES.md +11 -11
- package/config.example.json +2 -1
- package/docs/OPERATIONS.md +285 -85
- package/docs/design/execution.md +133 -24
- package/docs/design/messaging.md +235 -50
- package/docs/discord-voice.md +8 -4
- package/docs/releases/0.1.8.md +21 -0
- package/docs/releases/0.1.9.md +18 -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/notices/darwin-arm64/Cargo-LICENSES.txt +2 -0
- package/host-owner/bin/notices/darwin-arm64/Cargo-SOURCES.txt +2 -0
- package/host-owner/bin/notices/darwin-arm64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
- package/host-owner/bin/notices/darwin-arm64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
- package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/COPYRIGHT +29 -0
- package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
- package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
- package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
- package/host-owner/bin/notices/darwin-x64/Cargo-LICENSES.txt +2 -0
- package/host-owner/bin/notices/darwin-x64/Cargo-SOURCES.txt +2 -0
- package/host-owner/bin/notices/darwin-x64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
- package/host-owner/bin/notices/darwin-x64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
- package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/COPYRIGHT +29 -0
- package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
- package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
- package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
- package/host-owner/bin/notices/linux-arm64/Cargo-LICENSES.txt +3 -0
- package/host-owner/bin/notices/linux-arm64/Cargo-SOURCES.txt +3 -0
- package/host-owner/bin/notices/linux-arm64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
- package/host-owner/bin/notices/linux-arm64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
- package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/COPYRIGHT +29 -0
- package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/LICENSE-APACHE +201 -0
- package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
- package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/LICENSE-MIT +23 -0
- package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/COPYRIGHT +29 -0
- package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
- package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
- package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
- package/host-owner/bin/notices/linux-x64/Cargo-LICENSES.txt +3 -0
- package/host-owner/bin/notices/linux-x64/Cargo-SOURCES.txt +3 -0
- package/host-owner/bin/notices/linux-x64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
- package/host-owner/bin/notices/linux-x64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
- package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/COPYRIGHT +29 -0
- package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/LICENSE-APACHE +201 -0
- package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
- package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/LICENSE-MIT +23 -0
- package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/COPYRIGHT +29 -0
- package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
- package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
- package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/LICENSE-MIT +23 -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 +17 -15
- package/skills/head/SKILL.md +3 -11
- package/skills/head/references/routing.md +23 -17
- package/skills/head/references/supervision.md +13 -1
- package/skills/lane/references/workflow.md +8 -8
- package/src/cli.ts +6 -3
- package/src/config.ts +5 -0
- package/src/contracts.ts +95 -10
- package/src/cron-jobs.ts +443 -19
- package/src/cron-pr-intake.ts +257 -0
- package/src/discord-command-registration.ts +34 -186
- package/src/extension.ts +31 -3
- package/src/gateway-client.ts +11 -59
- package/src/gateway-protocol.ts +35 -1
- package/src/head-quota.ts +80 -0
- package/src/head-recovery.ts +249 -1
- package/src/host-extension.ts +194 -5
- package/src/host-protocol.ts +16 -9
- package/src/host-sdk-helper.ts +105 -10
- package/src/host.ts +111 -29
- package/src/installed-omp.ts +116 -4
- package/src/lane-models.ts +8 -0
- package/src/managed-ulw-probe.ts +22 -20
- package/src/managed-ulw.ts +137 -24
- package/src/messenger-command-catalog.json +6 -3
- package/src/messenger-commands.ts +9 -2
- package/src/native-presets.ts +32 -5
- package/src/omp-usage.ts +254 -36
- package/src/operator.ts +77 -0
- package/src/pr-github-schema.ts +2 -0
- package/src/pr-github.ts +4 -2
- package/src/pr-intake-automation.ts +315 -0
- package/src/pr-intake-comment.ts +225 -0
- package/src/pr-intake-fix.ts +232 -0
- package/src/pr-intake-github.ts +479 -0
- package/src/pr-intake-material.ts +229 -0
- package/src/pr-intake-mode.ts +59 -0
- package/src/pr-intake-review.ts +397 -0
- package/src/pr-intake-tree.ts +68 -0
- package/src/pr-intake-work.ts +29 -0
- package/src/pr-review-models.ts +28 -0
- package/src/result-attachment.ts +60 -79
- package/src/runtime.ts +2968 -449
- package/src/setup-profiles.ts +26 -65
- package/src/slack-command-registration.ts +48 -197
- package/src/store.ts +507 -87
- package/src/superkit-skills.ts +22 -0
- package/src/telegram-command-languages.json +17 -0
- package/src/telegram-command-registration.ts +32 -134
- package/src/topic-history.ts +30 -17
- package/src/worker-bridge.ts +21 -0
- package/src/worker-enrollment.ts +2 -1
- package/src/worker-host.ts +0 -24
- package/src/worker-serve-prepare.ts +19 -0
- package/src/worker-service.ts +51 -47
- package/scripts/ci.ts +0 -44
- package/scripts/release.ts +0 -112
- package/scripts/test-omp.sh +0 -43
- package/src/discord-commands.ts +0 -29
- package/src/discord-markdown.ts +0 -172
- package/src/slack-commands.ts +0 -18
- package/src/telegram-signal.ts +0 -14
- package/src/worker-stdio.ts +0 -61
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/operator.ts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { addAbortListener } from "node:events";
|
|
2
|
+
import { requireGateway } from "./gateway-native";
|
|
3
|
+
import { readCredentialFile, validateCredential } from "./credentials";
|
|
4
|
+
|
|
5
|
+
type Credentials = { readonly bot: string; readonly manifest?: string };
|
|
6
|
+
export type OperatorRun = <T>(operation: string, request: unknown, credentials: Credentials, signal?: AbortSignal) => Promise<T>;
|
|
7
|
+
|
|
8
|
+
export class OperatorStartError extends Error {
|
|
9
|
+
constructor() { super("Could not start the native operator; no mutation was attempted."); }
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function operatorBotToken(platform: "Discord" | "Telegram", configPath: string, tokenEnv: string): string {
|
|
13
|
+
const explicit = process.env[tokenEnv];
|
|
14
|
+
let stored: string | undefined;
|
|
15
|
+
try {
|
|
16
|
+
// Validate the sibling's ownership even when an explicit environment value wins.
|
|
17
|
+
stored = readCredentialFile(configPath)?.values[tokenEnv];
|
|
18
|
+
if (!explicit && stored) validateCredential(stored);
|
|
19
|
+
} catch { throw new Error(`Cannot safely load the configured ${platform} credential; details suppressed`); }
|
|
20
|
+
if (explicit) {
|
|
21
|
+
try { validateCredential(explicit); }
|
|
22
|
+
catch { throw new Error(`Configured ${platform} credential is invalid; value suppressed`); }
|
|
23
|
+
return explicit;
|
|
24
|
+
}
|
|
25
|
+
if (!stored) throw new Error(`Configured ${platform} credential is missing`);
|
|
26
|
+
return stored;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Run only the selected operation's credentials through the child's private environment. */
|
|
30
|
+
export async function invokeOperator<T>(argv: string[], request: unknown, credentials: Credentials, signal?: AbortSignal): Promise<T> {
|
|
31
|
+
let child: Bun.Subprocess<"pipe", "pipe", "ignore">;
|
|
32
|
+
let frame: string;
|
|
33
|
+
try {
|
|
34
|
+
if (signal?.aborted) throw new OperatorStartError();
|
|
35
|
+
frame = `${JSON.stringify(request)}\n`;
|
|
36
|
+
if (signal?.aborted) throw new OperatorStartError();
|
|
37
|
+
child = Bun.spawn(argv, {
|
|
38
|
+
env: { OMP_SA_OPERATOR_PARENT: String(process.pid), OMP_SA_OPERATOR_BOT: credentials.bot,
|
|
39
|
+
...(credentials.manifest !== undefined && { OMP_SA_OPERATOR_MANIFEST: credentials.manifest }) },
|
|
40
|
+
stdin: "pipe", stdout: "pipe", stderr: "ignore",
|
|
41
|
+
});
|
|
42
|
+
} catch {
|
|
43
|
+
throw new OperatorStartError();
|
|
44
|
+
}
|
|
45
|
+
const uncertain = "No authoritative operator receipt. A requested change may have reached the platform; inspect before retrying.";
|
|
46
|
+
const stop = () => {
|
|
47
|
+
if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
|
|
48
|
+
};
|
|
49
|
+
using abortListener = signal && addAbortListener(signal, stop);
|
|
50
|
+
if (signal?.aborted) stop();
|
|
51
|
+
const send = async () => {
|
|
52
|
+
// Keep the writer open after this frame. EOF is a parent-lifetime fence,
|
|
53
|
+
// including when a supervisor kills only the CLI and no JS handlers run.
|
|
54
|
+
await child.stdin.write(frame);
|
|
55
|
+
await child.stdin.flush();
|
|
56
|
+
};
|
|
57
|
+
try {
|
|
58
|
+
const [code, output] = await Promise.all([child.exited, new Response(child.stdout).text(), send()])
|
|
59
|
+
.catch(() => { throw new Error(uncertain); });
|
|
60
|
+
if (signal?.aborted) throw new Error(uncertain);
|
|
61
|
+
let reply: { ok?: boolean; error?: string; value?: T };
|
|
62
|
+
try { reply = JSON.parse(output); }
|
|
63
|
+
catch { throw new Error(uncertain); }
|
|
64
|
+
if (reply?.ok === false && typeof reply.error === "string") throw new Error(reply.error);
|
|
65
|
+
if (code !== 0 || reply?.ok !== true || reply.value === undefined) throw new Error(uncertain);
|
|
66
|
+
return reply.value;
|
|
67
|
+
} finally {
|
|
68
|
+
stop();
|
|
69
|
+
await child.exited.catch(() => undefined);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export const runOperator: OperatorRun = async (operation, request, credentials, signal) => {
|
|
74
|
+
if (signal?.aborted) throw new OperatorStartError();
|
|
75
|
+
const gateway = await requireGateway().catch(() => { throw new OperatorStartError(); });
|
|
76
|
+
return invokeOperator([gateway, "operator", operation], request, credentials, signal);
|
|
77
|
+
};
|
package/src/pr-github-schema.ts
CHANGED
|
@@ -17,6 +17,8 @@ export class PrReadError extends Error {
|
|
|
17
17
|
|
|
18
18
|
const id = Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER });
|
|
19
19
|
export const sha = Type.String({ pattern: "^(?:[0-9a-f]{40}|[0-9a-f]{64})$" });
|
|
20
|
+
// PR intake accepts SHA-1 only; general GitHub reads also accept SHA-256.
|
|
21
|
+
export const sha40 = Type.String({ pattern: "^[0-9a-f]{40}$" });
|
|
20
22
|
const nullableText = Type.Union([Type.String(), Type.Null()]);
|
|
21
23
|
const user = Type.Union([Type.Object({
|
|
22
24
|
login: Type.String({ pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*(\\[bot\\])?$", maxLength: 100 }),
|
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
|
}
|