omp-superagent 0.1.6 → 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.
Files changed (90) hide show
  1. package/DESIGN.md +36 -20
  2. package/README.ko.md +140 -33
  3. package/README.md +165 -41
  4. package/THIRD_PARTY_NOTICES.md +9 -7
  5. package/config.example.json +3 -1
  6. package/docs/OPERATIONS.md +395 -157
  7. package/docs/design/execution.md +156 -22
  8. package/docs/design/messaging.md +258 -52
  9. package/docs/discord-voice.md +8 -4
  10. package/docs/releases/0.1.7.md +25 -0
  11. package/docs/releases/0.1.8.md +21 -0
  12. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  13. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  14. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  15. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  16. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  17. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  18. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  19. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  20. package/package.json +9 -9
  21. package/scripts/ci.ts +4 -4
  22. package/scripts/test-omp.sh +2 -1
  23. package/skills/head/SKILL.md +26 -5
  24. package/skills/head/references/routing.md +68 -33
  25. package/skills/head/references/supervision.md +20 -4
  26. package/skills/lane/references/workflow.md +16 -7
  27. package/src/board.ts +5 -3
  28. package/src/cli.ts +161 -19
  29. package/src/config.ts +21 -1
  30. package/src/contracts.ts +63 -8
  31. package/src/cron-jobs.ts +443 -19
  32. package/src/cron-pr-intake.ts +257 -0
  33. package/src/discord-markdown.ts +350 -123
  34. package/src/extension.ts +78 -13
  35. package/src/gateway-client.ts +8 -2
  36. package/src/head-quota.ts +80 -0
  37. package/src/head-recovery.ts +40 -1
  38. package/src/host-extension.ts +122 -4
  39. package/src/host-inventory-manifest.ts +2 -2
  40. package/src/host-protocol.ts +11 -0
  41. package/src/host-sdk-helper.ts +121 -12
  42. package/src/host.ts +175 -57
  43. package/src/installed-omp.ts +116 -4
  44. package/src/lane-rows.ts +44 -4
  45. package/src/lane-watch.ts +339 -0
  46. package/src/managed-memory-helper.ts +13 -10
  47. package/src/managed-memory.ts +62 -27
  48. package/src/managed-ulw-probe.ts +75 -20
  49. package/src/managed-ulw.ts +174 -21
  50. package/src/messenger-command-catalog.json +2 -2
  51. package/src/native-launch-profile.ts +4 -2
  52. package/src/native-presets.ts +32 -5
  53. package/src/native-sessions.ts +3 -1
  54. package/src/native-settings.ts +47 -9
  55. package/src/observation-request.ts +23 -0
  56. package/src/omp-usage.ts +254 -36
  57. package/src/pr-github-schema.ts +5 -1
  58. package/src/pr-github.ts +68 -19
  59. package/src/pr-intake-automation.ts +316 -0
  60. package/src/pr-intake-comment.ts +226 -0
  61. package/src/pr-intake-fix.ts +233 -0
  62. package/src/pr-intake-github.ts +480 -0
  63. package/src/pr-intake-material.ts +230 -0
  64. package/src/pr-intake-mode.ts +59 -0
  65. package/src/pr-intake-review.ts +397 -0
  66. package/src/pr-intake-tree.ts +69 -0
  67. package/src/pr-intake-work.ts +29 -0
  68. package/src/pr-watch.ts +91 -32
  69. package/src/runtime.ts +2702 -391
  70. package/src/setup-judge.ts +1 -1
  71. package/src/setup.ts +12 -16
  72. package/src/store.ts +429 -86
  73. package/src/topic-history.ts +243 -47
  74. package/src/worker-checkout.ts +106 -0
  75. package/src/worker-destination.ts +10 -0
  76. package/src/worker-doctor.ts +66 -0
  77. package/src/worker-enrollment.ts +165 -0
  78. package/src/worker-host.ts +180 -0
  79. package/src/worker-ledger.ts +188 -0
  80. package/src/worker-placement.ts +78 -0
  81. package/src/worker-profile.ts +274 -0
  82. package/src/worker-registration.ts +288 -0
  83. package/src/worker-repository.ts +233 -0
  84. package/src/worker-request.ts +74 -0
  85. package/src/worker-service.ts +230 -0
  86. package/src/worker-stdio.ts +61 -0
  87. package/src/worker-trust.ts +36 -0
  88. package/src/worker-wire.ts +204 -0
  89. package/src/workflow.ts +81 -32
  90. package/src/setup-memory.ts +0 -21
@@ -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<void> {
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()) break;
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()) if (applied[index]) ownership[name] = { preset: snapshot, roles };
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
 
