@cortexkit/opencode-magic-context 0.49.48 → 0.49.50
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{announcement-g789dmt6.js → announcement-9pr71hd5.js} +3 -2
- package/dist/auto-search-worker.js +5 -5
- package/dist/chunk-embedding-write-worker.js +14 -15
- package/dist/{compaction-marker-candidates-dkfp1q9j.js → compaction-marker-candidates-8hazqfvj.js} +2 -3
- package/dist/compaction-marker-candidates-worker.js +1 -1
- package/dist/{compartment-chunk-embedding-snj51nmg.js → compartment-chunk-embedding-gfd093f8.js} +7 -8
- package/dist/config/project-security.d.ts.map +1 -1
- package/dist/config/schema/magic-context.d.ts +10 -0
- package/dist/config/schema/magic-context.d.ts.map +1 -1
- package/dist/{conflict-warning-hook-w1aw6w5t.js → conflict-warning-hook-56qpq7ws.js} +7 -8
- package/dist/{context-8r125qv3.js → context-4js5qnnm.js} +61 -49
- package/dist/{derive-budgets-nkw09vq7.js → derive-budgets-z53424qx.js} +2 -3
- package/dist/embedding-backfill-3wdjzrvs.js +27 -0
- package/dist/embedding-worker-process.js +2 -3
- package/dist/embedding-worker.js +6 -7
- package/dist/features/magic-context/dreamer/docs-proposals.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/provider-output-failure.d.ts +5 -7
- package/dist/features/magic-context/dreamer/provider-output-failure.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/task-scheduler.d.ts.map +1 -1
- package/dist/features/magic-context/dreamer/verify.d.ts.map +1 -1
- package/dist/features/magic-context/memory/embedding-identity.d.ts.map +1 -1
- package/dist/features/magic-context/memory/embedding-openai.d.ts +4 -0
- package/dist/features/magic-context/memory/embedding-openai.d.ts.map +1 -1
- package/dist/features/magic-context/memory/embedding-probe.d.ts +10 -0
- package/dist/features/magic-context/memory/embedding-probe.d.ts.map +1 -1
- package/dist/features/magic-context/memory/embedding.d.ts.map +1 -1
- package/dist/features/magic-context/project-embedding-registry.d.ts.map +1 -1
- package/dist/features/magic-context/storage-db.d.ts +14 -0
- package/dist/features/magic-context/storage-db.d.ts.map +1 -1
- package/dist/features/magic-context/transform-decision-log.d.ts +2 -0
- package/dist/features/magic-context/transform-decision-log.d.ts.map +1 -1
- package/dist/{history-owner-0z620wgz.js → history-owner-n50e0e8y.js} +2 -3
- package/dist/hooks/magic-context/compartment-runner-historian.d.ts.map +1 -1
- package/dist/hooks/magic-context/compartment-runner-incremental.d.ts.map +1 -1
- package/dist/hooks/magic-context/compartment-trigger.d.ts.map +1 -1
- package/dist/hooks/magic-context/protected-tail-boundary.d.ts +5 -3
- package/dist/hooks/magic-context/protected-tail-boundary.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform-compartment-phase.d.ts.map +1 -1
- package/dist/hooks/magic-context/transform.d.ts.map +1 -1
- package/dist/{index-rvmhyk89.js → index-07rp6xcn.js} +9 -9
- package/dist/{index-txs8tce6.js → index-0k283v27.js} +2 -4
- package/dist/{index-ak11t3gm.js → index-0tz2fzpq.js} +1 -1
- package/dist/{index-2qbtqg1w.js → index-25tm250q.js} +1 -1
- package/dist/{index-h9m41624.js → index-2ny9xwdn.js} +2 -2
- package/dist/{index-xa9mmq6c.js → index-36wseasx.js} +1 -1
- package/dist/{index-cgzpbz78.js → index-5dptmnvd.js} +5 -5
- package/dist/{index-q41sm60t.js → index-5g6npyw5.js} +89 -63
- package/dist/{index-qsyx931k.js → index-5t1mr0bt.js} +13 -15
- package/dist/{index-jrfre9ah.js → index-82dfe8en.js} +146 -5
- package/dist/{index-d4qw2h43.js → index-8d7gkgjs.js} +6 -5
- package/dist/{index-gn6gfz4y.js → index-90z05d0p.js} +1 -1
- package/dist/{index-trkxkgmd.js → index-97bjd14c.js} +5 -5
- package/dist/{index-9wnbnx8f.js → index-a6aqpfp6.js} +1 -1
- package/dist/{index-s79g172v.js → index-bamnjp2t.js} +29 -13
- package/dist/{index-4wpfbzks.js → index-bkg4hdyh.js} +3 -3
- package/dist/{index-gp3kcpc4.js → index-cd3vp8xa.js} +1 -1
- package/dist/{index-vk6srk5r.js → index-ct3ettqt.js} +3 -3
- package/dist/{index-sd2s4t4p.js → index-cwj6qhmf.js} +2 -2
- package/dist/{index-brj6was5.js → index-em92bp7f.js} +2 -2
- package/dist/{index-2p37txes.js → index-ga5q492k.js} +1 -1
- package/dist/{index-8cfnaagj.js → index-gapnh6tk.js} +2 -4
- package/dist/{index-fw42ms3m.js → index-gz001bx7.js} +1 -1
- package/dist/{index-zetm0ayn.js → index-h8g08nxs.js} +164 -106
- package/dist/{index-qcz1fy7h.js → index-hexdee98.js} +4 -4
- package/dist/{index-fgft4qjn.js → index-hkveze74.js} +4 -4
- package/dist/{index-smtbdmc3.js → index-hsv31e69.js} +2 -2
- package/dist/{index-dj2p8653.js → index-hsyczpn7.js} +2 -2
- package/dist/{index-4dpvnp8k.js → index-jjy5a5w0.js} +3 -0
- package/dist/{index-1hwn96x1.js → index-kn1bx21r.js} +3 -3
- package/dist/{index-t6s0tsp7.js → index-mjh63zvw.js} +3 -3
- package/dist/{index-ta87fpfs.js → index-n0twfvah.js} +64 -15
- package/dist/{index-nj360hcs.js → index-pb8ysnq2.js} +4 -4
- package/dist/{index-jz5bk7xd.js → index-qperbvjn.js} +2 -2
- package/dist/{index-25ka1jza.js → index-r9agn061.js} +4 -4
- package/dist/{index-hkh8x221.js → index-rbs27k1d.js} +7 -7
- package/dist/{index-hacf2tyx.js → index-reyws9fy.js} +1 -1
- package/dist/{index-cgsmttyj.js → index-s131svmx.js} +4 -4
- package/dist/{index-fxbk7gk3.js → index-tad3can2.js} +1 -1
- package/dist/{index-8ka0ne8t.js → index-v4a1pnny.js} +6 -6
- package/dist/{index-xh3jyejb.js → index-wr2t8zb0.js} +17 -19
- package/dist/{index-q6pjqm49.js → index-z4832qfe.js} +14 -14
- package/dist/index.js +54 -56
- package/dist/{logger-qwnbcfj9.js → logger-sw7z6sjz.js} +1 -2
- package/dist/{message-fts-rowid-map-msffhkve.js → message-fts-rowid-map-kx1bsdyg.js} +4 -5
- package/dist/{message-index-bounded-0q7sy04w.js → message-index-bounded-k0ebpy3y.js} +12 -13
- package/dist/{message-time-backfill-39bm498k.js → message-time-backfill-hp2jgn49.js} +2 -3
- package/dist/migration-worker.js +12 -13
- package/dist/plugin/embedding-bootstrap-helpers.d.ts.map +1 -1
- package/dist/plugin/embedding-routing.d.ts.map +1 -1
- package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
- package/dist/plugin/rpc-handlers.d.ts.map +1 -1
- package/dist/{project-embedding-registry-r6xfsrbe.js → project-embedding-registry-5dwh5zfn.js} +12 -13
- package/dist/raw-ordinal-warmup-worker.js +8 -8
- package/dist/{read-session-chunk-7fmg9p5m.js → read-session-chunk-6712p893.js} +10 -11
- package/dist/{read-session-raw-x7a9b3jm.js → read-session-raw-04ger9zt.js} +2 -3
- package/dist/{recomp-orchestrator-jqa5z4ar.js → recomp-orchestrator-8ebydg5j.js} +31 -32
- package/dist/render-dtc4qkq4.js +43 -0
- package/dist/{safe-notification-target-wztd7bgk.js → safe-notification-target-mx5khyxf.js} +2 -3
- package/dist/{search-archive-df09r8qn.js → search-archive-f6hjbnsa.js} +12 -13
- package/dist/{search-kt764afk.js → search-edv0gy1d.js} +24 -25
- package/dist/{send-session-notification-j93pn2hn.js → send-session-notification-gamjee2f.js} +5 -6
- package/dist/shared/data-path.d.ts +7 -13
- package/dist/shared/data-path.d.ts.map +1 -1
- package/dist/shared/hidden-model-cooldown.d.ts +23 -0
- package/dist/shared/hidden-model-cooldown.d.ts.map +1 -0
- package/dist/shared/model-suggestion-retry.d.ts +0 -2
- package/dist/shared/model-suggestion-retry.d.ts.map +1 -1
- package/dist/shared/provider-response-completion.d.ts +10 -0
- package/dist/shared/provider-response-completion.d.ts.map +1 -1
- package/dist/shared/rpc-types.d.ts +1 -0
- package/dist/shared/rpc-types.d.ts.map +1 -1
- package/dist/shared/status-summary.d.ts +1 -0
- package/dist/shared/status-summary.d.ts.map +1 -1
- package/dist/shared/status-view-check.d.ts.map +1 -1
- package/dist/shared/status-view.d.ts +1 -0
- package/dist/shared/status-view.d.ts.map +1 -1
- package/dist/shared/test-db.d.ts +13 -0
- package/dist/shared/test-db.d.ts.map +1 -0
- package/dist/{storage-tags-96vyd6ra.js → storage-tags-kdb4qsyq.js} +4 -5
- package/dist/test-preload.d.ts +2 -0
- package/dist/test-preload.d.ts.map +1 -0
- package/dist/{transform-postprocess-phase-a7ety10n.js → transform-postprocess-phase-1bg25094.js} +32 -33
- package/dist/v2/auto-search-worker.js +5 -5
- package/dist/v2/chunk-embedding-write-worker.js +14 -14
- package/dist/v2/{compaction-marker-candidates-y737qb1v.js → compaction-marker-candidates-re14353a.js} +2 -2
- package/dist/v2/compaction-marker-candidates-worker.js +1 -1
- package/dist/v2/{compartment-chunk-embedding-nj5nrnbj.js → compartment-chunk-embedding-0pxsrzrt.js} +7 -7
- package/dist/v2/{context-9x7mnb7x.js → context-qkr7z6d0.js} +99 -63
- package/dist/v2/{derive-budgets-b5cgrtp8.js → derive-budgets-w0815q82.js} +3 -3
- package/dist/v2/embedding-backfill-x1zpc04f.js +27 -0
- package/dist/v2/embedding-worker-process.js +1 -1
- package/dist/v2/embedding-worker.js +5 -5
- package/dist/v2/hidden-completion.d.ts.map +1 -1
- package/dist/v2/{history-owner-fpka43cn.js → history-owner-ep91wgqj.js} +2 -2
- package/dist/v2/hooks/context.d.ts.map +1 -1
- package/dist/v2/hooks/usage-persist.d.ts +1 -1
- package/dist/v2/hooks/usage-persist.d.ts.map +1 -1
- package/dist/v2/hooks/usage-reading.d.ts +3 -0
- package/dist/v2/hooks/usage-reading.d.ts.map +1 -1
- package/dist/v2/{logger-4cj6d03m.js → logger-xnscpj6w.js} +1 -1
- package/dist/v2/{message-fts-rowid-map-qe7cpksd.js → message-fts-rowid-map-57jh6xpb.js} +4 -4
- package/dist/v2/{message-index-bounded-hctgp22r.js → message-index-bounded-a36rw93p.js} +12 -12
- package/dist/v2/{message-time-backfill-0c4h7sg6.js → message-time-backfill-baxebka0.js} +2 -2
- package/dist/v2/migration-worker.js +11 -11
- package/dist/v2/{project-embedding-registry-ek0cy0d5.js → project-embedding-registry-v2fxrs8b.js} +12 -12
- package/dist/v2/raw-ordinal-warmup-worker.js +8 -8
- package/dist/v2/{read-session-chunk-zknadvjr.js → read-session-chunk-hzhxvhyv.js} +10 -10
- package/dist/v2/{read-session-raw-yss2ev98.js → read-session-raw-3e482h3c.js} +2 -2
- package/dist/v2/{recomp-orchestrator-m5w0eqke.js → recomp-orchestrator-yzr49pd0.js} +32 -32
- package/dist/v2/{render-89asy54r.js → render-rhaevxv1.js} +21 -21
- package/dist/v2/{safe-notification-target-gphhast7.js → safe-notification-target-9r79xnbt.js} +2 -2
- package/dist/v2/{search-archive-axz2gbdb.js → search-archive-9924fyk8.js} +12 -12
- package/dist/v2/{search-kdtja5rx.js → search-ggvexvv7.js} +23 -23
- package/dist/v2/{send-session-notification-na3q825m.js → send-session-notification-95p89k7q.js} +5 -5
- package/dist/v2/{server-yyqmvbvv.js → server-016a1whm.js} +161 -102
- package/dist/v2/{server-z3tyd1mx.js → server-0k586y7d.js} +3 -3
- package/dist/v2/{server-p9s40wfa.js → server-0ms13pc8.js} +3 -0
- package/dist/v2/{server-e3m10ds0.js → server-16kfxcxj.js} +4 -4
- package/dist/v2/{server-nn4hbymt.js → server-3bfc26r7.js} +9 -9
- package/dist/v2/{server-7vb38e51.js → server-3jc6qmdz.js} +1 -1
- package/dist/v2/{server-jra7awr5.js → server-3qf9n5ck.js} +11 -11
- package/dist/v2/{server-69m30b21.js → server-3yk44ddz.js} +1 -1
- package/dist/v2/{server-2gjqhmn9.js → server-4h4acntc.js} +27 -11
- package/dist/v2/{server-3schkz95.js → server-58h6rrnx.js} +4 -4
- package/dist/v2/{server-af1rmkyn.js → server-5kgesxck.js} +2 -2
- package/dist/v2/{server-mfn1yf9d.js → server-7vrtk78d.js} +1 -1
- package/dist/v2/{server-27kccwe7.js → server-88yvx6r9.js} +63 -12
- package/dist/v2/{server-f0j864ma.js → server-91gb0vh8.js} +1 -1
- package/dist/v2/{server-131h608x.js → server-966dq3pd.js} +2 -2
- package/dist/v2/{server-jb6tjyeb.js → server-bb6kf05j.js} +23 -20
- package/dist/v2/{server-sg2qjkrb.js → server-brsx45r6.js} +6 -4
- package/dist/v2/{server-gwxys0d0.js → server-c8z2grq0.js} +1 -1
- package/dist/v2/{server-y8n33d9j.js → server-g61hgy1y.js} +4 -4
- package/dist/v2/{server-zahgxer8.js → server-jxrqsn84.js} +3 -3
- package/dist/v2/{server-2j87594q.js → server-kgq2e2hh.js} +2 -2
- package/dist/v2/{server-ddw42d76.js → server-mxsy9h1d.js} +2 -2
- package/dist/v2/{server-qmmkhz2z.js → server-np27dgyt.js} +1 -1
- package/dist/v2/{server-jqn7q7tm.js → server-q93jdtz8.js} +5 -5
- package/dist/v2/{server-dcws5831.js → server-qp5sj6n5.js} +2 -2
- package/dist/v2/{server-7be0ersd.js → server-rcchadw0.js} +3 -3
- package/dist/v2/{server-b3r080cm.js → server-rz5jnhnv.js} +1 -1
- package/dist/v2/{server-zt1m5rwj.js → server-sa1fdt41.js} +1 -1
- package/dist/v2/{server-wa4qhryh.js → server-sb55ddgn.js} +5 -4
- package/dist/v2/{server-4x7n5qz7.js → server-scp3y4dh.js} +13 -11
- package/dist/v2/{server-pej5rnye.js → server-sgn61hht.js} +2 -2
- package/dist/v2/{server-ypf1ap0v.js → server-t8n27rbt.js} +1 -1
- package/dist/v2/{server-sefxj8k1.js → server-tmf0ayqp.js} +1 -1
- package/dist/v2/{server-sr8tf5dt.js → server-vjadwb3j.js} +6 -5
- package/dist/v2/{server-bez34e60.js → server-vqq3g1t7.js} +4 -4
- package/dist/v2/{server-tpt7bwq8.js → server-ww7xbxxf.js} +1 -1
- package/dist/v2/server.js +6 -6
- package/dist/v2/{storage-tags-xq8hjqkf.js → storage-tags-rzv7y0n3.js} +4 -4
- package/dist/v2/{v2-archive-reader-ky1wqcws.js → v2-archive-reader-5ggewg8q.js} +1 -1
- package/dist/v2/{wrapup-orchestrator-6wt67saz.js → wrapup-orchestrator-36c5wyvq.js} +32 -32
- package/dist/{v2-archive-reader-665x2x4d.js → v2-archive-reader-gx5ke1d7.js} +1 -1
- package/dist/wrapup-orchestrator-ya31knav.js +55 -0
- package/package.json +1 -1
- package/src/config/index.test.ts +20 -0
- package/src/config/project-security.test.ts +5 -1
- package/src/config/project-security.ts +4 -0
- package/src/config/schema/magic-context.test.ts +43 -0
- package/src/config/schema/magic-context.ts +19 -0
- package/src/shared/data-path.test.ts +104 -56
- package/src/shared/data-path.ts +30 -30
- package/src/shared/hidden-model-cooldown.test.ts +117 -0
- package/src/shared/hidden-model-cooldown.ts +123 -0
- package/src/shared/model-suggestion-retry.test.ts +53 -76
- package/src/shared/model-suggestion-retry.ts +38 -53
- package/src/shared/provider-response-completion.test.ts +49 -0
- package/src/shared/provider-response-completion.ts +64 -0
- package/src/shared/rpc-types.ts +1 -0
- package/src/shared/startup-maintenance-policy.test.ts +115 -0
- package/src/shared/status-detail-text.test.ts +7 -0
- package/src/shared/status-summary.ts +3 -0
- package/src/shared/status-view-check.ts +1 -0
- package/src/shared/status-view.test.ts +15 -0
- package/src/shared/status-view.ts +11 -1
- package/src/shared/test-db.test.ts +84 -0
- package/src/shared/test-db.ts +36 -0
- package/dist/embedding-backfill-kpy5shsa.js +0 -28
- package/dist/index-g2q4htwp.js +0 -146
- package/dist/render-mnqc74ar.js +0 -44
- package/dist/v2/embedding-backfill-360efh1t.js +0 -27
- package/dist/wrapup-orchestrator-7kmb3jf9.js +0 -56
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import type { ModelInput } from "./model-resolution";
|
|
2
|
+
import { isRecord } from "./record-type-guard";
|
|
3
|
+
import { toModelEntry } from "./resolve-fallbacks";
|
|
4
|
+
|
|
5
|
+
const MAX_SKIP_MS = 7 * 24 * 60 * 60 * 1_000;
|
|
6
|
+
const MIN_SKIP_MS = 60_000;
|
|
7
|
+
// Quota (412), rate limit (429) and overload (503) all arrive as "not before this time",
|
|
8
|
+
// so the wording names what the provider said, not why.
|
|
9
|
+
const RETRY_LATER_REASON = "provider said to retry later";
|
|
10
|
+
|
|
11
|
+
export interface HiddenModelCooldown {
|
|
12
|
+
model: string;
|
|
13
|
+
until: number;
|
|
14
|
+
reason: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Process-local provider evidence, shared by hidden agents but never by user requests. */
|
|
18
|
+
export class HiddenModelCooldowns {
|
|
19
|
+
private readonly entries = new Map<string, HiddenModelCooldown>();
|
|
20
|
+
|
|
21
|
+
constructor(private readonly now: () => number = () => Date.now()) {}
|
|
22
|
+
|
|
23
|
+
record(model: string | undefined, error: unknown): void {
|
|
24
|
+
if (!model?.includes("/")) return;
|
|
25
|
+
const now = this.now();
|
|
26
|
+
const delay = retryDelay(error, now);
|
|
27
|
+
if (delay === undefined || !Number.isFinite(delay) || delay <= MIN_SKIP_MS) return;
|
|
28
|
+
this.entries.set(model, {
|
|
29
|
+
model,
|
|
30
|
+
until: now + Math.min(delay, MAX_SKIP_MS),
|
|
31
|
+
reason: RETRY_LATER_REASON,
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
succeeded(model: string | undefined): void {
|
|
36
|
+
if (model) this.entries.delete(model);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
live(): HiddenModelCooldown[] {
|
|
40
|
+
const now = this.now();
|
|
41
|
+
for (const [model, entry] of this.entries) {
|
|
42
|
+
if (entry.until <= now) this.entries.delete(model);
|
|
43
|
+
}
|
|
44
|
+
return [...this.entries.values()];
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
startIndex(models: readonly string[], log: (message: string) => void): number {
|
|
48
|
+
const live = new Map(this.live().map((entry) => [entry.model, entry]));
|
|
49
|
+
let start = models.findIndex((model) => !live.has(model));
|
|
50
|
+
// Even a fully exhausted chain must try a model, rather than suppress work.
|
|
51
|
+
if (start < 0) {
|
|
52
|
+
start = 0;
|
|
53
|
+
for (let i = 1; i < models.length; i++) {
|
|
54
|
+
if (
|
|
55
|
+
(live.get(models[i])?.until ?? Infinity) <
|
|
56
|
+
(live.get(models[start])?.until ?? Infinity)
|
|
57
|
+
)
|
|
58
|
+
start = i;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
const logged = new Set<string>();
|
|
62
|
+
for (const model of models.slice(0, start)) {
|
|
63
|
+
const entry = live.get(model);
|
|
64
|
+
if (entry && !logged.has(model)) {
|
|
65
|
+
log(
|
|
66
|
+
`skipping ${model} until ${new Date(entry.until).toISOString()}: provider said to retry later`,
|
|
67
|
+
);
|
|
68
|
+
logged.add(model);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return start;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function retryDelay(error: unknown, now: number, depth = 0): number | undefined {
|
|
76
|
+
if (!isRecord(error) || depth > 4) return undefined;
|
|
77
|
+
const data =
|
|
78
|
+
typeof error.statusCode === "number" || typeof error.status === "number"
|
|
79
|
+
? error
|
|
80
|
+
: isRecord(error.data)
|
|
81
|
+
? error.data
|
|
82
|
+
: error;
|
|
83
|
+
const status = data.statusCode ?? data.status;
|
|
84
|
+
if (status === 412 || status === 429 || status === 503) {
|
|
85
|
+
// OpenCode 2.2 exposes milliseconds; OpenCode 1 retains the HTTP headers.
|
|
86
|
+
if (typeof data.retryAfterMs === "number") return data.retryAfterMs;
|
|
87
|
+
const headers = data.responseHeaders;
|
|
88
|
+
if (isRecord(headers)) {
|
|
89
|
+
const value = Object.entries(headers).find(
|
|
90
|
+
([name]) => name.toLowerCase() === "retry-after",
|
|
91
|
+
)?.[1];
|
|
92
|
+
if (typeof value === "string") {
|
|
93
|
+
const text = value.trim();
|
|
94
|
+
if (/^\d+$/.test(text)) return Number(text) * 1_000;
|
|
95
|
+
// Require an HTTP-date shape: Date.parse also accepts bare numbers and prose.
|
|
96
|
+
if (
|
|
97
|
+
/^(?:(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d{2} [A-Z][a-z]{2} \d{4} \d{2}:\d{2}:\d{2} GMT|(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), \d{2}-[A-Z][a-z]{2}-\d{2} \d{2}:\d{2}:\d{2} GMT|(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) [A-Z][a-z]{2} [ \d]\d \d{2}:\d{2}:\d{2} \d{4})$/.test(
|
|
98
|
+
text,
|
|
99
|
+
)
|
|
100
|
+
)
|
|
101
|
+
return Date.parse(text) - now;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return retryDelay(error.hostError ?? error.cause, now, depth + 1);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export const hiddenModelCooldowns = new HiddenModelCooldowns();
|
|
109
|
+
|
|
110
|
+
/** Change only the starting point; failures still continue down the configured suffix. */
|
|
111
|
+
export function selectHiddenModelStart(
|
|
112
|
+
primary: ModelInput | undefined,
|
|
113
|
+
fallbacks: readonly ModelInput[] = [],
|
|
114
|
+
note: (message: string) => void,
|
|
115
|
+
): { primary: ModelInput | undefined; fallbacks: readonly ModelInput[] } {
|
|
116
|
+
if (!primary) return { primary, fallbacks };
|
|
117
|
+
const chain = [primary, ...fallbacks];
|
|
118
|
+
const start = hiddenModelCooldowns.startIndex(
|
|
119
|
+
chain.map((entry) => toModelEntry(entry)?.model ?? ""),
|
|
120
|
+
note,
|
|
121
|
+
);
|
|
122
|
+
return { primary: chain[start], fallbacks: chain.slice(start + 1) };
|
|
123
|
+
}
|
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import { describe, expect, mock, spyOn, test } from "bun:test";
|
|
2
|
-
import { withDreamerModelCooldown } from "../features/magic-context/dreamer/provider-output-failure";
|
|
3
2
|
import { recordedGeminiQuotaMessages } from "../features/magic-context/dreamer/provider-output-failure.test-support";
|
|
4
|
-
|
|
5
3
|
import { HiddenAgentStepLimit } from "../v2/hooks/hidden-child";
|
|
4
|
+
import { hiddenModelCooldowns } from "./hidden-model-cooldown";
|
|
6
5
|
import {
|
|
7
6
|
getPromptFailureDetail,
|
|
8
7
|
noteModelActivityMonitored,
|
|
@@ -422,104 +421,82 @@ describe("promptSyncWithModelSuggestionRetry", () => {
|
|
|
422
421
|
});
|
|
423
422
|
});
|
|
424
423
|
|
|
425
|
-
describe("
|
|
426
|
-
test("
|
|
424
|
+
describe("process-wide hidden model quota cooldown", () => {
|
|
425
|
+
test("structured refusal makes later runs start on the fallback, then expires", async () => {
|
|
427
426
|
let now = 1791425104275;
|
|
428
427
|
const clock = spyOn(Date, "now").mockImplementation(() => now);
|
|
429
428
|
const models: string[] = [];
|
|
430
|
-
const primary = { providerID: "
|
|
431
|
-
let latestModel = "";
|
|
432
|
-
let primaryCalls = 0;
|
|
429
|
+
const primary = { providerID: "quota-test", modelID: "primary" };
|
|
433
430
|
const client = createClient(
|
|
434
431
|
mock(async (args: PromptCall) => {
|
|
435
|
-
|
|
436
|
-
models.push(
|
|
437
|
-
if (
|
|
438
|
-
|
|
432
|
+
const model = `${args.body.model?.providerID}/${args.body.model?.modelID}`;
|
|
433
|
+
models.push(model);
|
|
434
|
+
if (model === "quota-test/primary" && models.length === 1)
|
|
435
|
+
throw Object.assign(new Error("provider quota exhausted"), {
|
|
436
|
+
statusCode: 412,
|
|
437
|
+
responseHeaders: { "retry-after": "190000" },
|
|
438
|
+
});
|
|
439
|
+
if (model === "quota-test/first") throw new Error("fallback unavailable");
|
|
439
440
|
return {};
|
|
440
441
|
}),
|
|
441
442
|
);
|
|
442
443
|
const run = () =>
|
|
443
444
|
promptSyncWithValidatedOutputRetry(client, createArgs(primary), {
|
|
444
|
-
fallbackModels: ["
|
|
445
|
-
fetchOutput: async () =>
|
|
446
|
-
|
|
447
|
-
? recordedGeminiQuotaMessages()
|
|
448
|
-
: [
|
|
449
|
-
{
|
|
450
|
-
info: { role: "assistant" },
|
|
451
|
-
parts: [{ type: "text", text: "valid" }],
|
|
452
|
-
},
|
|
453
|
-
],
|
|
454
|
-
validateOutput: () => "valid",
|
|
445
|
+
fallbackModels: ["quota-test/first", "quota-test/second"],
|
|
446
|
+
fetchOutput: async () => "valid",
|
|
447
|
+
validateOutput: (output) => output,
|
|
455
448
|
});
|
|
456
449
|
try {
|
|
457
|
-
await
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
await withDreamerModelCooldown(async () => {
|
|
462
|
-
await run();
|
|
463
|
-
await run();
|
|
464
|
-
now += 5_700_000;
|
|
465
|
-
await run();
|
|
466
|
-
});
|
|
450
|
+
await run();
|
|
451
|
+
await run();
|
|
452
|
+
now += 190_000_000;
|
|
453
|
+
await run();
|
|
467
454
|
expect(models).toEqual([
|
|
468
|
-
"
|
|
469
|
-
"
|
|
470
|
-
"
|
|
471
|
-
"
|
|
472
|
-
"
|
|
473
|
-
"
|
|
474
|
-
"deepseek/first",
|
|
475
|
-
"deepseek/second",
|
|
476
|
-
"deepseek/first",
|
|
477
|
-
"deepseek/second",
|
|
478
|
-
"google/antigravity-gemini-3.8-flash",
|
|
455
|
+
"quota-test/primary",
|
|
456
|
+
"quota-test/first",
|
|
457
|
+
"quota-test/second",
|
|
458
|
+
"quota-test/first",
|
|
459
|
+
"quota-test/second",
|
|
460
|
+
"quota-test/primary",
|
|
479
461
|
]);
|
|
480
462
|
} finally {
|
|
463
|
+
hiddenModelCooldowns.succeeded("quota-test/primary");
|
|
481
464
|
clock.mockRestore();
|
|
482
465
|
}
|
|
483
466
|
});
|
|
484
467
|
|
|
485
|
-
test("
|
|
486
|
-
|
|
468
|
+
test("a prose quota notice still falls back but never creates a cooldown", async () => {
|
|
469
|
+
const models: string[] = [];
|
|
470
|
+
let latest = "";
|
|
487
471
|
const client = createClient(
|
|
488
472
|
mock(async (args: PromptCall) => {
|
|
489
|
-
|
|
490
|
-
|
|
473
|
+
latest = `${args.body.model?.providerID}/${args.body.model?.modelID}`;
|
|
474
|
+
models.push(latest);
|
|
491
475
|
return {};
|
|
492
476
|
}),
|
|
493
477
|
);
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
expect(
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
failureClass: "provider_error",
|
|
517
|
-
modelAttempted: "deepseek/deepseek-flash",
|
|
518
|
-
modelsTried: ["google/antigravity-gemini-3.8-flash", "deepseek/deepseek-flash"],
|
|
519
|
-
});
|
|
520
|
-
expect(getPromptFailureDetail(caught)?.providerError).toContain(
|
|
521
|
-
"primary quota exhausted until",
|
|
522
|
-
);
|
|
478
|
+
const run = () =>
|
|
479
|
+
promptSyncWithValidatedOutputRetry(
|
|
480
|
+
client,
|
|
481
|
+
createArgs({ providerID: "quota-prose", modelID: "primary" }),
|
|
482
|
+
{
|
|
483
|
+
fallbackModels: ["quota-prose/fallback"],
|
|
484
|
+
fetchOutput: async () =>
|
|
485
|
+
latest.endsWith("/primary") ? recordedGeminiQuotaMessages() : [],
|
|
486
|
+
validateOutput: () => "valid",
|
|
487
|
+
},
|
|
488
|
+
);
|
|
489
|
+
await run();
|
|
490
|
+
await run();
|
|
491
|
+
expect(models).toEqual([
|
|
492
|
+
"quota-prose/primary",
|
|
493
|
+
"quota-prose/fallback",
|
|
494
|
+
"quota-prose/primary",
|
|
495
|
+
"quota-prose/fallback",
|
|
496
|
+
]);
|
|
497
|
+
expect(
|
|
498
|
+
hiddenModelCooldowns.live().some((entry) => entry.model === "quota-prose/primary"),
|
|
499
|
+
).toBe(false);
|
|
523
500
|
});
|
|
524
501
|
});
|
|
525
502
|
|
|
@@ -1,9 +1,7 @@
|
|
|
1
1
|
import type { createOpencodeClient } from "@opencode-ai/sdk";
|
|
2
2
|
import {
|
|
3
|
-
|
|
4
|
-
primaryQuotaFailure,
|
|
3
|
+
isAccountPoolQuotaNotice,
|
|
5
4
|
providerOutputFailureFromInvalidManifest,
|
|
6
|
-
rememberPrimaryQuota,
|
|
7
5
|
} from "../features/magic-context/dreamer/provider-output-failure";
|
|
8
6
|
import { DreamTokenBudgetExceeded } from "../features/magic-context/dreamer/token-budget";
|
|
9
7
|
import { detectOverflow } from "../features/magic-context/overflow-detection";
|
|
@@ -15,10 +13,11 @@ import {
|
|
|
15
13
|
extractLatestAssistantFailure,
|
|
16
14
|
extractLatestAssistantText,
|
|
17
15
|
} from "./assistant-message-extractor";
|
|
16
|
+
import { hiddenModelCooldowns, selectHiddenModelStart } from "./hidden-model-cooldown";
|
|
18
17
|
import { log } from "./logger";
|
|
19
18
|
import type { ModelInput } from "./model-resolution";
|
|
20
19
|
import { sanitizeDiagnosticText } from "./redaction";
|
|
21
|
-
import { parseProviderModel, toModelEntry } from "./resolve-fallbacks";
|
|
20
|
+
import { modelBodyField, parseProviderModel, toModelEntry } from "./resolve-fallbacks";
|
|
22
21
|
|
|
23
22
|
type Client = ReturnType<typeof createOpencodeClient> | undefined;
|
|
24
23
|
|
|
@@ -67,8 +66,6 @@ export interface PromptAttemptInfo {
|
|
|
67
66
|
totalAttempts: number;
|
|
68
67
|
/** Explicit model override for this attempt, when one was supplied. */
|
|
69
68
|
model?: { providerID: string; modelID: string };
|
|
70
|
-
/** A run-local quota deadline prevented dispatch; not an actual model call. */
|
|
71
|
-
skipped?: boolean;
|
|
72
69
|
}
|
|
73
70
|
|
|
74
71
|
export interface PromptRetryOptions {
|
|
@@ -553,25 +550,14 @@ function throwWithPromptFailure(
|
|
|
553
550
|
legacyError instanceof Error ? legacyError : new Error(extractMessage(legacyError));
|
|
554
551
|
const last = failedAttempts.at(-1);
|
|
555
552
|
const failureClass = last?.failureClass ?? "unknown";
|
|
556
|
-
const quota = failedAttempts.find(
|
|
557
|
-
(failure) =>
|
|
558
|
-
failure.error instanceof DreamerProviderOutputFailureError &&
|
|
559
|
-
failure.error.quotaResetAt !== undefined,
|
|
560
|
-
)?.error as DreamerProviderOutputFailureError | undefined;
|
|
561
|
-
if (quota && error !== quota && !error.message.includes(quota.message))
|
|
562
|
-
error.message = `${quota.message}; ${error.message}`;
|
|
563
553
|
const providerError =
|
|
564
|
-
failureClass === "provider_error"
|
|
565
|
-
? sanitizeDiagnosticText(
|
|
566
|
-
`${quota ? `${quota.message}; ` : ""}${shortErr(last?.error ?? legacyError)}`,
|
|
567
|
-
).slice(0, 500)
|
|
554
|
+
failureClass === "provider_error"
|
|
555
|
+
? sanitizeDiagnosticText(shortErr(last?.error ?? legacyError)).slice(0, 500)
|
|
568
556
|
: null;
|
|
569
557
|
promptFailureDetails.set(error, {
|
|
570
558
|
failureClass,
|
|
571
559
|
modelAttempted: last?.attempt.label ?? null,
|
|
572
|
-
modelsTried: failedAttempts
|
|
573
|
-
.filter((failure) => !failure.attempt.skipped)
|
|
574
|
-
.map((failure) => failure.attempt.label),
|
|
560
|
+
modelsTried: failedAttempts.map((failure) => failure.attempt.label),
|
|
575
561
|
providerError,
|
|
576
562
|
timeoutMs: failureClass === "provider_timeout" ? timeoutMs : null,
|
|
577
563
|
childSessionId: transport ? (transport.childSessionId ?? null) : args.path.id || null,
|
|
@@ -618,6 +604,8 @@ async function attemptOnce(
|
|
|
618
604
|
} catch (error) {
|
|
619
605
|
// Non-retryable failures and callers with model suggestions disabled
|
|
620
606
|
// must surface the original error without accepting a provider suggestion.
|
|
607
|
+
if (!signal?.aborted && !isPromptTimeoutError(error))
|
|
608
|
+
hiddenModelCooldowns.record(label, error);
|
|
621
609
|
if (isNonRetryable(error, signal) || !allowModelSuggestions) throw error;
|
|
622
610
|
|
|
623
611
|
const suggestion = parseModelSuggestion(error);
|
|
@@ -686,6 +674,24 @@ function createChainClock(options: PromptRetryOptions, timeoutMs: number) {
|
|
|
686
674
|
};
|
|
687
675
|
}
|
|
688
676
|
|
|
677
|
+
function cooldownStart<T extends PromptRetryOptions>(
|
|
678
|
+
args: PromptArgs,
|
|
679
|
+
options: T,
|
|
680
|
+
): { args: PromptArgs; options: T } {
|
|
681
|
+
const model = args.body.model;
|
|
682
|
+
if (!model) return { args, options };
|
|
683
|
+
const selected = selectHiddenModelStart(
|
|
684
|
+
{ model: `${model.providerID}/${model.modelID}`, qualifier: args.body.variant },
|
|
685
|
+
options.fallbackModels,
|
|
686
|
+
log,
|
|
687
|
+
);
|
|
688
|
+
const { variant: _variant, ...body } = args.body;
|
|
689
|
+
return {
|
|
690
|
+
args: copyPromptArgs(args, { ...body, ...modelBodyField(selected.primary) }),
|
|
691
|
+
options: { ...options, fallbackModels: selected.fallbacks },
|
|
692
|
+
};
|
|
693
|
+
}
|
|
694
|
+
|
|
689
695
|
/**
|
|
690
696
|
* Run an OpenCode subagent prompt with model fallback support.
|
|
691
697
|
*
|
|
@@ -705,6 +711,7 @@ export async function promptSyncWithModelSuggestionRetry(
|
|
|
705
711
|
args: PromptArgs,
|
|
706
712
|
options: PromptRetryOptions = {},
|
|
707
713
|
): Promise<void> {
|
|
714
|
+
({ args, options } = cooldownStart(args, options));
|
|
708
715
|
const timeoutMs = options.timeoutMs ?? 300_000;
|
|
709
716
|
const callContext = options.callContext ?? "subagent";
|
|
710
717
|
const fallbacks = options.fallbackModels ?? [];
|
|
@@ -848,6 +855,8 @@ async function attemptAndValidate<TOutput, TValidated>(
|
|
|
848
855
|
try {
|
|
849
856
|
output = await raceWithSignal(options.fetchOutput(args, attempt), options.signal);
|
|
850
857
|
} catch (error) {
|
|
858
|
+
if (!signal?.aborted && !isPromptTimeoutError(error))
|
|
859
|
+
hiddenModelCooldowns.record(attempt.label, error);
|
|
851
860
|
throw {
|
|
852
861
|
error,
|
|
853
862
|
failureClass: classifyPromptFailure(error, "output", signal),
|
|
@@ -856,7 +865,7 @@ async function attemptAndValidate<TOutput, TValidated>(
|
|
|
856
865
|
}
|
|
857
866
|
|
|
858
867
|
try {
|
|
859
|
-
// Only the
|
|
868
|
+
// Only the exact account-pool notice bypasses caller validation.
|
|
860
869
|
// The near-zero-token heuristic remains owned by manifest callers.
|
|
861
870
|
const messages = Array.isArray(output)
|
|
862
871
|
? output
|
|
@@ -864,7 +873,7 @@ async function attemptAndValidate<TOutput, TValidated>(
|
|
|
864
873
|
const text = extractLatestAssistantText(messages);
|
|
865
874
|
if (text) {
|
|
866
875
|
const failure = providerOutputFailureFromInvalidManifest(messages, text);
|
|
867
|
-
if (failure
|
|
876
|
+
if (failure && isAccountPoolQuotaNotice(text)) throw failure;
|
|
868
877
|
}
|
|
869
878
|
if (!extractLatestAssistantText(output)) {
|
|
870
879
|
const assistantFailure = extractLatestAssistantFailure(output);
|
|
@@ -875,10 +884,13 @@ async function attemptAndValidate<TOutput, TValidated>(
|
|
|
875
884
|
Object.assign(error, {
|
|
876
885
|
name: "DreamerProviderOutputFailureError",
|
|
877
886
|
transient: true,
|
|
887
|
+
hostError: assistantFailure.error,
|
|
878
888
|
});
|
|
889
|
+
hiddenModelCooldowns.record(attempt.label, assistantFailure.error);
|
|
879
890
|
throw error;
|
|
880
891
|
}
|
|
881
892
|
}
|
|
893
|
+
hiddenModelCooldowns.succeeded(attempt.label);
|
|
882
894
|
const validated = await options.validateOutput(output, attempt);
|
|
883
895
|
return { output, validated, attempt };
|
|
884
896
|
} catch (error) {
|
|
@@ -903,6 +915,7 @@ export async function promptSyncWithValidatedOutputRetry<TOutput, TValidated = T
|
|
|
903
915
|
args: PromptArgs,
|
|
904
916
|
options: ValidatedPromptRetryOptions<TOutput, TValidated>,
|
|
905
917
|
): Promise<ValidatedPromptRetryResult<TOutput, TValidated>> {
|
|
918
|
+
({ args, options } = cooldownStart(args, options));
|
|
906
919
|
const timeoutMs = options.timeoutMs ?? 300_000;
|
|
907
920
|
const callContext = options.callContext ?? "subagent";
|
|
908
921
|
const fallbacks = options.fallbackModels ?? [];
|
|
@@ -920,24 +933,10 @@ export async function promptSyncWithValidatedOutputRetry<TOutput, TValidated = T
|
|
|
920
933
|
const failedAttempts: FailedAttempt[] = [];
|
|
921
934
|
let firstError: unknown = null;
|
|
922
935
|
let lastError: unknown = null;
|
|
923
|
-
const cooledPrimary = primaryQuotaFailure(explicitPrimaryLabel);
|
|
924
936
|
const clock = createChainClock(options, timeoutMs);
|
|
925
937
|
|
|
926
938
|
const primaryStartedAt = Date.now();
|
|
927
939
|
try {
|
|
928
|
-
if (cooledPrimary)
|
|
929
|
-
throw {
|
|
930
|
-
error: cooledPrimary,
|
|
931
|
-
failureClass: "provider_error",
|
|
932
|
-
attempt: {
|
|
933
|
-
label: explicitPrimaryLabel,
|
|
934
|
-
attemptIndex: 0,
|
|
935
|
-
isFallback: false,
|
|
936
|
-
totalAttempts,
|
|
937
|
-
model: baseBody.model,
|
|
938
|
-
skipped: true,
|
|
939
|
-
},
|
|
940
|
-
} satisfies FailedAttempt;
|
|
941
940
|
const budget = clock.budget(0);
|
|
942
941
|
return await attemptAndValidate(
|
|
943
942
|
client,
|
|
@@ -961,19 +960,6 @@ export async function promptSyncWithValidatedOutputRetry<TOutput, TValidated = T
|
|
|
961
960
|
clock.settle(failure.error, primaryStartedAt);
|
|
962
961
|
firstError = failure.error;
|
|
963
962
|
lastError = failure.error;
|
|
964
|
-
if (
|
|
965
|
-
failure.error instanceof DreamerProviderOutputFailureError &&
|
|
966
|
-
failure.error.quotaResetAt !== undefined
|
|
967
|
-
)
|
|
968
|
-
failure.error.message = failure.error.message.replace(
|
|
969
|
-
/^provider quota exhausted/,
|
|
970
|
-
"primary quota exhausted",
|
|
971
|
-
);
|
|
972
|
-
const quota = !cooledPrimary && rememberPrimaryQuota(explicitPrimaryLabel, failure.error);
|
|
973
|
-
if (quota)
|
|
974
|
-
log(
|
|
975
|
-
`[${callContext}] ${quota.message}; skipping ${explicitPrimaryLabel} for this run until reset`,
|
|
976
|
-
);
|
|
977
963
|
if (isNonRetryable(failure.error, options.signal)) {
|
|
978
964
|
throwWithPromptFailure(
|
|
979
965
|
failure.error,
|
|
@@ -994,10 +980,9 @@ export async function promptSyncWithValidatedOutputRetry<TOutput, TValidated = T
|
|
|
994
980
|
);
|
|
995
981
|
}
|
|
996
982
|
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
);
|
|
983
|
+
log(
|
|
984
|
+
`[${callContext}] primary (${explicitPrimaryLabel}) failed validation/prompt: ${shortErr(failure.error)}; ${fallbacks.length} fallback(s) configured, subject to remaining budget`,
|
|
985
|
+
);
|
|
1001
986
|
}
|
|
1002
987
|
|
|
1003
988
|
for (let i = 0; i < fallbacks.length; i += 1) {
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { expect, test } from "bun:test";
|
|
2
|
+
import * as completion from "./provider-response-completion";
|
|
3
|
+
|
|
4
|
+
for (const location of ["native", "state"]) {
|
|
5
|
+
test(`detects usage and boundary markers in ${location}.signature`, () => {
|
|
6
|
+
for (const [signature, expected] of [
|
|
7
|
+
[
|
|
8
|
+
'cortexkit-server-fallback-usage-v1:{"iterations":[{"type":"fallback_message","input_tokens":1}]}',
|
|
9
|
+
{ kind: "usage", inputTokens: 1 },
|
|
10
|
+
],
|
|
11
|
+
[
|
|
12
|
+
"cortexkit-server-fallback-v1:primary|fallback",
|
|
13
|
+
{ kind: "boundary", invalidUsage: false },
|
|
14
|
+
],
|
|
15
|
+
] as const) {
|
|
16
|
+
const content = [{ type: "reasoning", [location]: { signature } }];
|
|
17
|
+
expect(completion.hasServerFallbackUsage(content)).toBe(true);
|
|
18
|
+
expect(completion.readServerFallbackUsage(content)).toEqual(expected);
|
|
19
|
+
}
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
test("detects server-fallback usage only in the marked reasoning part", () => {
|
|
24
|
+
const content = [
|
|
25
|
+
{ type: "reasoning", text: "thinking", native: { signature: "real-signature" } },
|
|
26
|
+
{
|
|
27
|
+
type: "reasoning",
|
|
28
|
+
text: " ",
|
|
29
|
+
native: {
|
|
30
|
+
signature: "cortexkit-server-fallback-v1:claude-opus-5-5|claude-opus-4-8",
|
|
31
|
+
},
|
|
32
|
+
},
|
|
33
|
+
{ type: "text", text: "answer" },
|
|
34
|
+
{ type: "tool", name: "read" },
|
|
35
|
+
];
|
|
36
|
+
expect(completion.hasServerFallbackUsage(content)).toBe(true);
|
|
37
|
+
expect(completion.hasServerFallbackUsage([content[0], content[2]])).toBe(false);
|
|
38
|
+
for (const invalid of [
|
|
39
|
+
undefined,
|
|
40
|
+
null,
|
|
41
|
+
{},
|
|
42
|
+
[null, {}, { type: "reasoning", native: { signature: 3 } }],
|
|
43
|
+
[{ type: "text", native: content[1]!.native }],
|
|
44
|
+
[{ type: "reasoning", native: { signature: "cortexkit-server-fallback-v10:models" } }],
|
|
45
|
+
[{ type: "reasoning", native: { signature: "other-cortexkit-server-fallback-v1:models" } }],
|
|
46
|
+
]) {
|
|
47
|
+
expect(completion.hasServerFallbackUsage(invalid)).toBe(false);
|
|
48
|
+
}
|
|
49
|
+
});
|
|
@@ -1,3 +1,67 @@
|
|
|
1
|
+
import { isRecord } from "./record-type-guard";
|
|
2
|
+
|
|
3
|
+
const SERVER_FALLBACK_USAGE_SIGNATURE_PREFIX = "cortexkit-server-fallback-usage-v1:";
|
|
4
|
+
const SERVER_FALLBACK_SIGNATURE_PREFIX = "cortexkit-server-fallback-v1:";
|
|
5
|
+
|
|
6
|
+
export function hasServerFallbackUsage(content: unknown): boolean {
|
|
7
|
+
return readServerFallbackUsage(content) !== undefined;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
type ServerFallbackUsage =
|
|
11
|
+
| { kind: "usage"; inputTokens: number }
|
|
12
|
+
| { kind: "boundary"; invalidUsage: boolean };
|
|
13
|
+
|
|
14
|
+
function parseServerFallbackInputTokens(json: string): number | undefined {
|
|
15
|
+
try {
|
|
16
|
+
const payload: unknown = JSON.parse(json);
|
|
17
|
+
if (!isRecord(payload) || !Array.isArray(payload.iterations)) return undefined;
|
|
18
|
+
let last: unknown;
|
|
19
|
+
for (const entry of payload.iterations) {
|
|
20
|
+
if (isRecord(entry) && entry.type === "fallback_message") last = entry;
|
|
21
|
+
}
|
|
22
|
+
if (!isRecord(last)) return undefined;
|
|
23
|
+
const counts = [
|
|
24
|
+
last.input_tokens,
|
|
25
|
+
last.cache_read_input_tokens ?? 0,
|
|
26
|
+
last.cache_creation_input_tokens ?? 0,
|
|
27
|
+
];
|
|
28
|
+
if (
|
|
29
|
+
!counts.every(
|
|
30
|
+
(count) => typeof count === "number" && Number.isFinite(count) && count >= 0,
|
|
31
|
+
)
|
|
32
|
+
)
|
|
33
|
+
return undefined;
|
|
34
|
+
const inputTokens = counts.reduce<number>((sum, count) => sum + Number(count), 0);
|
|
35
|
+
return Number.isFinite(inputTokens) ? inputTokens : undefined;
|
|
36
|
+
} catch {
|
|
37
|
+
// Invalid usage must not replace the previous pressure measurement.
|
|
38
|
+
return undefined;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function readServerFallbackUsage(content: unknown): ServerFallbackUsage | undefined {
|
|
43
|
+
if (!Array.isArray(content)) return undefined;
|
|
44
|
+
let boundary = false;
|
|
45
|
+
let invalidUsage = false;
|
|
46
|
+
for (const part of content) {
|
|
47
|
+
if (!isRecord(part) || part.type !== "reasoning") continue;
|
|
48
|
+
for (const location of [part.native, part.state]) {
|
|
49
|
+
if (!isRecord(location) || typeof location.signature !== "string") continue;
|
|
50
|
+
const signature = location.signature;
|
|
51
|
+
if (signature.startsWith(SERVER_FALLBACK_USAGE_SIGNATURE_PREFIX)) {
|
|
52
|
+
const inputTokens = parseServerFallbackInputTokens(
|
|
53
|
+
signature.slice(SERVER_FALLBACK_USAGE_SIGNATURE_PREFIX.length),
|
|
54
|
+
);
|
|
55
|
+
if (inputTokens !== undefined) return { kind: "usage", inputTokens };
|
|
56
|
+
invalidUsage = true;
|
|
57
|
+
} else if (signature.startsWith(SERVER_FALLBACK_SIGNATURE_PREFIX)) {
|
|
58
|
+
boundary = true;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return boundary || invalidUsage ? { kind: "boundary", invalidUsage } : undefined;
|
|
63
|
+
}
|
|
64
|
+
|
|
1
65
|
/** Failure markers take precedence over a completion timestamp or token usage. */
|
|
2
66
|
export function providerResponseFailed(input: { finish?: unknown; error?: unknown }): boolean {
|
|
3
67
|
if (input.error !== undefined && input.error !== null && input.error !== "") return true;
|
package/src/shared/rpc-types.ts
CHANGED
|
@@ -149,6 +149,7 @@ export interface SidebarSnapshot {
|
|
|
149
149
|
/** Dreamer tasks whose last scheduled run failed. Empty when all of them are
|
|
150
150
|
* healthy; absent on a database with no scheduler table yet. */
|
|
151
151
|
dreamerFailures?: DreamTaskFailureState[];
|
|
152
|
+
hiddenModelSkips?: string[];
|
|
152
153
|
dreamerSkipped?: string[];
|
|
153
154
|
recompProgress?: {
|
|
154
155
|
/** "recomp" → "Recomp" labels; "upgrade" → "Upgrade" labels. */
|