Dashboard › opencode-lore › Session 14z1KW1Xrje7
14z1KW1Xrje7cV1kpIndependent READ-ONLY adversarial correctness review of immutable candidate in /home/byk/Code/opencode-lore-recall-recovery. Base literal 2cbf40060c67df229731cf1b9e34d5bf22ec2145; head stable change spyyzvyyyqxs, commit 3f3ae768fde5; expected plain range-diff SHA-256 0bb7846a803d07be809d2cbd5220ad78aa8503c56eddb3efcd5c5dea8c29beed. Do not edit/format/install/mutate VCS/server/network/production DB or rerun exhaustive suite. Read AGENTS.md, quality/REVIEW.md, root/gateway scripts. Verify identity/status/conflicts/files/hash at start/end. Inspect every changed line across exactly the 11 cumulative files and relevant callers/tests. Focus adversarially on: exactly one recovery synthesis after accepted recall failure; frozen accepted request/response and route/credentials/deadline; stream/consumer coupling; no provider cache controls; strict protocol-complete recovery envelopes for Anthropic, Vertex, OpenAI Chat, Responses/Codex, Gemini; response identity/model/role/usage/tool-status/finish semantics; repeated recall and unusable reasoning-only/empty output independently rejected; no warning-only success; quota metadata schema/privacy/dedup/order/request-wide event+byte bounds across buffered and live chains; usage overflow atomicity; JSON/SSE mismatch cleanup; non-settling cancellation; fixed logging; EOF-only transactional persistence; cancellation/backpressure/rollback/exact-once accounting. Examine fail-first and guard-removal discrimination, including both live quota append sites. Run only focused checks if essential. Report each finding PASS/CONCERN/MUST-FIX with exact current file:line and concrete failure. Never return empty; state blockers. End exactly MERGE or DO-NOT-MERGE.
<skill_content name="jj-guide"> # Skill: jj-guide # jj Guide for AI Agents Jujutsu (jj) is a Git-compatible VCS with mutable commits, automatic snapshotting, no staging area, and first-class conflicts. This skill teaches you how to use it safely from a non-interactive agent environment. If `.jj/` exists in the repo root, this is a jj repo. **Use `jj` commands, not `git`.** In a colocated repo (`.jj/` *and* `.git/`), git tools can read the state, but mutations should go through `jj` so the operation log stays consistent. ## Critical Rules - **NEVER** use interactive flags (`-i`, `--interactive`). TUI prompts hang in agent environments. This applies to `jj split -i`, `jj squash -i`, `jj commit -i`, `jj resolve`, `jj diffedit`, etc. - **ALWAYS** pass `-m "msg"` when describing/committing. Without `-m`, an editor opens and hangs. - **VERIFY** mutations with `jj st` and `jj log` after `squash`, `abandon`, `rebase`, `restore`, `commit`. ...
/home/byk/Code/opencode-lore-recall-recovery The working copy has no changes. Working copy (@) : rkqkzwmo e8fbf605 (empty) (no description set) Parent commit (@-): spyyzvyy 3f3ae768 fix/recall-failure-synthesis | fix(recall): validate recovery metadata Warning: These bookmarks have conflicts: fix/responses-private-references Hint: Use `jj bookmark list` to see details. Use `jj bookmark set <name> -r <rev>` to resolve. rkqkzwmozkxz e8fbf605d765379e541ce09cd5f2f9b8c126d883 parents=3f3ae768fde5b08b5c8e5dced647e361fddfd5aa conflict=false empty=true description= spyyzvyyyqxs 3f3ae768fde5b08b5c8e5dced647e361fddfd5aa parents=b61b086186cb6a2219bdd40c96a0bba602dae3b2 conflict=false empty=false description=fix(recall): validate recovery metadata pxrvwsvvkmpo 2cbf40060c67df229731cf1b9e34d5bf22ec2145 parents=e977b4b1da8f8197c3238466d41de0bccd8eb054 conflict=false empty=false description=feat(cch): add seeds for Claude Code up to 2.1.272 (#1780) --- changed files ...
<path>/home/byk/Code/opencode-lore-recall-recovery/AGENTS.md</path> <type>file</type> <content> 1: <!-- This section is maintained by the coding agent via lore (https://github.com/BYK/loreai) --> 2: ## Long-term Knowledge 3: 4: For long-term knowledge entries managed by [lore](https://github.com/BYK/loreai) (gotchas, patterns, decisions, architecture), see [`.lore.md`](.lore.md) in the project root. 5: <!-- End lore-managed section --> 6: 7: ## Review 8: 9: See [`quality/REVIEW.md`](quality/REVIEW.md) for the review heuristics and workflow — regression-test discipline, adversarial-order state setup, fan-out registry coverage, recurring bug-class batteries, and the two-reviewer rule. Every non-trivial PR requires an adversarial correctness review before merge. 10: 11: # Project Overview 12: 13: Lore is a **three-tier memory architecture** for AI coding agents. ...
<path>/home/byk/Code/opencode-lore-recall-recovery/quality/REVIEW.md</path> <type>file</type> <content> 1: # Review Heuristics — Lore 2: 3: This document codifies the review bar for pull requests. It exists because 4: adversarial review has repeatedly caught correctness bugs that a green test 5: suite missed — skip/early-return branches, lifecycle sequences, and fan-out 6: registry gaps. Institutionalizing these patterns so they compound. 7: 8: The review workflow (§6) is referenced from AGENTS.md. 9: 10: --- 11: 12: ## 1. Regression-test discipline 13: 14: Every adversarial-review finding that surfaces a defect **must** land a 15: deterministic regression test in the same PR. The test: 16: - fails on the base branch (proving it reproduces the bug), 17: - passes on the fix (proving the fix works), 18: - drives the *real* precondition, not an artificially-constructed state (e.g. ...
<path>/home/byk/Code/opencode-lore-recall-recovery/package.json</path>
<type>file</type>
<content>
1: {
2: "name": "lore-monorepo",
3: "private": true,
4: "type": "module",
5: "license": "FSL-1.1-Apache-2.0",
6: "description": "Monorepo root for Lore — three-tier memory architecture",
7: "main": "./packages/opencode/src/index.ts",
8: "exports": {
9: ".": "./packages/opencode/src/index.ts"
10: },
11: "packageManager": "pnpm@10.28.0",
12: "volta": {
13: "node": "24.16.0",
14: "pnpm": "10.28.0"
15: },
16: "pnpm": {
17: "onlyBuiltDependencies": [
18: "esbuild",
19: "onnxruntime-node",
20: "sharp"
21: ],
22: "overrides": {
23: "basic-ftp": "5.3.1",
24: "ip-address": "10.2.0",
25: "fast-xml-parser": "5.7.3",
26: "@huggingface/hub": "2.11.0",
27: "onnxruntime-node": "1.27.0",
28: "yaml": ">=2.8.3",
29: "esbuild": ">=0.28.1",
30: "@opentelemetry/core": ">=2.8.0",
31: ...
<path>/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/package.json</path>
<type>file</type>
<content>
1: {
2: "name": "@loreai/gateway",
3: "version": "0.40.0",
4: "type": "module",
5: "license": "FSL-1.1-Apache-2.0",
6: "description": "Lore as a transparent LLM proxy — context management for any AI coding client",
7: "main": "./dist/index.cjs",
8: "types": "./dist/index.d.cts",
9: "exports": {
10: ".": {
11: "types": "./dist/index.d.cts",
12: "bun": "./dist/index.bun.js",
13: "require": "./dist/index.cjs",
14: "default": "./dist/index.cjs"
15: }
16: },
17: "bin": {
18: "lore": "./dist/bin.cjs",
19: "lore-gateway": "./dist/bin.cjs"
20: },
21: "scripts": {
22: "typecheck": "tsc --noEmit",
23: "build": "tsx script/build.ts",
24: "bundle": "tsx script/bundle.ts",
25: "build:binary": "tsx script/build.ts --binary",
26: "build:binary:sea": "tsx script/build-binary-sea.ts",
27: "start": ...
No files found
packages/gateway/src/codex-rate-limits.ts | 120 ++++ packages/gateway/src/pipeline.ts | 409 +++++++++++---- packages/gateway/src/recall.ts | 132 +++- packages/gateway/src/stream/openai-responses.ts | 74 +- packages/gateway/src/translate/openai-responses.ts | 5 +- packages/gateway/test/codex-usage-metadata.test.ts | 133 +++- ...est/openai-responses-recall-aware-stream.test.ts | 68 ++ packages/gateway/test/pipeline-streaming.test.ts | 440 +++++++++++++--- ...gateway/test/recall-buffered-transaction.test.ts | 597 +++++++++++++++++++++- packages/gateway/test/recall-exhaustion.test.ts | 51 +- packages/gateway/test/recall.test.ts | 297 +++++++++- 11 files changed, 2105 insertions(+), 221 deletions(-)
Added regular file packages/gateway/src/codex-rate-limits.ts:
1: export const MAX_CODEX_RATE_LIMIT_EVENTS = 64;
2: export const MAX_CODEX_RATE_LIMIT_BYTES = 16 * 1024;
3:
4: const encoder = new TextEncoder();
5:
6: const CATEGORY = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
7: const DECIMAL = /^(?:0|[1-9][0-9]{0,23})(?:\.[0-9]{1,12})?$/;
8:
9: function isRecord(value: unknown): value is Record<string, unknown> {
10: return value !== null && typeof value === "object" && !Array.isArray(value);
11: }
12:
13: function category(value: unknown): string | undefined {
14: return typeof value === "string" && CATEGORY.test(value) ? value : undefined;
15: }
16:
17: function rateLimit(value: unknown): Record<string, unknown> | undefined {
18: if (!isRecord(value)) return undefined;
19: const result: Record<string, unknown> = {};
20: if (
...
Modified regular file packages/gateway/src/recall.ts:
...
1115 1115: input: { query, scope, id, ids, detailOffset, detailLimit },
1116 1116: coverage: recall.coverage,
1117 1117: };
1118 : } catch (e) {
1118: } catch {
1119 1119: if (signal?.aborted) throw signal.reason;
1120 : log.error("gateway recall execution failed:", e);
1120: const diagnostic = new Error("gateway recall execution failed");
1121: diagnostic.name = "RecallExecutionError";
1122: log.error(diagnostic);
1121 1123: return {
1122 1124: result: "Recall search failed. The memory system encountered an error.",
1123 1125: input: { query, scope, id, ids, detailOffset, detailLimit },
...
1325 1327: };
1326 1328: }
1327 1329:
1330: const RECALL_RECOVERY_INSTRUCTION =
1331: "Continue the user's task using the accepted recall results and the context already available. ...
Modified regular file packages/gateway/src/stream/openai-responses.ts:
...
34 34: safeTokenSum,
35 35: validateResponsesUsage,
36 36: } from "../usage-validation";
37: import { appendCodexRateLimitEvent } from "../codex-rate-limits";
37 38:
38 39: // ---------------------------------------------------------------------------
39 40: // Stream accumulator — shared per-event core
...
251 252: return OUTPUT_ITEM_STATUSES_BY_TYPE[type]?.[phase]?.has(status) ?? false;
252 253: }
253 254:
255: export function assertSuccessfulResponsesCompletion(
256: response: Record<string, unknown>,
257: ): void {
258: const usage = validateResponsesUsage(
259: response.usage,
260: "malformed Responses usage",
261: );
262: if (
263: response.status !== "completed" ||
264: !isNonEmptyString(response.id) ||
265: !isNonEmptyString(response.model) ||
266: ...
Modified regular file packages/gateway/src/translate/openai-responses.ts:
...
21 21: GatewayTool,
22 22: GatewayUsage,
23 23: } from "./types";
24: import { sanitizeCodexRateLimitEvents } from "../codex-rate-limits";
24 25: import {
25 26: blocksToText,
26 27: forwardClientHeaders,
...
1278 1279:
1279 1280: // Buffered Codex responses still carry subscription windows and credits.
1280 1281: // These values are independent of the token usage Lore may rescale.
1281 : for (const quota of resp.codexRateLimits ?? []) {
1282: for (const quota of sanitizeCodexRateLimitEvents(
1283: resp.codexRateLimits ?? [],
1284: )) {
1282 1285: emit("codex.rate_limits", quota);
1283 1286: }
1284 1287:
...
Modified regular file packages/gateway/src/pipeline.ts:
...
213 213: responsesDoneItemMatchesAdded,
214 214: responsesTerminalItemMatches,
215 215: normalizeCodexResponsesEvent,
216: assertSuccessfulResponsesCompletion,
216 217: ResponsesTerminalError,
217 218: type ResponsesAccState,
218 219: } from "./stream/openai-responses";
219 220: import {
221: appendCodexRateLimitEvent,
222: sanitizeCodexRateLimitEvents,
223: } from "./codex-rate-limits";
224: import {
220 225: accumulateOpenAISSEStream,
221 226: translateAnthropicStreamToOpenAI,
222 227: } from "./stream/openai";
...
233 238: safeTokenSum,
234 239: validateOpenAIUsage,
235 240: validateResponsesUsage,
241: validateAnthropicUsage,
242: validateGeminiUsageMetadata,
236 243: } from "./usage-validation";
237 244: import {
238 245: accumulateSSEResponse,
... ...
Found 37 matches /home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/pipeline.ts: Line 402: runRecallRecovery, Line 707: let pipelineResponseReadFailureForTest: Line 868: pipelineResponseReadFailureForTest = failure; Line 1030: pipelineResponseReadFailureForTest = undefined; Line 15242: onResponseBodyCompleted?: () => void, Line 15337: onResponseBodyCompleted, Line 15338: () => pipelineResponseReadFailureForTest, Line 16215: downstreamCompleted: () => boolean, Line 18245: const cumulativeCodexRateLimits = sanitizeCodexRateLimitEvents( Line 18294: ...(cumulativeCodexRateLimits.length > 0 Line 18295: ? ...
Modified regular file packages/gateway/test/codex-usage-metadata.test.ts:
...
7 7: } from "../src/stream/openai-responses";
8 8: import { buildOpenAIResponsesResponse } from "../src/translate/openai-responses";
9 9:
10: const MAX_CODEX_RATE_LIMIT_EVENTS = 64;
11: const MAX_CODEX_RATE_LIMIT_BYTES = 16 * 1024;
12:
10 13: const limits = {
11 14: type: "codex.rate_limits",
12 15: plan_type: "pro",
...
150 153: expect(quotaEvents(await response.text())).toEqual([limits]);
151 154: });
152 155:
156: test.each(["buffered", "passthrough"] as const)(
157: "%s projection rebuilds quota metadata from the private allowlist",
158: async (mode) => {
159: const sentinel = "private diagnostic\nforged log line";
160: const hostile = {
161: ...limits,
162: plan_type: sentinel,
163: metered_limit_name: sentinel,
164: ...
Modified regular file packages/gateway/test/openai-responses-recall-aware-stream.test.ts:
...
230 230: expect(out).not.toContain("response.failed");
231 231: });
232 232:
233: test("bounds Codex quota metadata across the principal and continuation", async () => {
234: const quota = (index: number) =>
235: sseEvent("codex.rate_limits", {
236: metered_limit_name: `bucket_${index}`,
237: rate_limits: {
238: primary: {
239: used_percent: index,
240: window_minutes: 300,
241: reset_at: 2000000000 + index,
242: },
243: },
244: });
245: const principalQuotas = Array.from({ length: 40 }, (_, index) => [
246: quota(index),
247: quota(index),
248: ]).flat();
249: const continuationQuotas = Array.from({ length: 40 }, (_, index) => [
250: ...
Modified regular file packages/gateway/test/recall-exhaustion.test.ts:
...
230 230: "refusal",
231 231: "unfinished",
232 232: ] as const)("final result %s", async (mode) => {
233: const requiresRecovery =
234: !stream &&
235: (mode === "recall" ||
236: mode === "failed" ||
237: mode === "reasoning" ||
238: mode === "unfinished");
233 239: let recallCalls = 0;
234 240: vi.mocked(executeRecall).mockImplementation(async () => {
235 241: recallCalls++;
... ...
Modified regular file packages/gateway/test/pipeline-streaming.test.ts:
...
58 58: resetPipelineState,
59 59: scheduleStreamingPostResponseForTest,
60 60: setPipelinePreUpstreamPauseForTest,
61: setPipelineResponseReadFailureForTest,
61 62: setMaxActivePipelineRequestsForTest,
62 63: setMaxDetachedPipelineRequestsForTest,
63 64: setPipelineResetSettleTimeoutForTest,
...
519 520: }
520 521: });
521 522:
522 : it("accounts typed failed JSON recall follow-up usage in the fallback turn", async () => {
523 : clearAllCosts();
524 : let call = 0;
525 : setUpstreamInterceptor(async () => {
526 : call++;
527 : if (call === 1) {
523: it.each([
524: "tool",
525: "malformed",
526: "repeated-recall",
527: "overflow",
528: "failed-overflow",
529: "recall-plus-text",
530: "reasoning-only",
531: ...
Modified regular file packages/gateway/test/recall-buffered-transaction.test.ts:
...
26 26: recallAnchorContext,
27 27: MAX_RECALL_STORE_ENTRIES,
28 28: } from "../src/recall";
29: import { _setTestVertexTokenProvider } from "../src/vertex-auth";
29 30:
30 31: afterEach(async () => {
31 32: setUpstreamInterceptor(undefined);
...
37 38: productiveRecallIds = undefined;
38 39: vi.restoreAllMocks();
39 40: resetWorkerHealth();
41: _setTestVertexTokenProvider(null);
40 42: });
41 43:
42 44: test.each(["absent", "different-bucket"] as const)(
...
112 114: },
113 115: );
114 116:
117: test("buffered Codex recovery preserves accepted, failed, and recovered quota updates in order", async () => {
118: knowledge();
119: const alias = crypto.randomUUID();
120: const req = request("openai-responses", alias, true);
121: setUpstreamInterceptor(async () =>
...
Modified regular file packages/gateway/test/recall.test.ts:
...
9 9: * - Response stripping
10 10: */
11 11: import { describe, test, expect, vi } from "vitest";
12: import { log } from "@loreai/core";
12 13: import {
13 14: LORE_COMMIT_REMINDER,
14 15: accumulateOpenAINonStreamJSON,
...
28 29: hasOtherToolUse,
29 30: clientHasRecallTool,
30 31: buildRecallFollowUpRequest,
32: buildRecallRecoveryRequest,
31 33: runRecallFollowUpStreaming,
32 34: runRecallFollowUpJSON,
33 35: runRecallFollowUpStreamAccumulated,
36: runRecallRecovery,
34 37: type RecallFollowUpCtx,
35 38: buildRecallMarker,
36 39: buildRecallAnchor,
...
269 272: "Recall search failed. The memory system encountered an error.",
270 273: );
271 274: });
275:
276: test("logs malformed recall input through a fixed error envelope", async () => {
277: const ...
<path>/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/recall.ts</path>
<type>file</type>
<content>
1200: if (
1201: resp.content.some(
1202: (block) =>
1203: block.type === "tool_use" &&
1204: (typeof block.name !== "string" || block.name.trim().length === 0),
1205: )
1206: )
1207: return false;
1208: return (
1209: resp.content.some((block) => {
1210: if (block.type === "text") return block.text.trim().length > 0;
1211: if (block.type === "tool_use") return block.name !== RECALL_TOOL_NAME;
1212: return (
1213: block.type === "opaque" &&
1214: block.responsesItem === true &&
1215: hasResponsesRefusal(block.raw)
1216: );
1217: }) ||
1218: // Buffered Responses refusals live only in the lossless raw output items.
1219: (resp.rawOutputItems?.some(hasResponsesRefusal) ?? ...
<path>/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/pipeline.ts</path>
<type>file</type>
<content>
18040: try {
18041: await completeBudgetThrottleDelay(
18042: actualDelay * 1000,
18043: foregroundAbort.signal,
18044: () => {
18045: const costs = getSessionCosts(sessionID);
18046: if (costs) {
18047: costs.throttle.events++;
18048: costs.throttle.totalDelayMs += actualDelay * 1000;
18049: }
18050: },
18051: );
18052: } catch (error) {
18053: foregroundAbort.dispose();
18054: throw error;
18055: }
18056: }
18057: }
18058: }
18059: assertCurrentPipelineGeneration(req.signal, requestGeneration);
18060:
18061: // Start gen_ai.chat span before the upstream call so it captures real
18062: // wall-clock duration (including network latency and streaming time). ...
<path>/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/pipeline.ts</path>
<type>file</type>
<content>
18720: dropStreamingFinalizer();
18721: return;
18722: }
18723: if (downstreamWasCancelled() || !downstreamCompleted()) {
18724: rollbackRecallPersistence();
18725: accountUnsuccessfulResponse(
18726: resp,
18727: sessionState.sessionID,
18728: sessionState.resolvedConversationTTL,
18729: genAiSpan,
18730: endGenAiSpan,
18731: () => {
18732: sessionState._dirty = true;
18733: },
18734: );
18735: return;
18736: }
18737: try {
18738: const postResponseFailed = new Error(
18739: "Responses recall post-response persistence failed",
18740: );
18741: try {
18742: withTenant(sessionState.storageTenantId ?? ...
<path>/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/pipeline.ts</path>
<type>file</type>
<content>
11870: headers.set("retry-after-ms", boundedRetryAfterMsValue);
11871: }
11872: return new Response(
11873: JSON.stringify({
11874: type: "error",
11875: error: { type: "server_error", message: "Gateway request failed" },
11876: }),
11877: { status: response.status, headers },
11878: );
11879: }
11880:
11881: export async function readForegroundBody(
11882: response: Response,
11883: diagnostic: boolean,
11884: onTruncated?: () => void,
11885: signal?: AbortSignal,
11886: ): Promise<string> {
11887: const limit = diagnostic
11888: ? MAX_FOREGROUND_ERROR_BYTES
11889: : MAX_FOREGROUND_RESPONSE_BYTES;
11890: const reader = response.body?.getReader();
11891: if (!reader) return "";
11892: const chunks: Uint8Array[] = [];
11893: let bytes = 0;
11894: try {
11895: for (;;) {
11896: const { done, value ...
Found 18 matches /home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/pipeline.ts: Line 238: safeTokenSum, Line 7172: recallBudget.recordUsage(currentResp.usage); Line 7182: ? mergeRecallUsage( Line 7623: cumulativeUsage = mergeRecallUsage( Line 7628: const continuationStopReason = recallBudget.recordUsage( Line 10517: recallBudget.recordUsage(state.usage); Line 11220: recallBudget.recordUsage(contState.usage); Line 16139: export function mergeRecallUsage( Line 16144: inputTokens: safeTokenSum( Line 16148: outputTokens: safeTokenSum( Line 16157: merged.cacheReadInputTokens = safeTokenSum( Line 16166: merged.cacheCreationInputTokens = safeTokenSum( Line 16171: safeTokenSum( Line 18254: recallBudget.recordUsage(resp.usage); Line 18429: mergeRecallUsage( Line 18494: ...
<path>/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/pipeline.ts</path>
<type>file</type>
<content>
16080: * Check whether the upstream prompt cache is likely still warm for this
16081: * session. Returns true when a warmup ping was successfully sent within
16082: * the current cache TTL window.
16083: *
16084: * When true, post-idle compaction should be skipped: the warmer replayed
16085: * the full (uncompacted) request body, so compacting now would produce
16086: * different bytes and bust the cache the warmer just paid to preserve.
16087: */
16088: function isCacheWarm(state: SessionState): boolean {
16089: const warmup = state.warmup;
16090: // Require at least one successful warmup before claiming warm.
16091: // This also gates the forceKeepWarm early-return below.
16092: if (!warmup?.lastWarmupAt) return false;
16093:
16094: const profile = resolveWarmingProfile(
16095: state.lastUpstream?.model,
16096: ...
Found 11 matches
/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/stream/openai-responses.ts:
Line 612: export function applyResponsesEvent(
Line 1410: applyResponsesEvent(state, "response.output_item.added", {
Line 1614: applyResponsesEvent(state, "response.output_item.added", {
Line 1784: applyResponsesEvent(state, event, parsed);
Line 2187: const acceptedCodexRateLimit = applyResponsesEvent(state, event, parsed);
Line 2279: applyResponsesEvent(state, "response.output_item.done", {
/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/pipeline.ts:
Line 8390: applyResponsesEvent(state, "response.output_item.added", {
Line 9162: applyResponsesEvent(acc, "response.output_item.added", {
Line 9443: applyResponsesEvent(acc, "response.output_item.done", {
Line 10259: const acceptedCodexRateLimit = applyResponsesEvent(
Line 10867: const ...
<path>/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/stream/openai-responses.ts</path>
<type>file</type>
<content>
1880: }
1881: }
1882: }
1883: }
1884:
1885: /**
1886: * Accumulate an OpenAI Responses API SSE stream into a GatewayResponse.
1887: *
1888: * Consumes the upstream Response body and returns the accumulated result.
1889: */
1890: export async function accumulateResponsesSSEStream(
1891: response: Response,
1892: opts: {
1893: /** Omit to preserve the legacy tolerant accumulator behavior. */
1894: validation?: ResponsesValidationMode;
1895: stopAtTerminal?: boolean;
1896: signal?: AbortSignal;
1897: inactivityMs?: number;
1898: maxFrames?: number;
1899: onSemanticContent?: () => void;
1900: /** Called only after the event has passed strict validation and mutation. */
1901: onValidatedEvent?: (event: string, data: string) => void | Promise<void>;
1902: /** Passthrough clients must receive a ...
<path>/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/stream/openai-responses.ts</path>
<type>file</type>
<content>
560: return snapshot;
561: }
562: const finalizedContent = finalizedResponsesMessageContent(
563: outputIndex,
564: terminalContentParts,
565: ).map((part) =>
566: part.kind === "text"
567: ? { type: "output_text", text: part.value }
568: : { type: "refusal", refusal: part.value },
569: );
570: return finalizedContent.length > 0
571: ? { ...snapshot, content: finalizedContent }
572: : snapshot;
573: }
574:
575: /** Validated unsuccessful terminal, carrying usage for accounting-only paths. */
576: export class ResponsesTerminalError extends Error {
577: constructor(
578: readonly response: GatewayResponse,
579: readonly status: string,
580: ) {
581: super(`upstream Responses request ended with status ${status}`);
582: this.name = "ResponsesTerminalError";
583: }
584: }
585:
586: export ...
Found 2 matches
/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/stream/openai-responses.ts:
Line 618: case "codex.rate_limits": {
Line 2380: if (event !== "codex.rate_limits" || acceptedCodexRateLimit) {
Found 3 matches /home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/stream/openai-responses.ts: Line 1642: function validateCodexResponsesEvent( Line 1773: validateCodexResponsesEvent(state, event, parsed, maxSparseIndex); Line 1987: validateCodexResponsesEvent(state, event, parsed, maxSparseIndex);
<path>/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/stream/openai-responses.ts</path>
<type>file</type>
<content>
1570: providedIndex !== undefined &&
1571: itemIndex !== undefined &&
1572: providedIndex !== itemIndex
1573: ) {
1574: malformedResponsesEvent();
1575: }
1576:
1577: let outputIndex = providedIndex ?? itemIndex;
1578: const kind = codexItemKind(item);
1579: if (
1580: outputIndex === undefined &&
1581: event === "response.output_item.done" &&
1582: kind
1583: ) {
1584: if (itemId === undefined) {
1585: outputIndex = soleCodexItem(codexItemSet(state, kind));
1586: } else {
1587: const unbound = soleCodexItem(codexItemSet(state, kind, true));
1588: if (unbound !== undefined) {
1589: outputIndex = unbound;
1590: bindCodexItemId(state, outputIndex, itemId);
1591: } else if (codexItemSet(state, kind).size > 0) {
1592: malformedResponsesEvent();
1593: ...
Found 93 matches
/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/pipeline.ts:
Line 487: * A short, capability-framed note telling the agent that Lore is actively
Line 2040: * gap past this TTL re-warms the SAME frozen bytes rather than rebuilding from
Line 2114: * system[2] would render the same bytes — no content change hides here),
Line 2163: * desc, updated_at desc) so the frozen bytes never depend on call order.
Line 3704: * alone — the 1h pinned bytes must not churn).
Line 4926: // hydrating instead of trusting those historical header bytes.
Line 5120: `OpenRouter provider routing options exceed ${MAX_PROVIDER_OPTIONS_BYTES} bytes`,
Line 6375: /** Repeat the exact prepared request bytes, headers, route, and interceptor. ...
<path>/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/pipeline.ts</path>
<type>file</type>
<content>
7770: if (!sourceSucceeded || cancelled || streamSignal.aborted) {
7771: recallPersistence.rollback();
7772: return;
7773: }
7774: try {
7775: withTenant(recallContext?.sessionState.storageTenantId ?? "", () =>
7776: withSavepoint("native_recall_delivery", recallPersistence.commit),
7777: );
7778: } catch (error) {
7779: recallPersistence.rollback();
7780: throw error;
7781: }
7782: },
7783: streamSignal,
7784: recallPersistence.rollback,
7785: );
7786: }
7787:
7788: /**
7789: * True-streaming, recall-aware variant of `streamResponsesPassthrough` for the
7790: * OpenAI Responses API (codex/ChatGPT) — used when the request carries the
7791: * gateway-injected `recall` tool but the client speaks the Responses API. ...
Found 7 matches
/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/recall.ts:
Line 44: import { promiseAgainstAbort } from "./abort-race";
Line 1425: const { done, value } = await promiseAgainstAbort(
Line 1487: const { done, value } = await promiseAgainstAbort(
Line 1538: return await promiseAgainstAbort(parse, signal);
Line 1599: const { response } = await promiseAgainstAbort(
Line 1660: const { response, effectiveProtocol } = await promiseAgainstAbort(
Line 1738: const { response } = await promiseAgainstAbort(
<path>/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/abort-race.ts</path>
<type>file</type>
<content>
1: /**
2: * Settle a Response-producing operation against an AbortSignal even when the
3: * underlying implementation ignores that signal. Late responses are drained
4: * by cancellation and late rejections stay observed.
5: */
6: export function promiseAgainstAbort<T>(
7: start: () => Promise<T>,
8: signal?: AbortSignal,
9: onLateResolve?: (value: T) => void,
10: ): Promise<T> {
11: if (!signal) return start();
12: signal.throwIfAborted();
13:
14: return new Promise<T>((resolve, reject) => {
15: let settled = false;
16: const cleanup = (): void => signal.removeEventListener("abort", onAbort);
17: const onAbort = (): void => {
18: if (settled) return;
19: settled = true;
20: cleanup();
21: reject(signal.reason);
22: };
23:
24: signal.addEventListener("abort", onAbort, { once: true });
25: if ...
Found 16 matches /home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/pipeline.ts: Line 138: resolveUpstreamRoute, Line 6206: modelRoute: ReturnType<typeof resolveUpstreamRoute>; Line 6290: const modelRoute = resolveUpstreamRoute(req.model); Line 16334: const requestUpstreamRoute = captureRequestUpstream( Line 16520: requestUpstreamRoute.providerID ?? Line 16521: (requestUpstreamRoute.effectiveProtocol === "anthropic" Line 16523: : requestUpstreamRoute.effectiveProtocol === "openai" || Line 16524: requestUpstreamRoute.effectiveProtocol === "openai-responses" Line 16526: : requestUpstreamRoute.effectiveProtocol === "gemini" Line 16653: resolveUpstreamRoute(req.model)?.url ?? Line 18071: requestUpstreamRoute.providerID ?? Line 18072: requestUpstreamRoute.effectiveProtocol, Line 18122: requestUpstreamRoute, Line 18456: requestUpstreamRoute, ...
<path>/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/pipeline.ts</path>
<type>file</type>
<content>
6160: provisionalIdentity: true,
6161: provisionalKey: indexKey,
6162: };
6163: }
6164: }
6165: return { sessionID: bestMatch.sid, isNew: false, tier: 3 };
6166: }
6167:
6168: // --- Tier 3b: DB-backed fingerprint adoption (restart-proof) ---
6169: // The in-memory scan above is empty after a restart, so it can never rematch
6170: // a resumed conversation. For a header-less client, recover + adopt the prior
6171: // session from its persisted fingerprint, confirmed by content overlap. (The
6172: // header-bearing case — e.g. opencode's x-lore-session-id — is handled in the
6173: // Tier 1 mint path above.) (issue #796)
6174: const adopted = await adoptByFingerprint({
6175: req,
6176: headers,
6177: projectPath,
6178: gitRemote: trustedAdoptionRemote(projectPath, headers),
6179: known: ...
Found 100 matches (more matches available)
/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/llm-adapter.ts:
Line 1801: cache_control: { type: "ephemeral", ttl: "1h" },
Line 2806: cache_control: { type: "ephemeral" as const },
Line 2833: // prompt caching is driven by the cache_control block on `systemBlocks`
/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/cch.ts:
Line 466: * reconstructs the body (different JSON key ordering, cache_control
Line 616: * cache_control breakpoints are actually honored by the API.
/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/usage-validation.ts:
Line 238: "cachedContentTokenCount",
Line 295: counts.cachedContentTokenCount !== undefined &&
Line 297: counts.cachedContentTokenCount > counts.promptTokenCount)
Line 304: ...
<path>/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/translate/types.ts</path>
<type>file</type>
<content>
210: export type GatewayProtocol =
211: | "anthropic"
212: | "openai"
213: | "openai-responses"
214: | "vertex"
215: | "gemini";
216:
217: /** Normalized request after ingress translation from either protocol. */
218: export type GatewayRequest = {
219: /** Caller disconnect/cancellation propagated from the ingress Request. */
220: signal?: AbortSignal;
221: /** Which protocol the request arrived as — determines egress translation. */
222: protocol: GatewayProtocol;
223: /** Model identifier (e.g. `claude-sonnet-4-20250514`, `gpt-4o`). */
224: model: string;
225: /**
226: * Extracted system prompt.
227: * - Anthropic: top-level `system` field.
228: * - OpenAI: first message with `role: "system"`, removed from messages. ...
Found 17 matches
/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/translate/anthropic.ts:
Line 129: * - an array of content blocks (e.g. with `cache_control`) → join text blocks
Line 262: * explicit `cache_control` breakpoint. This is the highest-stability
Line 264: * 2. **Conversation caching**: places an explicit `cache_control` breakpoint
Line 290: * system[0]: host prompt — no cache_control (covered by [1]'s prefix)
Line 291: * system[1]: stable LTM (prefs) — cache_control: 1h TTL
Line 308: * Place an explicit `cache_control` breakpoint on the last block of the
Line 311: * When `true`, the gateway adds `cache_control: { type: "ephemeral" }`
Line 332: * `> 0` AND there is a raw window beyond it, an EXTRA `cache_control`
Line 366: * `cache_control` annotations are added (passthrough behavior). ...
Found 70 matches
/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/llm-adapter.ts:
Line 1801: cache_control: { type: "ephemeral", ttl: "1h" },
Line 2360: export function parseAnthropicResponse(data: {
Line 2806: cache_control: { type: "ephemeral" as const },
Line 2833: // prompt caching is driven by the cache_control block on `systemBlocks`
/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/cch.ts:
Line 466: * reconstructs the body (different JSON key ordering, cache_control
Line 616: * cache_control breakpoints are actually honored by the API.
/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/translate/vertex.ts:
Line 104: * other fields (system, messages, tools, cache_control, thinking, …) are
Line 158: * Vertex is driven by `cache_control` body blocks (a GA feature), NOT a beta
/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/translate/openai.ts:
Line 735: ...
<path>/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/translate/anthropic.ts</path>
<type>file</type>
<content>
110: function normalizeContent(content: unknown): GatewayContentBlock[] {
111: if (typeof content === "string") {
112: return [{ type: "text", text: content }];
113: }
114:
115: if (Array.isArray(content)) {
116: return content.map((block) =>
117: toGatewayBlock(block as Record<string, unknown>),
118: );
119: }
120:
121: // Null / undefined / unexpected → empty
122: return [];
123: }
124:
125: /**
126: * Normalize Anthropic's `system` field. Can be:
127: * - `undefined` / `null` → `""`
128: * - a plain string → used directly
129: * - an array of content blocks (e.g. with `cache_control`) → join text blocks
130: */
131: function normalizeSystem(system: unknown): string {
132: if (system == null) return "";
133: if (typeof system === "string") return system;
134:
135: if (Array.isArray(system)) {
136: ...
<path>/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/translate/anthropic.ts</path>
<type>file</type>
<content>
1: /**
2: * Anthropic ↔ Gateway translation layer.
3: *
4: * Converts between Anthropic's `/v1/messages` API format and the gateway's
5: * internal `GatewayRequest`/`GatewayResponse` types. The parser is lenient —
6: * unknown fields pass through in `metadata` rather than causing errors.
7: */
8: import type {
9: GatewayContentBlock,
10: GatewayMessage,
11: GatewayRequest,
12: GatewayResponse,
13: GatewayTool,
14: } from "./types";
15: import { forwardClientHeaders, ZERO_USAGE } from "./types";
16: import { asString } from "@loreai/core";
17: import { extractAuth, authHeaders } from "../auth";
18: import {
19: normalizeAnthropicStopReason,
20: toAnthropicStopReason,
21: } from "../anthropic-protocol";
22: import { validateAnthropicUsage } from "../usage-validation";
23:
24: // ...
<path>/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/translate/anthropic.ts</path>
<type>file</type>
<content>
360: *
361: * Returns the relative path, headers, and JSON body. The caller prepends
362: * the upstream base URL.
363: *
364: * @param req The normalized gateway request
365: * @param cache Optional caching configuration. When omitted, no
366: * `cache_control` annotations are added (passthrough behavior).
367: */
368: export function buildAnthropicRequest(
369: req: GatewayRequest,
370: cache?: AnthropicCacheOptions,
371: ): {
372: url: string;
373: headers: Record<string, string>;
374: body: unknown;
375: } {
376: // --- Headers ---
377: // Forward non-managed client headers first (provider-specific headers like
378: // anthropic-beta, user-agent, etc.), then overlay gateway-managed headers
379: // so they always take precedence.
380: const headers: Record<string, string> = {
381: ...
<path>/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/recall.ts</path>
<type>file</type>
<content>
1140: | "vertex"
1141: | "gemini";
1142:
1143: /**
1144: * Injected upstream dependencies for recall follow-up execution.
1145: *
1146: * Passed by the pipeline so `recall.ts` never imports `pipeline.ts`
1147: * (avoids a circular dependency). `forward` wraps `forwardToUpstream`
1148: * — callers should disable conversation caching on the follow-up;
1149: * `parseJSON` wraps `accumulateNonStreamResponse`.
1150: */
1151: export interface RecallFollowUpCtx {
1152: /** Forward a follow-up request upstream and return the raw response. */
1153: forward: (
1154: req: GatewayRequest,
1155: signal?: AbortSignal,
1156: ) => Promise<{ response: Response; effectiveProtocol: RecallProtocol }>;
1157: /** Parse a non-streaming (JSON) upstream response into a GatewayResponse. ...
<path>/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/pipeline.ts</path>
<type>file</type>
<content>
14920: { status: 502, headers: { "content-type": "application/json" } },
14921: );
14922: }
14923: if (
14924: !route &&
14925: fallbackProviderID &&
14926: !headerUpstream &&
14927: (!fallbackProviderRoute?.url ||
14928: (fallbackProviderRoute.protocol !== null &&
14929: fallbackProviderRoute.protocol !== "openai-responses"))
14930: ) {
14931: abortScope.dispose();
14932: return new Response(
14933: JSON.stringify({
14934: error: "compaction_routing_failed",
14935: message: `Cannot safely resolve a Responses compact endpoint for provider "${fallbackProviderID}"`,
14936: }),
14937: { status: 502, headers: { "content-type": "application/json" } },
14938: );
14939: }
14940: const effectiveUpstreamBase =
14941: trustedUpstream ??
14942: route?.effectiveUpstreamBase ?? ...
spyyzvyyyqxs 3f3ae768fde5 fix(recall): validate recovery metadata mmmktlwmwuts b61b086186cb fix(recall): harden failure synthesis mvtnxtlyooxq 9258a29630b9 fix(recall): synthesize after recall failure
<path>/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/test/recall-buffered-transaction.test.ts</path>
<type>file</type>
<content>
1: import { afterEach, describe, expect, test, vi } from "vitest";
2: import { db, ltm, loadSessionTracking, temporal } from "@loreai/core";
3: import * as core from "@loreai/core";
4: import { loadConfig } from "../src/config";
5: import { clearAllCosts, getSessionCosts } from "../src/cost-tracker";
6: import {
7: accumulateNonStreamResponse,
8: buildStreamingResponse,
9: getActiveSessions,
10: handleRequest,
11: resetPipelineState,
12: setRecallPersistenceCommitObserverForTest,
13: setUpstreamInterceptor,
14: streamingPostResponsePendingForTest,
15: } from "../src/pipeline";
16: import type { GatewayRequest } from "../src/translate/types";
17: import { parseAnthropicResponseJSON } from "../src/translate/anthropic";
18: import {
19: _resetForTest as resetWorkerHealth,
20: _setNowForTest as setWorkerHealthTime,
21: ...
Found 4 matches
/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/pipeline.ts:
Line 2585: export function captureToolPairing400(input: {
Line 7517: captureToolPairing400({
Line 18206: captureToolPairing400({
Line 18598: captureToolPairing400({
<path>/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/pipeline.ts</path>
<type>file</type>
<content>
2540: if (!deltaCompressed) return null;
2541: return reanchorExistingDelta(sessionID, projectPath, messages);
2542: }
2543:
2544: export function safeDeltaInsertIndex(
2545: messages: GatewayMessage[],
2546: desired: number,
2547: ): number {
2548: // The injected delta is a user→assistant PAIR. It must NEVER be placed at the
2549: // true tail (idx == messages.length): the pair's trailing assistant would
2550: // become the literal last message of the request, so (1) agent harnesses
2551: // (Claude Code REPL, OpenCode) render it as a stray turn ("Understood.") and
2552: // (2) the model sees the conversation ending on its OWN turn and ends the
2553: // agent loop early (the wedge). Cap at messages.length - 1 so at least one
2554: // real message (a user turn / tool_result) always follows the pair and closes
2555: // the request. ...
Found 52 matches
/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/worker-health.ts:
Line 970: detail: string;
Line 986: detail: "background workers healthy",
Line 992: detail:
/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/ui.ts:
Line 279: opts.detailLeftHtml || opts.detailRightHtml
Line 280: ? `<div class="cost-bar-detail"><span>${opts.detailLeftHtml ?? ""}</span><span>${opts.detailRightHtml ?? ""}</span></div>`
/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/server.ts:
Line 569: detail: embeddings.detail,
Line 574: detail: worker.detail,
/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/recall.ts:
Line 89: description: RECALL_PARAM_DESCRIPTIONS.detailOffset,
Line 95: description: RECALL_PARAM_DESCRIPTIONS.detailLimit,
Line 543: ((item.input as Record<string, unknown>).detailOffset !== undefined &&
Line 545: (item.input ...
<path>/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/translate/anthropic.ts</path>
<type>file</type>
<content>
538: * Parse an Anthropic-format response JSON back into a `GatewayResponse`.
539: *
540: * This is the inverse of `buildAnthropicNonStreamResponse`. Used when the
541: * pipeline returns Anthropic-format JSON that needs to be translated to
542: * another protocol (OpenAI Chat Completions, OpenAI Responses API).
543: */
544: export function parseAnthropicResponseJSON(
545: json: Record<string, unknown>,
546: ): GatewayResponse {
547: const content: GatewayContentBlock[] = [];
548: const toolIdentities = new Set<string>();
549: const rawContent = json.content as Array<Record<string, unknown>> | undefined;
550: if (rawContent) {
551: for (const block of rawContent) {
552: switch (block.type) {
553: case "text":
554: content.push({ type: "text", text: asString(block.text) });
555: break;
556: case ...
<path>/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/anthropic-protocol.ts</path> <type>file</type> <content> 1: /** Anthropic response values accepted at the provider boundary. */ 2: 3: export const ANTHROPIC_STOP_REASONS: ReadonlySet<string> = new Set([ 4: "end_turn", 5: "max_tokens", 6: "stop_sequence", 7: "tool_use", 8: "pause_turn", 9: "refusal", 10: "model_context_window_exceeded", 11: ]); 12: 13: export const ANTHROPIC_CONTENT_BLOCK_TYPES: ReadonlySet<string> = new Set([ 14: "text", 15: "thinking", 16: "redacted_thinking", 17: "tool_use", 18: "server_tool_use", 19: "web_search_tool_result", 20: "web_fetch_tool_result", 21: "code_execution_tool_result", 22: "bash_code_execution_tool_result", 23: "text_editor_code_execution_tool_result", 24: "tool_search_tool_result", 25: "container_upload", 26: // Server-side fallback emits a boundary block with no deltas. ...
12716 12781 197
Found 7 matches
/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/test/worker-codex-sse-path.test.ts:
Line 116: "event: response.completed",
Line 117: 'data: {"type":"response.completed","response":{"status":"completed"}}',
/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/test/recall-codex-stream.test.ts:
Line 74: sseEvent("response.completed", {
Line 118: sseEvent("response.completed", {
Line 334: sseEvent("response.completed", {
/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/test/codex-usage-provisional.test.ts:
Line 108: incomplete ? "event: response.incomplete" : "event: response.completed",
/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/test/codex-usage-metadata.test.ts:
Line 76: body.indexOf("event: response.completed"),
<path>/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/test/recall-codex-stream.test.ts</path>
<type>file</type>
<content>
1: /**
2: * Integration test: recall follow-up on the `openai-responses` streaming path
3: * (including the `openai-codex` / ChatGPT case).
4: *
5: * The recall follow-up is issued STREAMING (`stream: true`) for all
6: * `openai-responses` clients. This unifies two requirements:
7: * - `openai-codex` (ChatGPT) MANDATES streaming: its
8: * `/backend-api/codex/responses` backend rejects a non-streaming request
9: * with `400 {"detail":"Stream must be set to true"}`.
10: * - The true-streaming resume avoids the header-timeout hang on slow
11: * reasoning-heavy upstreams (opencode's 10s `ProviderHeaderTimeoutError`):
12: * a *buffered* `stream:false` follow-up re-introduces the wait. ...
Found 19 matches
/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/test/codex-usage-provisional.test.ts:
Line 22: type: "codex.rate_limits",
Line 48: `event: codex.rate_limits\ndata: ${JSON.stringify(quota)}\n\n${await response.text()}`,
Line 104: .filter((frame) => frame.startsWith("event: codex.rate_limits\n"))
/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/test/codex-usage-metadata.test.ts:
Line 14: type: "codex.rate_limits",
Line 61: .filter((frame) => frame.startsWith("event: codex.rate_limits\n"))
Line 75: expect(body.indexOf("codex.rate_limits")).toBeLessThan(
Line 133: `${await upstream([]).text()}event: codex.rate_limits\ndata: ${JSON.stringify(limits)}\n\n`,
Line 200: type: "codex.rate_limits",
Line 223: type: "codex.rate_limits",
Line 254: type: "codex.rate_limits",
Line 300: type: ...
<path>/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/test/codex-usage-metadata.test.ts</path>
<type>file</type>
<content>
1: import { describe, expect, test } from "vitest";
2: import fc from "fast-check";
3: import {
4: accumulateResponsesSSEStream,
5: ResponsesTerminalError,
6: streamResponsesPassthrough,
7: } from "../src/stream/openai-responses";
8: import { buildOpenAIResponsesResponse } from "../src/translate/openai-responses";
9:
10: const MAX_CODEX_RATE_LIMIT_EVENTS = 64;
11: const MAX_CODEX_RATE_LIMIT_BYTES = 16 * 1024;
12:
13: const limits = {
14: type: "codex.rate_limits",
15: plan_type: "pro",
16: rate_limits: {
17: primary: { used_percent: 12.5, window_minutes: 300, reset_at: 2000000000 },
18: secondary: {
19: used_percent: 75,
20: window_minutes: 10080,
21: reset_at: 2000100000,
22: },
23: },
24: credits: { has_credits: true, unlimited: false, balance: "12.34" },
25: };
26:
27: function upstream(
28: ...
<path>/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/translate/openai-responses.ts</path>
<type>file</type>
<content>
1220: status: 200,
1221: headers: { "content-type": "application/json" },
1222: });
1223: }
1224:
1225: function mapStopReasonToStatus(reason: string): string {
1226: switch (reason) {
1227: case "end_turn":
1228: case "stop":
1229: case "stop_sequence":
1230: return "completed";
1231: case "max_tokens":
1232: case "length":
1233: case "content_filter":
1234: return "incomplete";
1235: case "tool_use":
1236: return "completed";
1237: default:
1238: return "completed";
1239: }
1240: }
1241:
1242: function incompleteDetails(stopReason: string): { reason: string } {
1243: return {
1244: reason:
1245: stopReason === "content_filter" ? ...
Found 1 matches /home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/translate/types.ts: Line 349: codexRateLimits?: Array<Record<string, unknown>>;
<path>/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/pipeline.ts</path>
<type>file</type>
<content>
10080: };
10081: // Recall items are gateway-internal and must stay hidden on every exit,
10082: // including failures raised before marker replacement.
10083: const recallIndices = new Set<number>();
10084: const unresolvedToolIndices = new Set<number>();
10085: const referenceIndices = new Map<number, ReferenceLifecycle>();
10086:
10087: const retainedStateBaseline = retainedStateBytes;
10088: const hiddenRecallBaseline = hiddenRecallBytes;
10089: const runPrincipalAttempt = async (): Promise<void> => {
10090: principalReadFinished = false;
10091: if (!currentPrincipalResponse.body) {
10092: throw new Error("Upstream response has no body");
10093: }
10094: const reader = currentPrincipalResponse.body.getReader();
10095: ...
<path>/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/pipeline.ts</path>
<type>file</type>
<content>
10690: deferredContinuationBytes -=
10691: heldContinuationEvents[index].chunk.byteLength;
10692: }
10693: heldContinuationEvents.splice(index, 1);
10694: }
10695: }
10696: };
10697: const promoteVisibleContinuationCandidate = (
10698: outputIndex: number,
10699: ): void => {
10700: for (const held of heldContinuationEvents) {
10701: if (held.candidateIndex !== outputIndex) continue;
10702: deferredContinuationBytes -= held.chunk.byteLength;
10703: reserveTransactionalBytes(held.chunk);
10704: ...
<path>/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/src/translate/gemini.ts</path> <type>file</type> <content> 405: 406: /** 407: * Map a Gemini `finishReason` + tool presence to an internal stop reason. 408: * 409: * Abnormal reasons (SAFETY, RECITATION, BLOCKLIST, PROHIBITED_CONTENT, SPII, 410: * MALFORMED_FUNCTION_CALL, OTHER, …) are preserved VERBATIM so a proxied client 411: * still sees the real block/filter signal instead of a laundered "STOP". 412: * `toGeminiFinishReason` echoes any such preserved value back on egress. Only 413: * the truly-normal reasons are normalized to the internal model. A block reason 414: * takes precedence over `hasToolCall` (a filtered turn is not a tool turn). ...
552 35328
<path>/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/test/openai-responses-recall-aware-stream.test.ts</path>
<type>file</type>
<content>
225: // The terminal event is forwarded verbatim with no marker or follow-up.
226: expect(out).toContain("response.completed");
227: expect(out).toContain("hello world");
228: expect(out).not.toContain('"recall"');
229: expect(out).not.toContain("lore_marker");
230: expect(out).not.toContain("response.failed");
231: });
232:
233: test("bounds Codex quota metadata across the principal and continuation", async () => {
234: const quota = (index: number) =>
235: sseEvent("codex.rate_limits", {
236: metered_limit_name: `bucket_${index}`,
237: rate_limits: {
238: primary: {
239: used_percent: index,
240: window_minutes: 300,
241: reset_at: 2000000000 + index,
242: },
243: },
244: });
245: const principalQuotas = ...
<path>/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/test/codex-usage-metadata.test.ts</path>
<type>file</type>
<content>
145:
146: test("true streaming forwards quota events without duplication", async () => {
147: const response = streamResponsesPassthrough(
148: upstream([limits]),
149: () => {},
150: undefined,
151: "codex",
152: );
153: expect(quotaEvents(await response.text())).toEqual([limits]);
154: });
155:
156: test.each(["buffered", "passthrough"] as const)(
157: "%s projection rebuilds quota metadata from the private allowlist",
158: async (mode) => {
159: const sentinel = "private diagnostic\nforged log line";
160: const hostile = {
161: ...limits,
162: plan_type: sentinel,
163: metered_limit_name: sentinel,
164: limit_name: "valid_limit",
165: rate_limits: {
166: primary: {
167: used_percent: 25,
168: window_minutes: ...
/home/byk/Code/opencode-lore-recall-recovery The working copy has no changes. Working copy (@) : rkqkzwmo e8fbf605 (empty) (no description set) Parent commit (@-): spyyzvyy 3f3ae768 fix/recall-failure-synthesis | fix(recall): validate recovery metadata Warning: These bookmarks have conflicts: fix/responses-private-references Hint: Use `jj bookmark list` to see details. Use `jj bookmark set <name> -r <rev>` to resolve. rkqkzwmozkxz e8fbf605d765379e541ce09cd5f2f9b8c126d883 parents=3f3ae768fde5b08b5c8e5dced647e361fddfd5aa conflict=false empty=true description= spyyzvyyyqxs 3f3ae768fde5b08b5c8e5dced647e361fddfd5aa parents=b61b086186cb6a2219bdd40c96a0bba602dae3b2 conflict=false empty=false description=fix(recall): validate recovery metadata pxrvwsvvkmpo 2cbf40060c67df229731cf1b9e34d5bf22ec2145 parents=e977b4b1da8f8197c3238466d41de0bccd8eb054 conflict=false empty=false description=feat(cch): add seeds for Claude Code up to 2.1.272 (#1780) --- candidate conflicts --- --- changed files ...
Found 100 matches (more matches available)
/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/test/context-capability-note.test.ts:
Line 51: type: "message",
Line 52: role: "assistant",
/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/test/content-passthrough.test.ts:
Line 5: * types survive the gateway round-trip faithfully — both as top-level message
Line 109: role: "assistant",
Line 163: role: "assistant",
Line 216: role: "assistant",
Line 261: role: "assistant",
Line 389: { role: "developer", content: "You are a code assistant." },
Line 413: type: "message",
Line 441: role: "assistant" as const,
/home/byk/Code/opencode-lore-recall-recovery/packages/gateway/test/compaction.test.ts:
Line 55: return { role: "assistant", content: [{ type: "text", text }] };
Line 658: { role: "assistant", content: "latest answer" ...
Found 12 matches /home/byk/Code/opencode-lore-recall-recovery/packages/gateway/test/foreground-body-limit.test.ts: Line 58: const pending = accumulateNonStreamResponse( Line 172: const result = await accumulateNonStreamResponse( Line 187: const result = await accumulateNonStreamResponse(response, "openai"); Line 205: accumulateNonStreamResponse( Line 233: accumulateNonStreamResponse( Line 268: accumulateNonStreamResponse(response, "openai-responses"), Line 306: const result = await accumulateNonStreamResponse( Line 352: accumulateNonStreamResponse(response, "openai-responses"), Line 364: accumulateNonStreamResponse(response, "openai-responses", true), /home/byk/Code/opencode-lore-recall-recovery/packages/gateway/test/recall-buffered-transaction.test.ts: Line 375: accumulateNonStreamResponse( Line 400: accumulateNonStreamResponse( Line 677: const error = await accumulateNonStreamResponse(
2cbf40060c67df229731cf1b9e34d5bf22ec2145 through change spyyzvyyyqxs, commit 3f3ae768fde5b08b5c8e5dced647e361fddfd5aa.0bb7846a803d07be809d2cbd5220ad78aa8503c56eddb3efcd5c5dea8c29beed.e8fbf605d765379e541ce09cd5f2f9b8c126d883.fix/responses-private-references.AGENTS.md, quality/REVIEW.md, and root/gateway package scripts. No CONTRIBUTING.md exists.repo-setup skill was unavailable; I performed its documented checks manually.packages/gateway/src/pipeline.ts:10147-10169 treats any non-JSON, non-response.* event as an opaque event and forwards it. The continuation path repeats this behavior at packages/gateway/src/pipeline.ts:10765-10787.
A provider can send:
event: codex.rate_limits
data: private diagnostic
JSON.parse fails, but the code forwards the raw payload before reaching the sanitizers at pipeline.ts:10259-10272 or pipeline.ts:10867-10880. On the principal path it can reach the client immediately. On a successful continuation it enters the transactional output.
This causes three concrete failures:
Both parse-failure branches must suppress or reject codex.rate_limits before generic opaque-event forwarding. ...