@@ -4,9 +4,11 @@ import { SessionManager } from "@oh-my-pi/pi-coding-agent/session/session-manage
4
4
  import { readSessionInfo } from "@oh-my-pi/pi-coding-agent/session/session-listing";
5
5
 
6
6
  /** Stock OMP follows leaf session links for discovery and writes through them. */
7
- export async function publishNativeSession(sessionFile: string, cwd: string): Promise<string | undefined> {
7
+ export async function publishNativeSession(sessionFile: string, cwd: string, expectedId?: string): Promise<string | undefined> {
8
8
  const info = await readSessionInfo(sessionFile);
9
9
  if (!info) return;
10
+ if (expectedId !== undefined && (info.id !== expectedId || info.cwd !== cwd))
11
+ throw new Error("Refusing to publish a journal with a different managed session identity");
10
12
  const source = await fs.realpath(sessionFile);
11
13
  const directory = SessionManager.getDefaultSessionDir(cwd);
12
14
  const target = join(directory, `${info.created.toISOString().replace(/[:.]/g, "-")}_${info.id}.jsonl`);
@@ -1,8 +1,13 @@
1
1
  import { lstat, mkdir, readFile, realpath, stat } from "node:fs/promises";
2
+ import { homedir } from "node:os";
2
3
  import { basename, delimiter, dirname, join, resolve } from "node:path";
4
+ import { settingsCapability, type Settings as DiscoveredSettings } from "@oh-my-pi/pi-coding-agent/capability/settings";
5
+ import { cfgDisabledProviders } from "@oh-my-pi/pi-coding-agent/config/model-settings";
3
6
  import { Settings } from "@oh-my-pi/pi-coding-agent/config/settings";
7
+ import { loadCapability } from "@oh-my-pi/pi-coding-agent/discovery";
4
8
  import { writeFileAtomically } from "@oh-my-pi/pi-coding-agent/utils/atomic-file";
5
- import { getAgentDbPath, MAIN_CONFIG_FILENAMES } from "@oh-my-pi/pi-utils/dirs";
9
+ import { isEnoent } from "@oh-my-pi/pi-utils";
10
+ import { getAgentDbPath, getProjectAgentDir, MAIN_CONFIG_FILENAMES, normalizePathForComparison } from "@oh-my-pi/pi-utils/dirs";
6
11
  import { withFileLock } from "@oh-my-pi/pi-utils/file-lock";
7
12
  import { expandTilde } from "@oh-my-pi/pi-utils/path";
8
13
  import { stringifyYamlConfig } from "@oh-my-pi/pi-utils/yaml-config";
@@ -26,6 +31,30 @@ export async function hasUnresolvedNativeLegacy(agentDir: string): Promise<boole
26
31
  ])).some(Boolean);
27
32
  }
28
33
 
