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.
Files changed (122) hide show
  1. package/DESIGN.md +27 -16
  2. package/README.ko.md +40 -19
  3. package/README.md +43 -18
  4. package/THIRD_PARTY_NOTICES.md +11 -11
  5. package/config.example.json +2 -1
  6. package/docs/OPERATIONS.md +285 -85
  7. package/docs/design/execution.md +133 -24
  8. package/docs/design/messaging.md +235 -50
  9. package/docs/discord-voice.md +8 -4
  10. package/docs/releases/0.1.8.md +21 -0
  11. package/docs/releases/0.1.9.md +18 -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/notices/darwin-arm64/Cargo-LICENSES.txt +2 -0
  17. package/host-owner/bin/notices/darwin-arm64/Cargo-SOURCES.txt +2 -0
  18. package/host-owner/bin/notices/darwin-arm64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
  19. package/host-owner/bin/notices/darwin-arm64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
  20. package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/COPYRIGHT +29 -0
  21. package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
  22. package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  23. package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
  24. package/host-owner/bin/notices/darwin-x64/Cargo-LICENSES.txt +2 -0
  25. package/host-owner/bin/notices/darwin-x64/Cargo-SOURCES.txt +2 -0
  26. package/host-owner/bin/notices/darwin-x64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
  27. package/host-owner/bin/notices/darwin-x64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
  28. package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/COPYRIGHT +29 -0
  29. package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
  30. package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  31. package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
  32. package/host-owner/bin/notices/linux-arm64/Cargo-LICENSES.txt +3 -0
  33. package/host-owner/bin/notices/linux-arm64/Cargo-SOURCES.txt +3 -0
  34. package/host-owner/bin/notices/linux-arm64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
  35. package/host-owner/bin/notices/linux-arm64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
  36. package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/COPYRIGHT +29 -0
  37. package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/LICENSE-APACHE +201 -0
  38. package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  39. package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/LICENSE-MIT +23 -0
  40. package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/COPYRIGHT +29 -0
  41. package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
  42. package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  43. package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
  44. package/host-owner/bin/notices/linux-x64/Cargo-LICENSES.txt +3 -0
  45. package/host-owner/bin/notices/linux-x64/Cargo-SOURCES.txt +3 -0
  46. package/host-owner/bin/notices/linux-x64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
  47. package/host-owner/bin/notices/linux-x64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
  48. package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/COPYRIGHT +29 -0
  49. package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/LICENSE-APACHE +201 -0
  50. package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  51. package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/LICENSE-MIT +23 -0
  52. package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/COPYRIGHT +29 -0
  53. package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
  54. package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  55. package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
  56. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  57. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  58. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  59. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  60. package/package.json +17 -15
  61. package/skills/head/SKILL.md +3 -11
  62. package/skills/head/references/routing.md +23 -17
  63. package/skills/head/references/supervision.md +13 -1
  64. package/skills/lane/references/workflow.md +8 -8
  65. package/src/cli.ts +6 -3
  66. package/src/config.ts +5 -0
  67. package/src/contracts.ts +95 -10
  68. package/src/cron-jobs.ts +443 -19
  69. package/src/cron-pr-intake.ts +257 -0
  70. package/src/discord-command-registration.ts +34 -186
  71. package/src/extension.ts +31 -3
  72. package/src/gateway-client.ts +11 -59
  73. package/src/gateway-protocol.ts +35 -1
  74. package/src/head-quota.ts +80 -0
  75. package/src/head-recovery.ts +249 -1
  76. package/src/host-extension.ts +194 -5
  77. package/src/host-protocol.ts +16 -9
  78. package/src/host-sdk-helper.ts +105 -10
  79. package/src/host.ts +111 -29
  80. package/src/installed-omp.ts +116 -4
  81. package/src/lane-models.ts +8 -0
  82. package/src/managed-ulw-probe.ts +22 -20
  83. package/src/managed-ulw.ts +137 -24
  84. package/src/messenger-command-catalog.json +6 -3
  85. package/src/messenger-commands.ts +9 -2
  86. package/src/native-presets.ts +32 -5
  87. package/src/omp-usage.ts +254 -36
  88. package/src/operator.ts +77 -0
  89. package/src/pr-github-schema.ts +2 -0
  90. package/src/pr-github.ts +4 -2
  91. package/src/pr-intake-automation.ts +315 -0
  92. package/src/pr-intake-comment.ts +225 -0
  93. package/src/pr-intake-fix.ts +232 -0
  94. package/src/pr-intake-github.ts +479 -0
  95. package/src/pr-intake-material.ts +229 -0
  96. package/src/pr-intake-mode.ts +59 -0
  97. package/src/pr-intake-review.ts +397 -0
  98. package/src/pr-intake-tree.ts +68 -0
  99. package/src/pr-intake-work.ts +29 -0
  100. package/src/pr-review-models.ts +28 -0
  101. package/src/result-attachment.ts +60 -79
  102. package/src/runtime.ts +2968 -449
  103. package/src/setup-profiles.ts +26 -65
  104. package/src/slack-command-registration.ts +48 -197
  105. package/src/store.ts +507 -87
  106. package/src/superkit-skills.ts +22 -0
  107. package/src/telegram-command-languages.json +17 -0
  108. package/src/telegram-command-registration.ts +32 -134
  109. package/src/topic-history.ts +30 -17
  110. package/src/worker-bridge.ts +21 -0
  111. package/src/worker-enrollment.ts +2 -1
  112. package/src/worker-host.ts +0 -24
  113. package/src/worker-serve-prepare.ts +19 -0
  114. package/src/worker-service.ts +51 -47
  115. package/scripts/ci.ts +0 -44
  116. package/scripts/release.ts +0 -112
  117. package/scripts/test-omp.sh +0 -43
  118. package/src/discord-commands.ts +0 -29
  119. package/src/discord-markdown.ts +0 -172
  120. package/src/slack-commands.ts +0 -18
  121. package/src/telegram-signal.ts +0 -14
  122. package/src/worker-stdio.ts +0 -61
@@ -1,10 +1,9 @@
1
1
  import type { IncomingMessage } from "node:http";
2
- import { Readable, Transform } from "node:stream";
3
2
  import type { Config } from "./config";
4
3
  import { createHash } from "node:crypto";
5
- import type { Approval, Attachment, DiscordContext, DiscordPurposeNote, DiscordPurposeRequest, GatewayRestartRecord, GatewayRestartRequest, Inbound, MessageActivity, MessageReference, Messenger, OutputRecord, Route, ThreadInfo, ThreadUpdate } from "./contracts";
4
+ import type { Approval, DiscordContext, DiscordPurposeNote, DiscordPurposeRequest, GatewayRestartRecord, GatewayRestartRequest, Inbound, InboundAttachmentBatch, InboundAttachmentReceipt, MessageActivity, MessageReference, Messenger, OutputRecord, Route, ThreadInfo, ThreadUpdate } from "./contracts";
6
5
  import { DeliveryError } from "./delivery";
7
- import { gatewayCall, gatewayPaths, gatewayRequest, MAX_GATEWAY_ATTACHMENT, MAX_GATEWAY_FRAME, readGatewayJson, type GatewayResult } from "./gateway-protocol";
6
+ import { gatewayCall, gatewayPaths, gatewayRequest, MAX_GATEWAY_FRAME, parseInboundAttachmentReceipt, readGatewayJson, type GatewayResult } from "./gateway-protocol";
8
7
  import type { GatewayReceipt, QueuedEvent } from "./gateway-wire";
9
8
  import type { GroupReply } from "./group-policy";
10
9
  import type { DiscordPresenceStatus, MessengerPresenceRequest } from "./contracts";
@@ -156,9 +155,12 @@ class GatewayMessenger implements GatewayHeadMessenger {
156
155
  // Stable across client reattachment; the Gateway journals the one attempt.
157
156
  const hash = createHash("sha256").update(JSON.stringify(["result-attachment", output.id])).digest("hex");
158
157
  const id = `${hash.slice(0, 8)}-${hash.slice(8, 12)}-${hash.slice(12, 16)}-${hash.slice(16, 20)}-${hash.slice(20, 32)}`;
159
- // The adapter needs bytes and filename, not filesystem paths or native IDs.
158
+ // Transfer only a receipt; the old persisted payload is read by the Gateway
159
+ // itself so its original attempt fingerprint can still be reconciled.
160
+ const { payload } = resultAttachment;
160
161
  return this.call<string>("/effect", { id, operation: "send", args: [{
161
- id: output.id, route: output.route, text: output.text, replyTo: output.replyTo, resultAttachment: resultAttachment.payload,
162
+ id: output.id, route: output.route, text: output.text, replyTo: output.replyTo,
163
+ resultAttachment: "data" in payload ? { name: payload.name, legacy: true } : payload,
162
164
  }] });
163
165
  }