34
+ /**
35
+ * Before a global fallback, distinguish an absent native project settings.json
36
+ * from one native discovery silently omitted or rejected. Settings already
37
+ * handles strict project YAML read and parse errors.
38
+ */
39
+ export async function hasUnresolvedNativeProjectSettings(settings: Settings): Promise<boolean> {
40
+ const provider = "native";
41
+ if (cfgDisabledProviders.get(settings).includes(provider)) return false;
42
+ const cwd = resolve(settings.getCwd());
43
+ // Native discovery treats the home directory as user scope only.
44
+ if (normalizePathForComparison(cwd) === normalizePathForComparison(homedir())) return false;
45
+ const file = join(getProjectAgentDir(cwd), "settings.json");
46
+ try {
47
+ // Inspect the entry itself so a dangling settings symlink is not treated as absent.
48
+ await lstat(file);
49
+ } catch (error) {
50
+ return !isEnoent(error);
51
+ }
52
+ const { items } = await loadCapability<DiscoveredSettings>(settingsCapability.id, {
53
+ cwd, agentDir: settings.getAgentDir(), providers: [provider], includeDisabledProviders: true,
54
+ });
55
+ return !items.some(item => item.level === "project" && item.path === file);
56
+ }
57
+
29
58
  export function readNativeSettings(settings: Settings): Promise<Settings> {
30
59
  const cwd = settings.getCwd();
31
60
  const configFiles = settings.getConfigFiles();
@@ -57,9 +86,10 @@ function valueAt(record: unknown, path: readonly string[]): unknown {
57
86
  }
58
87
 
59
88
  /**
60
- * Application-owned edits only. Native read-only loading validates all inputs;
61
- * the native lock and atomic publisher serialize with stock Settings writers.
62
- * A stale key is preserved while disjoint keys are merged from the locked file.
89
+ * Application-owned edits only. Recheck the effective scope with native
90
+ * read-only loading and use the lock shared by stock Settings writers.
91
+ * Compare staged keys against the YAML being edited. A writer that ignores
92
+ * the lock can still change the file after that comparison.
63
93
  */
64
94
  export async function editNativeGlobalConfig(settings: Settings, edits: readonly GlobalEdit[],
65
95
  accept?: (actual: Settings) => boolean | Promise<boolean>): Promise<boolean[]> {
@@ -105,7 +135,6 @@ export async function editNativeGlobalConfig(settings: Settings, edits: readonly
105
135
  if (raw === null || raw === undefined) raw = {};
106
136
  if (!isRecord(raw)) throw new Error("Native global config must be a mapping");
107
137
  const global = raw;
108
- const actualGlobal = actual.getGlobalSettings();
109
138
  const updated = structuredClone(global);
110
139
  const applied = edits.map(edit => {
111
140
  const path = edit.path.split(".");
@@ -116,10 +145,19 @@ export async function editNativeGlobalConfig(settings: Settings, edits: readonly
116
145
  [actual.mirrorState().overrides, actual.mirrorState().configOverlay].some(layer =>
117
146
  isRecord(layer.modelPresets) && Object.hasOwn(layer.modelPresets, name))) return false;
118
147
  } else {
119
- // Native Settings interprets legacy `memories.enabled` in modern YAML
120
- // as a backend. Compare that effective global value while editing raw YAML.
121
- const latest = edit.path === "memory.backend" ? actualGlobal : global;
122
- if (!Bun.deepEquals(valueAt(latest, path), valueAt(baseline, path))) return false;
148
+ let latest = valueAt(global, path);
149
+ if (edit.path === "memory.backend") {
150
+ if (global.memory !== undefined && global.memory !== null && !isRecord(global.memory)) return false;
151
+ // The staged value has already been migrated by native Settings.
152
+ // Apply the same selector rules to the exact YAML we will edit.
153
+ const legacyEnabled = valueAt(global, ["memories", "enabled"]);
154
+ if (typeof latest !== "string" && typeof legacyEnabled === "boolean") {
155
+ latest = legacyEnabled ? "local" : "off";
156
+ } else if (latest === "mnemosyne") {
157
+ latest = "mnemopi";
158
+ }
159
+ }
160
+ if (!Bun.deepEquals(latest, valueAt(baseline, path))) return false;
123
161
  }
124
162
  let target = updated;
125
163
  for (const segment of path.slice(0, -1)) {
@@ -0,0 +1,23 @@
1
+ import { ownerRoutingProse } from "./topic-history";
2
+
3
+ const observationSubject = /\b(?:presence|online|pr|ci|lane|pull request|watches|monitors)\b|github\.com\/[^ ]+\/pull\/\d+|#\d+|온라인|오프라인|접속\s*표시|레인|작업|봇/iu;
4
+ const watchTarget = /^(?:watch|monitor|track|untrack|(?:start|stop) (?:watching|monitoring|tracking)|keep an eye on)\s+(?:(?:this|that|the|our|my)\s+)?(?:pr\b|pull request\b|lane\b|ci(?=[.?!\s]*$|\s+(?:checks?|runs?|status|on|for|of|and)\b)|https?:\/\/github\.com\/[\w.-]+\/[\w.-]+\/pull\/\d+\b|[\w.-]+\/[\w.-]+#\d+\b|#\d+\b)/i;
5
+ const watchList = /^(?:list|show) (?:my |the |our )?(?:watches|monitors)\b/i;
6
+ const notify = /^(?:notify me|let me know) (?:when|if)\b/i;
7
+ const implicitWatch = /^(?:keep an eye on (?:it|this)|(?:notify me|let me know) when (?:it|this) (?:finishes|stalls|fails|passes|completes))[.?!\s]*$/i;
8
+ const englishPresence = /^(?:(?:please|can you|could you)\s+)*(?:keep|set|show|check|enable|disable|turn (?:on|off)|is)\s+(?:the |our |your |my )?(?:(?:discord|slack|telegram)\s+)?(?:bot(?:'s)?\s+(?:presence|online|invisible)\b|presence\b|online (?:indicator|dot)\b)/i;
9
+ const koreanWatch = /(?:감시|모니터링|추적)(?:해|(?:를|을)?\s*(?:시작|중지|종료|해제|그만)(?:해)?)$/u;
10
+ const koreanPresence = /(?:(?:온라인|오프라인)(?:으로|\s*상태(?:로|를)?)?\s*(?:유지|표시|전환)해|(?:온라인|오프라인|접속)\s*표시(?:를)?\s*(?:켜|꺼))$/u;
11
+ const koreanStatus = /(?:(?:상태|목록)(?:를|을)?\s*(?:알려|보여|확인해)|(?:되면|나면|지면|추면|하면|했는지|인지)\s*(?:여기(?:에|로)?\s*)?알려)$/u;
12
+
13
+ /** This changes only the session receiving the message, never the subscription or
14
+ * presence. HEAD resolves the target, asks when ambiguous, and calls the tool. */
15
+ export function isObservationRequest(text: string): boolean {
16
+ const prose = ownerRoutingProse(text);
17
+ if (!prose || prose.includes("\n") || prose.startsWith("/") || /^cwd\s*:/i.test(prose)) return false;
18
+ const english = prose.replace(/^(?:(?:please|can you|could you)\s+)+/i, "");
19
+ if (englishPresence.test(prose) || watchTarget.test(english) || watchList.test(english) || implicitWatch.test(english)) return true;
20
+ if (!observationSubject.test(prose) && !/^(?:감시|모니터링)/u.test(prose)) return false;
21
+ const request = prose.replace(/[.!?…\s]+$/u, "").replace(/\s*(?:주세요|주라|줘요?|줘라|둬|놔|봐|라)$/u, "");
22
+ return notify.test(english) || koreanWatch.test(request) || koreanPresence.test(request) || koreanStatus.test(request);
23
+ }
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({ provider: Type.String(), limits: Type.Array(limitSchema) })),
29
- accountsWithoutUsage: Type.Optional(Type.Array(Type.Object({ provider: Type.String() }))),
30
- disabledCredentials: Type.Optional(Type.Array(Type.Object({ provider: Type.String() }))),
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
- const windowLabel = window?.label;
39
- const shortWindow = window?.id === "5h" ? "5시간" : window?.id === "7d" ? "주간" : windowLabel;
40
- let name = label;
41
- if (windowLabel && shortWindow && windowLabel.toLowerCase() !== "quota window") {
42
- const labelWithoutProvider = label.replace(/^Claude /, "");
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 && amount.unit !== "percent" && amount.unit !== "unknown") {
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
- /** Use the configured stock OMP's profile and publish only the quota projection. */
77
- export async function readOmpUsage(config: Config, environment: NodeJS.ProcessEnv = process.env): Promise<string> {
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
- const child = Bun.spawn([executable, ...(profile ? [`--profile=${profile}`] : []),
84
- "usage", "--json", "--redact", "--no-extensions"], {
85
- cwd: config.headCwd, env, stdin: "ignore", stdout: "pipe", stderr: "ignore", timeout: 30_000, killSignal: "SIGKILL",
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: unknown = JSON.parse(stdout);
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 { provider } of response.accountsWithoutUsage ?? []) {
104
- addAccount(provider, ["• 남은 한도 미확인"]);
167
+ for (const account of response.accountsWithoutUsage ?? []) {
168
+ addAccount(account.provider, usageAccountLabel(account), ["• 남은 한도 미확인"]);
105
169
  }
106
- for (const { provider } of response.disabledCredentials ?? []) {
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" : provider;
112
- return entries.map((limits, index) =>
113
- [`${name}${entries.length > 1 ? ` · 계정 ${index + 1}` : ""}`, ...limits].join("\n"));
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
+ }
@@ -2,12 +2,13 @@ import { Type, type Static, type TSchema } from "@sinclair/typebox/type";
2
2
  import { Value } from "@sinclair/typebox/value";
3
3
 
4
4
  export class PrReadError extends Error {
5
- constructor(readonly reason: "reference" | "request" | "response" | "changed" | "aborted") {
5
+ constructor(readonly reason: "reference" | "request" | "response" | "changed" | "ci-changed" | "aborted") {
6
6
  super({
7
7
  reference: "Invalid GitHub PR reference",
8
8
  request: "GitHub PR observation request failed",
9
9
  response: "GitHub PR observation response was invalid or incomplete",
10
10
  changed: "GitHub PR changed during observation",
11
+ "ci-changed": "GitHub PR check attempts changed during observation",
11
12
  aborted: "GitHub PR observation was cancelled",
12
13
  }[reason]);
13
14
  this.name = "PrReadError";
@@ -62,6 +63,9 @@ export const statusSchema = Type.Object({
62
63
  id, context: Type.String(), target_url: nullableText, created_at: Type.String(),
63
64
  state: Type.Union((["error", "failure", "pending", "success"] as const).map(value => Type.Literal(value))),
64
65
  });
66
+ export const ciOutcomeSchema = Type.Union(
67
+ (["missing", "pending", "skipped", "failed", "passed", "passed_with_skips"] as const).map(value => Type.Literal(value)),
68
+ );
65
69
  export const comparePageSchema = Type.Object({
66
70
  status: Type.Union((["ahead", "behind", "diverged", "identical"] as const).map(value => Type.Literal(value))),
67
71
  total_commits: Type.Integer({ minimum: 0 }),