164
166
  assertRoute(route: Route, purpose?: "history"): Promise<void> {
@@ -185,62 +187,12 @@ class GatewayMessenger implements GatewayHeadMessenger {
185
187
  discordPurpose(request: DiscordPurposeRequest): Promise<readonly DiscordPurposeNote[]> { return this.effect("discordPurpose", [request]); }
186
188
  fetchAfter(route: Route, messageId: string): Promise<Inbound[] | null> { return this.effect("fetchAfter", [route, messageId]); }
187
189
 
188
- async openAttachment(route: Route, attachment: Attachment, signal: AbortSignal): Promise<Response> {
190
+ async openAttachment(batch: InboundAttachmentBatch, signal: AbortSignal): Promise<InboundAttachmentReceipt> {
189
191
  if (this.stopped) throw new DeliveryError("Gateway client is stopped", "rejected");
190
- if (attachment.size !== null && (!Number.isSafeInteger(attachment.size) || attachment.size < 0 || attachment.size > MAX_GATEWAY_ATTACHMENT))
191
- throw new DeliveryError("Invalid attachment size", "rejected");
192
- const incoming = await gatewayRequest(this.socketPath, "/attachment", { route, attachment }, { ...this.options(), signal });
193
- if (incoming.headers["x-gateway-attachment-protocol"] !== "1") {
194
- const result = await readGatewayJson(incoming) as GatewayResult;
195
- throw new DeliveryError(result.error ?? "Attachment rejected", result.certainty ?? "uncertain");
196
- }
197
- let bytes = 0;
198
- const header = Buffer.allocUnsafe(4);
199
- let headerBytes = 0;
200
- let remaining = 0;
201
- let complete = false;
202
- const bounded = new Transform({
203
- transform(chunk: Buffer, _encoding, callback) {
204
- let offset = 0;
205
- while (offset < chunk.length) {
206
- if (complete) { callback(new Error("Attachment data followed its completion frame")); return; }
207
- if (!remaining) {
208
- const count = Math.min(4 - headerBytes, chunk.length - offset);
209
- chunk.copy(header, headerBytes, offset, offset + count);
210
- headerBytes += count;
211
- offset += count;
212
- if (headerBytes < 4) continue;
213
- remaining = header.readUInt32BE();
214
- headerBytes = 0;
215
- if (!remaining) { complete = true; continue; }
216
- if (bytes + remaining > (attachment.size ?? MAX_GATEWAY_ATTACHMENT) || bytes + remaining > MAX_GATEWAY_ATTACHMENT) {
217
- callback(new Error("Attachment stream exceeds declared size"));
218
- return;
219
- }
220
- }
221
- const count = Math.min(remaining, chunk.length - offset);
222
- if (count) this.push(chunk.subarray(offset, offset + count));
223
- offset += count;
224
- remaining -= count;
225
- bytes += count;
226
- }
227
- callback();
228
- },
229
- flush(callback) {
230
- callback(!complete || remaining || headerBytes || attachment.size !== null && bytes !== attachment.size
231
- ? new Error("Attachment stream ended without a complete delivery receipt") : undefined);
232
- },
192
+ const result = await gatewayCall<unknown>(this.socketPath, "/attachment", batch, {
193
+ ...this.options(), signal, timeoutMs: 30_000 * Math.min(batch.attachments.length, 10) + 1000,
233
194
  });
234
- incoming.on("error", error => bounded.destroy(error));
235
- incoming.on("aborted", () => bounded.destroy(new Error("Attachment stream was interrupted")));
236
- bounded.on("close", () => incoming.destroy());
237
- incoming.pipe(bounded);
238
- const headers = new Headers();
239
- const contentType = incoming.headers["content-type"];
240
- const contentLength = incoming.headers["x-gateway-attachment-length"];
241
- if (typeof contentType === "string") headers.set("content-type", contentType);
242
- if (typeof contentLength === "string") headers.set("content-length", contentLength);
243
- return new Response(Readable.toWeb(bounded) as ReadableStream<Uint8Array>, { status: incoming.statusCode ?? 502, headers });
195
+ return parseInboundAttachmentReceipt(this.socketPath, batch, result);
244
196
  }
245
197
 
246
198
  async stop(): Promise<void> {
@@ -1,13 +1,16 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { request, type IncomingMessage } from "node:http";
2
3
  import { existsSync } from "node:fs";
3
- import { lstat } from "node:fs/promises";
4
+ import { lstat, realpath } from "node:fs/promises";
4
5
  import { dirname, join } from "node:path";
5
6
  import type { Config } from "./config";
7
+ import type { InboundAttachmentBatch, InboundAttachmentReceipt } from "./contracts";
6
8
  import { DeliveryError } from "./delivery";
7
9
  import type { GatewayStatus } from "./gateway-wire";
8
10
 
9
11
  export const MAX_GATEWAY_FRAME = 16 * 1024 * 1024;
10
12
  export const MAX_GATEWAY_ATTACHMENT = 20 * 1024 * 1024;
13
+ export const MAX_GATEWAY_ATTACHMENT_BATCH = 40 * 1024 * 1024;
11
14
  export interface GatewayResult { ok: boolean; value?: unknown; error?: string; certainty?: "rejected" | "uncertain"; retryAfterMs?: number }
12
15
 
13
16
  export function gatewayPaths(config: Pick<Config, "stateDir">) {
@@ -83,3 +86,34 @@ export async function gatewayCall<T>(socketPath: string, endpoint: string, body?
83
86
  if (!result.ok) throw new DeliveryError(result.error ?? "Gateway rejected operation", result.certainty ?? "uncertain", result.retryAfterMs);
84
87
  return result.value as T;
85
88
  }
89
+
90
+ /** A spool reply carries only correctly indexed local references, never attachment bytes. */
91
+ export async function parseInboundAttachmentReceipt(
92
+ socketPath: string, batch: InboundAttachmentBatch, value: unknown,
93
+ ): Promise<InboundAttachmentReceipt> {
94
+ const invalid = () => new DeliveryError("Invalid attachment spool receipt", "uncertain");
95
+ if (!value || typeof value !== "object" || !("receipt" in value) || !("files" in value)
96
+ || typeof value.receipt !== "string" || !/^[a-f0-9]{64}$/.test(value.receipt)
97
+ || !Array.isArray(value.files) || value.files.length !== batch.attachments.length) throw invalid();
98
+ const directory = join(await realpath(dirname(dirname(socketPath))), "attachments", value.receipt);
99
+ const digest = createHash("sha256").update(createHash("sha256").update(batch.inputId).digest());
100
+ let total = 0;
101
+ const files: InboundAttachmentReceipt["files"][number][] = [];
102
+ for (const [index, attachment] of batch.attachments.entries()) {
103
+ const file: unknown = value.files[index];
104
+ if (!file || typeof file !== "object" || !("path" in file) || !("size" in file) || !("mimeType" in file)
105
+ || file.path !== join(directory, String(index)) || typeof file.size !== "number"
106
+ || !Number.isSafeInteger(file.size) || file.size < 0 || file.size > MAX_GATEWAY_ATTACHMENT
107
+ || (attachment.size !== null && file.size !== attachment.size)
108
+ || !("sha256" in file) || typeof file.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(file.sha256)
109
+ || typeof file.mimeType !== "string"
110
+ || !["application/octet-stream", "image/png", "image/jpeg", "image/gif", "image/webp"].includes(file.mimeType))
111
+ throw invalid();
112
+ total += file.size;
113
+ if (total > MAX_GATEWAY_ATTACHMENT_BATCH) throw invalid();
114
+ digest.update(Buffer.from(file.sha256, "hex"));
115
+ files.push({ path: file.path, size: file.size, mimeType: file.mimeType, sha256: file.sha256 });
116
+ }
117
+ if (digest.digest("hex") !== value.receipt) throw invalid();
118
+ return { receipt: value.receipt, files };
119
+ }
@@ -0,0 +1,80 @@
1
+ import type { AgentSession } from "@oh-my-pi/pi-coding-agent";
2
+ import { cfgRetryUsageReservePct } from "@oh-my-pi/pi-coding-agent/session/settings";
3
+ import { quotaTierFor } from "@oh-my-pi/pi-catalog/compat/behavior";
4
+ import type { HeadQuotaFailure } from "./head-recovery";
5
+
6
+ /** Match stock OMP's usage-report cache horizon, not a presumed provider reset time. */
7
+ export const HEAD_QUOTA_CHECK_MS = 5 * 60_000;
8
+
9
+ type QuotaSession = Pick<AgentSession, "modelRegistry" | "sessionId" | "settings"> & {
10
+ readonly model: Pick<NonNullable<AgentSession["model"]>, "provider" | "id" | "baseUrl" | "accountAccess"> | undefined;
11
+ };
12
+
13
+ export async function readHeadQuota(
14
+ session: QuotaSession,
15
+ failure: HeadQuotaFailure,
16
+ signal: AbortSignal,
17
+ ): Promise<boolean> {
18
+ const { model, sessionId } = session;
19
+ if (!model || model.provider !== failure.model.provider || model.id !== failure.model.id) return false;
20
+ const { authStorage } = session.modelRegistry;
21
+ const { health, usage, sessions, oauth } = authStorage;
22
+ if (typeof health?.model !== "function" || typeof usage?.reports !== "function"
23
+ || typeof sessions?.permits !== "function" || typeof oauth?.accounts !== "function"
24
+ || typeof oauth?.policy !== "function") return false;
25
+ const { provider, id, baseUrl } = model;
26
+ // Native health supplies model scope, entitlement, reserves and credential
27
+ // blocks, but can use a stale last-good report after a failed usage read.
28
+ const availability = await health.model(provider, { modelId: id, baseUrl, sessionId, signal,
29
+ reserveFraction: cfgRetryUsageReservePct.get(session.settings) / 100 });
30
+ const eligible = availability.accounts.filter(account => account.credentialType === "oauth"
31
+ && account.state === "healthy" && account.remainingFraction !== undefined && account.remainingFraction > 0
32
+ && sessions.permits(provider, sessionId, account.credentialId));
33
+ if (!eligible.length) return false;
34
+ const reports = await usage.reports({ provider, baseUrlResolver: () => baseUrl, signal });
35
+ if (signal.aborted || session.sessionId !== sessionId || session.model !== model) return false;
36
+ const now = Date.now();
37
+ const accounts = oauth.accounts(provider, sessionId);
38
+ // Request auth looks up the current discovery roster, which can change
39
+ // without replacing the session's model object.
40
+ const accountAccess = session.modelRegistry.find(provider, id)?.accountAccess ?? model.accountAccess;
41
+ const spark = quotaTierFor(provider, id) === "spark";
42
+ const windowPrefix = spark ? `${provider}:spark:` : `${provider}:`;
43
+ return reports?.some(report => {
44
+ const { fetchedAt, metadata } = report;
45
+ if (report.provider !== provider || !Number.isFinite(fetchedAt) || fetchedAt <= failure.failedAt
46
+ || fetchedAt > now || now - fetchedAt > HEAD_QUOTA_CHECK_MS || !metadata
47
+ || metadata.source === "ratelimit-headers" || metadata.headersUpdatedAt !== undefined) return false;
48
+ const meters = metadata.meterStates;
49
+ const meter: unknown = spark
50
+ ? meters && typeof meters === "object" && "spark" in meters ? meters.spark : null
51
+ : metadata;
52
+ if (!meter || typeof meter !== "object" || !("allowed" in meter) || meter.allowed !== true
53
+ || !("limitReached" in meter) || meter.limitReached !== false) return false;
54
+ // The verdict can include credit-funded overage. Check actual headroom in
55
+ // this report, not just the potentially older snapshot used by model health.
56
+ const windows = report.limits.filter(limit =>
57
+ limit.id === `${windowPrefix}primary` || limit.id === `${windowPrefix}secondary`);
58
+ const limits = windows.length || spark ? windows : report.limits.filter(limit => limit.id === `${provider}:spend-cap`);
59
+ // Local reports carry the credential row. A broker may carry only the
60
+ // Codex account ID; accept it only if it maps to exactly one native row.
61
+ const accountId = metadata.accountId;
62
+ const matching = metadata.credentialId === undefined && typeof accountId === "string" && accountId
63
+ ? accounts.filter(account => account.accountId === accountId) : [];
64
+ const credentialId = metadata.credentialId ?? (matching.length === 1 ? matching[0]?.credentialId : undefined);
65
+ const account = accounts.find(candidate => candidate.credentialId === credentialId);
66
+ if (!account || !eligible.some(candidate => candidate.credentialId === account.credentialId)
67
+ || !sessions.permits(provider, sessionId, account.credentialId)) return false;
68
+ // Use the identity precedence ModelRegistry uses for its discovered account roster.
69
+ const accountKey = account.accountId ?? account.email ?? account.projectId;
70
+ if (accountAccess && (!accountKey || !Object.hasOwn(accountAccess, accountKey))) return false;
71
+ const reservePct = oauth.policy(provider, account)?.reservePct ?? cfgRetryUsageReservePct.get(session.settings);
72
+ const reserveFraction = Math.max(0, Math.min(100, reservePct)) / 100;
73
+ return limits.length > 0 && limits.every(limit => {
74
+ const used = limit.amount.usedFraction;
75
+ // Match native isWithinUsageReserve's float slack at the boundary.
76
+ return limit.status !== "exhausted" && typeof used === "number" && used >= 0
77
+ && 1 - used > reserveFraction + 1e-9;
78
+ });
79
+ }) ?? false;
80
+ }
@@ -1,9 +1,192 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import type { HeadRecoveryAttempt } from "./contracts";
3
3
 
4
+ export interface HeadQuotaFailure {
5
+ readonly model: { readonly provider: "openai-codex"; readonly id: string };
6
+ readonly failedAt: number;
7
+ }
8
+
4
9
  const object = (value: unknown): Record<string, unknown> =>
5
10
  value !== null && typeof value === "object" ? value as Record<string, unknown> : {};
6
11
 
12
+ const codexFailureCode = /^Codex (?:error event|response failed)(?:: [\s\S]+)? \(code=([a-z_]+)(?:, status=[a-z_]+)?\)$/;
13
+ // AssistantMessage.errorId uses the SDK's public wire bits. Read them without
14
+ // requiring the installed CLI to expose a particular SDK error submodule.
15
+ const transientErrorBit = 0x0002_0000;
16
+ const usageLimitErrorBit = 0x0008_0000;
17
+
18
+ function googleQuotaError(message: string, status: unknown): boolean {
19
+ const http = /^(Google API|Cloud Code Assist API) error \((402|429)\)(?: resuming a long generation)?: /.exec(message);
20
+ const prefix = http ?? /^(?:Google API|Cloud Code Assist) stream error: /.exec(message);
21
+ if (!prefix || (http ? status !== Number(http[2]) : status !== undefined && status !== 429 && status !== 402)) return false;
22
+ // Cloud Code Assist HTTP preserves the whole response body. Google/Vertex HTTP
23
+ // and both streaming adapters can append a JSON.stringify'd RPC status suffix.
24
+ const detail = message.slice(prefix[0].length).trim();
25
+ const suffix = http?.[1] === "Cloud Code Assist API" ? -1 : detail.lastIndexOf(' {"error":{"status":');
26
+ if (!http && (suffix < 0 || !/(?: \(RESOURCE_EXHAUSTED\)|^RESOURCE_EXHAUSTED)$/.test(detail.slice(0, suffix)))) return false;
27
+ try {
28
+ const error = object(object(JSON.parse(detail.slice(suffix + 1))).error);
29
+ if (error.status !== "RESOURCE_EXHAUSTED" || !Array.isArray(error.details)
30
+ || (suffix >= 0 && Object.keys(error).length !== 2)) return false;
31
+ const reasons = error.details.map(object).filter(part => part["@type"] === "type.googleapis.com/google.rpc.ErrorInfo");
32
+ return reasons.some(part => part.reason === "QUOTA_EXHAUSTED" || part.reason === "INSUFFICIENT_G1_CREDITS_BALANCE")
33
+ && !reasons.some(part => part.reason === "MODEL_CAPACITY_EXHAUSTED" || part.reason === "MODEL_CAPACITY_EXCEEDED");
34
+ } catch (error) {
35
+ if (error instanceof SyntaxError) return false;
36
+ throw error;
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Classify only the error metadata of an owned native prompt receipt or
42
+ * terminal assistant message. A bare HTTP status or SDK UsageLimit flag can
43
+ * also represent a throttle; neither is evidence of account quota exhaustion.
44
+ */
45
+ export function laneQuotaExhausted(error: unknown): boolean {
46
+ const failure = object(error);
47
+ const assistant = failure.role === "assistant" && failure.stopReason === "error";
48
+ if (failure.role !== undefined && !assistant) return false;
49
+ const errorId = assistant && typeof failure.errorId === "number" ? failure.errorId : 0;
50
+ const transient = failure.retryable === true || (errorId & transientErrorBit) !== 0;
51
+ const detail = assistant ? failure.errorClassificationMessage ?? failure.errorMessage : failure.message;
52
+ // DashScope uses the same code and billing wording for a transient TPM/TPS cap.
53
+ const lower = typeof detail === "string" ? detail.toLowerCase() : "";
54
+ if (lower.includes("you exceeded your current quota, please check your plan and billing details")
55
+ && lower.includes("error-code") && lower.includes("#token-limit")) return false;
56
+ const code = failure.code ?? failure.type;
57
+ if (code !== undefined) return !transient && (code === "usage_limit_reached" || code === "insufficient_quota");
58
+ if (typeof detail !== "string" || typeof failure.provider !== "string" || !failure.provider
59
+ || (!assistant && typeof failure.retryable !== "boolean")) return false;
60
+
61
+ // Stock OMP 19.1.1 strips structured provider codes in RPC prompt errors.
62
+ // Its native formatters can still preserve one in a dedicated position.
63
+ const message = detail.replace(/ retry-after-ms=\d+$/, "");
64
+ const status = assistant ? failure.errorStatus : failure.httpStatus;
65
+ // The stock SDK can mark any ProviderHttpError 429 transient, even when
66
+ // its provider-specific machine code proves a persistent quota failure.
67
+ if (failure.provider === "cursor" && (failure.api === undefined || failure.api === "cursor-agent")) {
68
+ return status === 429 && /^Cursor USAGE_PRICING_REQUIRED: \S/.test(message);
69
+ }
70
+ const googleWire = failure.api === undefined
71
+ ? ["google", "google-vertex", "google-antigravity", "google-gemini-cli"].includes(failure.provider)
72
+ : failure.api === "google-generative-ai" || failure.api === "google-vertex" || failure.api === "google-gemini-cli";
73
+ if (googleWire) return googleQuotaError(message, status);
74
+ if (failure.provider === "openai-codex" || failure.api === "openai-codex-responses") {
75
+ if (transient) return false;
76
+ const nativeCode = codexFailureCode.exec(message)?.[1];
77
+ if (nativeCode !== undefined) return nativeCode === "usage_limit_reached" || nativeCode === "insufficient_quota";
78
+ // Codex's HTTP adapter uses the same friendly text for usage_not_included.
79
+ // The stock SDK marks that HTTP 429 transient, while usage_limit_reached
80
+ // is non-transient. Require the native classification, not the phrase alone.
81
+ return status === 429 && (!assistant || (errorId & usageLimitErrorBit) !== 0)
82
+ && /^You have hit your ChatGPT usage limit(?: \([a-z0-9_-]+ plan\))?\.(?: Try again in ~\d+ min\.)?$/.test(message);
83
+ }
84
+ const openAiApi = failure.api === "openai-responses" || failure.api === "azure-openai-responses"
85
+ || failure.api === "openai-completions";
86
+ if (failure.api !== undefined && !openAiApi) return false;
87
+ const knownOpenAiWire = openAiApi || ["openai", "openai-api", "azure"].includes(failure.provider);
88
+ // Responses-API event and failed-response errors prefix the machine code.
89
+ if (knownOpenAiWire && !transient && /^(?:Error Code )?insufficient_quota: [\s\S]+$/.test(message)) return true;
90
+ // The captured HTTP formatter renders type, param and code in order but
91
+ // re-labels after omitting null fields. A lone param is not a machine code.
92
+ const http = /^(402|429) [\s\S]+ \(type=([a-z_]+)(?: param=([\w.-]+)(?: code=([\w.-]+))?)?\)$/.exec(message);
93
+ if (!http || (status === undefined ? !knownOpenAiWire : status !== Number(http[1]))
94
+ || (transient && status !== 429)) return false;
95
+ const [, , type, param, httpCode] = http;
96
+ // Stock SDK text classification adds Transient for the literal status prefix
97
+ // "429", even on HTTP billing caps. Override it only with the captured code
98
+ // or corroborating type and relabeled code, never the status or a lone type.
99
+ return httpCode === "insufficient_quota" || (httpCode === undefined && type === "insufficient_quota"
100
+ && (param === "insufficient_quota" || (param === undefined && knownOpenAiWire && !transient)));
101
+ }
102
+
103
+ function sessionExitWithoutPendingTools(entry: Record<string, unknown>): boolean {
104
+ if (entry.type !== "custom" || entry.customType !== "session_exit") return false;
105
+ const { reason, kind, pendingToolCalls } = object(entry.data);
106
+ return typeof reason === "string" && (kind === "normal" || kind === "signal" || kind === "fatal" || kind === "process_exit")
107
+ && (pendingToolCalls === undefined || (Array.isArray(pendingToolCalls) && pendingToolCalls.length === 0));
108
+ }
109
+
110
+ /** Recover one settled prompt from the journal suffix after its authenticated cursor. */
111
+ export function settledLaneReceipt(entries: unknown[], owner: {
112
+ readonly sessionId: string; readonly sessionFile: string; readonly requestId: string; readonly hostPid: number;
113
+ }): { frame: Record<string, unknown>; assistant?: Record<string, unknown> } | null {
114
+ if (!Number.isSafeInteger(owner.hostPid) || owner.hostPid <= 0) return null;
115
+ const owned = (data: Record<string, unknown>) => data.hostPid === owner.hostPid
116
+ && data.sessionId === owner.sessionId && data.sessionFile === owner.sessionFile;
117
+ let start: Record<string, unknown> | undefined;
118
+ let frame: Record<string, unknown> | undefined;
119
+ let assistant: Record<string, unknown> | undefined;
120
+ let userSeen = false;
121
+ for (const value of entries) {
122
+ const entry = object(value);
123
+ if (typeof entry.id !== "string" || typeof entry.type !== "string") return null;
124
+ if (frame) {
125
+ if (entry.type === "model_usage" || sessionExitWithoutPendingTools(entry)) continue;
126
+ // A later run, user/assistant, tool, or unknown effect prevents recovery.
127
+ return null;
128
+ }
129
+ if (entry.type === "custom" && entry.customType === "rpc_agent_start") {
130
+ const data = object(entry.data);
131
+ if (start || !owned(data) || typeof data.instanceKey !== "string" || !data.instanceKey
132
+ || typeof data.runOrdinal !== "number" || !Number.isSafeInteger(data.runOrdinal) || data.runOrdinal <= 0) return null;
133
+ start = data;
134
+ } else if (entry.type === "custom" && entry.customType === "rpc_prompt_result") {
135
+ const data = object(entry.data);
136
+ const receipt = object(data.frame);
137
+ if (!start || !userSeen || !owned(data) || data.instanceKey !== start.instanceKey
138
+ || data.runOrdinal !== start.runOrdinal || receipt.id !== owner.requestId || receipt.sessionSettled !== true
139
+ || receipt.agentInvoked !== true) return null;
140
+ frame = receipt;
141
+ } else if (entry.type === "custom" && entry.customType === "tool_execution_start" && (!start || !userSeen)) {
142
+ return null;
143
+ } else if (entry.type === "message") {
144
+ const message = object(entry.message);
145
+ if (message.role === "user") {
146
+ if (userSeen) return null;
147
+ userSeen = true;
148
+ } else if (message.role === "assistant") {
149
+ if (!start || !userSeen) return null;
150
+ assistant = message;
151
+ } else if (message.role === "toolResult" && (!start || !userSeen)) return null;
152
+ }
153
+ }
154
+ if (!frame) return null;
155
+ switch (frame.status) {
156
+ case "completed":
157
+ return assistant?.stopReason === "stop" || assistant?.stopReason === "length" ? { frame, assistant } : null;
158
+ case "aborted":
159
+ if (assistant?.stopReason === "aborted") return { frame, assistant };
160
+ // An owned abort can settle before the provider replies or while tools run.
161
+ return !assistant || assistant.stopReason === "toolUse" ? { frame } : null;
162
+ case "error":
163
+ return assistant?.stopReason === "error" ? { frame, assistant } : { frame };
164
+ default:
165
+ return null;
166
+ }
167
+ }
168
+
169
+ // Stock Usage.server counts provider-side tool requests, independently of
170
+ // whether the provider retained a tool block in the journal.
171
+ function usedServerTools(usage: unknown): boolean {
172
+ return Object.values(object(object(usage).server)).some(count => typeof count === "number" && count > 0);
173
+ }
174
+
175
+ // Opaque provider history can contain effects outside content. In content
176
+ // allow only passive blocks, not tools, images, or unknown future variants.
177
+ function passiveAssistantOutput({ content, providerPayload, usage }: Record<string, unknown>): boolean {
178
+ return providerPayload === undefined && !usedServerTools(usage) && Array.isArray(content) && content.every(part => {
179
+ const block = object(part);
180
+ switch (block.type) {
181
+ case "text": return typeof block.text === "string";
182
+ case "thinking": return typeof block.thinking === "string";
183
+ case "redactedThinking": return typeof block.data === "string";
184
+ case "fallback": return typeof object(block.from).model === "string" && typeof object(block.to).model === "string";
185
+ default: return false;
186
+ }
187
+ });
188
+ }
189
+
7
190
  /** Only journal identities and native outcome fields leave this evidence reader. */
8
191
  export function headRecoveryEvidence(entries: unknown[], owner: Pick<HeadRecoveryAttempt,
9
192
  "sessionId" | "sessionFile" | "requestId" | "cursor">, boundary?: string) {
@@ -44,12 +227,77 @@ export function headRecoveryEvidence(entries: unknown[], owner: Pick<HeadRecover
44
227
  else if (latestStart && (latestRunStatus === "stop" || latestRunStatus === "length")) outcome = "done";
45
228
  else if (latestStart && latestRunStatus === "aborted") outcome = "cancelled";
46
229
  }
230
+ const error = object(frame.error);
231
+ const failedAt = typeof receipt.timestamp === "string" ? Date.parse(receipt.timestamp) : NaN;
232
+ const receiptIndex = slice.indexOf(receipt);
233
+ const sameRun = typeof receiptData.hostPid === "number" && Number.isSafeInteger(receiptData.hostPid)
234
+ && receiptData.hostPid > 0 && typeof receiptData.instanceKey === "string" && receiptData.instanceKey !== ""
235
+ && typeof receiptData.runOrdinal === "number" && Number.isSafeInteger(receiptData.runOrdinal) && receiptData.runOrdinal > 0
236
+ && receiptData.hostPid === startData.hostPid && receiptData.instanceKey === startData.instanceKey
237
+ && receiptData.runOrdinal === startData.runOrdinal;
238
+ // The exact settled run failed before any tool started: only its prompt,
239
+ // passive failed model/refusal output and usage records exist. An earlier
240
+ // tool, another request or unknown journal entry leaves effects unproven.
241
+ const settledToolFreeError = frame.status === "error" && frame.sessionSettled === true && frame.agentInvoked === true
242
+ && sameRun && users.length === 1 && receiptIndex > latestStartIndex
243
+ && slice.every((entry, index) => {
244
+ if (typeof entry.id !== "string") return false;
245
+ if (entry.type === "model_usage") return !usedServerTools(entry.usage);
246
+ if (entry === receipt) return true;
247
+ // These stock restart records don't start work. Arbitrary custom
248
+ // messages can trigger another turn; unknown custom entries prove nothing.
249
+ if (index > receiptIndex) {
250
+ if (entry.type === "custom_message" && entry.customType === "eval-state-context") return typeof entry.content === "string";
251
+ return sessionExitWithoutPendingTools(entry) && typeof object(entry.data).recordedAt === "string";
252
+ }
253
+ if (matches(entry, "rpc_agent_start")) {
254
+ const start = object(entry.data);
255
+ return start.hostPid === receiptData.hostPid && start.instanceKey === receiptData.instanceKey
256
+ && typeof start.runOrdinal === "number" && Number.isSafeInteger(start.runOrdinal)
257
+ && start.runOrdinal > 0 && start.runOrdinal <= Number(receiptData.runOrdinal);
258
+ }
259
+ if (entry.type === "custom" && entry.customType === "provider_refusal") {
260
+ const refusal = object(entry.data);
261
+ return (refusal.stopType === "refusal" || refusal.stopType === "sensitive") && passiveAssistantOutput(refusal);
262
+ }
263
+ if (entry.type !== "message") return false;
264
+ const message = object(entry.message);
265
+ return message.role === "user" || message.role === "assistant" && message.stopReason === "error" && passiveAssistantOutput(message);
266
+ });
267
+ const quotaLikeText = (value: unknown): boolean => typeof value === "string"
268
+ && /(?:usage_limit_reached|insufficient_quota|quota_exceeded|usage_limit|usage limit|quota)/i.test(value);
269
+ const quotaLikeFailure = laneQuotaExhausted(error) || quotaLikeText(error.message) || quotaLikeText(error.code) || quotaLikeText(error.type)
270
+ || slice.some(entry => {
271
+ if (entry.type !== "message") return false;
272
+ const message = object(entry.message);
273
+ return message.role === "assistant"
274
+ && (laneQuotaExhausted(message) || quotaLikeText(message.errorMessage) || quotaLikeText(message.error));
275
+ });
276
+ // The exact provider refused the entire turn for quota. A partial answer or
277
+ // another provider's reply makes it something other than a quota hold.
278
+ const quotaFailure: HeadQuotaFailure | null = settledToolFreeError
279
+ && error.provider === "openai-codex" && typeof error.model === "string" && error.model !== ""
280
+ && error.retryable === false && typeof error.message === "string"
281
+ // Stock OMP's RPC error lacks a structured quota code. Match either
282
+ // native Codex formatter, but require the exact code in its metadata.
283
+ && codexFailureCode.exec(error.message)?.[1] === "usage_limit_reached"
284
+ && Number.isFinite(failedAt) && latestRunStatus === "error"
285
+ && slice.slice(receiptIndex + 1).every(entry => entry.type === "model_usage")
286
+ && slice.every(entry => {
287
+ if (entry.type === "custom") return entry.customType !== "provider_refusal";
288
+ const message = object(entry.message);
289
+ return entry.type !== "message" || message.role !== "assistant" || message.provider === error.provider
290
+ && message.model === error.model && Array.isArray(message.content) && message.content.length === 0;
291
+ })
292
+ ? { failedAt, model: { provider: error.provider, id: error.model } } : null;
293
+ // Quota-like refusals stay held unless native quota recovery proves safe release.
294
+ const toolFreeFailure = settledToolFreeError && !quotaFailure && !quotaLikeFailure;
47
295
  const selected = [receipt, ...starts, ...assistants];
48
296
  if (selected.some(entry => typeof entry.id !== "string")) return null;
49
297
  const entryIds = [...new Set(selected.map(entry => String(entry.id)))];
50
298
  const proof = { entryIds, receiptStatus: String(frame.status), latestRunStatus: latestRunStatus ?? null,
51
299
  outcome: outcome ?? null };
52
- return { ...proof, boundary: String(journal[end]!.id),
300
+ return { ...proof, settledToolFreeError, toolFreeFailure, quotaFailure, boundary: String(journal[end]!.id),
53
301
  fingerprint: createHash("sha256").update(JSON.stringify(slice.map(entry => [
54
302
  entry.id, entry.type, entry.customType,
55
303
  matches(entry, "rpc_prompt_result") ? object(entry.data).frame : null,