@cortexkit/opencode-magic-context 0.49.49 → 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/auto-search-worker.js +3 -3
- package/dist/chunk-embedding-write-worker.js +1 -1
- 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/{context-bwf57gnh.js → context-4js5qnnm.js} +37 -23
- package/dist/{embedding-backfill-d9x9q2e2.js → embedding-backfill-3wdjzrvs.js} +4 -4
- package/dist/embedding-worker.js +2 -2
- 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/hooks/magic-context/compartment-runner-historian.d.ts.map +1 -1
- package/dist/{index-qb75tv9j.js → index-07rp6xcn.js} +1 -1
- package/dist/{index-7n2n3v92.js → index-5dptmnvd.js} +2 -2
- package/dist/{index-j7verehm.js → index-5g6npyw5.js} +36 -27
- package/dist/{index-5bksfv58.js → index-5t1mr0bt.js} +5 -5
- package/dist/{index-arxg51bj.js → index-8d7gkgjs.js} +4 -3
- package/dist/{index-wdmfnmv1.js → index-97bjd14c.js} +4 -4
- package/dist/{index-0mdh2cke.js → index-bamnjp2t.js} +20 -4
- package/dist/{index-5850zme4.js → index-ct3ettqt.js} +3 -3
- package/dist/{index-3n9ee4jh.js → index-cwj6qhmf.js} +1 -1
- package/dist/{index-va9x7y48.js → index-h8g08nxs.js} +135 -81
- package/dist/{index-jedbxq6n.js → index-hkveze74.js} +1 -1
- package/dist/{index-4dpvnp8k.js → index-jjy5a5w0.js} +3 -0
- package/dist/{index-h3p558ec.js → index-mjh63zvw.js} +1 -1
- package/dist/{index-vyv4tame.js → index-n0twfvah.js} +53 -2
- package/dist/{index-tj5gz396.js → index-rbs27k1d.js} +4 -2
- package/dist/{index-cs7pmwt6.js → index-s131svmx.js} +1 -1
- package/dist/{index-vbmh68fb.js → index-v4a1pnny.js} +4 -4
- package/dist/{index-k47v0tmk.js → index-wr2t8zb0.js} +8 -8
- package/dist/{index-agfh931z.js → index-z4832qfe.js} +4 -2
- package/dist/index.js +22 -22
- package/dist/{message-index-bounded-2shxmht9.js → message-index-bounded-k0ebpy3y.js} +3 -3
- package/dist/migration-worker.js +1 -1
- 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-nzgkq61z.js → project-embedding-registry-5dwh5zfn.js} +3 -3
- package/dist/raw-ordinal-warmup-worker.js +3 -3
- package/dist/{read-session-chunk-c15y8yg6.js → read-session-chunk-6712p893.js} +2 -2
- package/dist/{recomp-orchestrator-gfxqqpph.js → recomp-orchestrator-8ebydg5j.js} +11 -11
- package/dist/{render-5tx8r0me.js → render-dtc4qkq4.js} +6 -6
- package/dist/{search-archive-6tgh88xp.js → search-archive-f6hjbnsa.js} +4 -4
- package/dist/{search-k2n5bvsk.js → search-edv0gy1d.js} +9 -9
- 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/test-preload.d.ts +2 -0
- package/dist/test-preload.d.ts.map +1 -0
- package/dist/{transform-postprocess-phase-36dw4kxb.js → transform-postprocess-phase-1bg25094.js} +12 -12
- package/dist/v2/auto-search-worker.js +3 -3
- package/dist/v2/chunk-embedding-write-worker.js +1 -1
- package/dist/v2/{context-td3jyze3.js → context-qkr7z6d0.js} +47 -30
- package/dist/v2/{embedding-backfill-5dqdm3ff.js → embedding-backfill-x1zpc04f.js} +4 -4
- package/dist/v2/embedding-worker.js +2 -2
- package/dist/v2/hidden-completion.d.ts.map +1 -1
- 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/{message-index-bounded-j1jskn8a.js → message-index-bounded-a36rw93p.js} +3 -3
- package/dist/v2/migration-worker.js +1 -1
- package/dist/v2/{project-embedding-registry-swm4mw1t.js → project-embedding-registry-v2fxrs8b.js} +3 -3
- package/dist/v2/raw-ordinal-warmup-worker.js +3 -3
- package/dist/v2/{read-session-chunk-carzw3m8.js → read-session-chunk-hzhxvhyv.js} +2 -2
- package/dist/v2/{recomp-orchestrator-e7vrs932.js → recomp-orchestrator-yzr49pd0.js} +11 -11
- package/dist/v2/{render-e9mh9y1d.js → render-rhaevxv1.js} +6 -6
- package/dist/v2/{search-archive-j3kb9ggd.js → search-archive-9924fyk8.js} +4 -4
- package/dist/v2/{search-sr23g316.js → search-ggvexvv7.js} +8 -8
- package/dist/v2/{server-z7n3n1ra.js → server-016a1whm.js} +134 -81
- package/dist/v2/{server-4y2pcckw.js → server-0k586y7d.js} +3 -3
- package/dist/v2/{server-p9s40wfa.js → server-0ms13pc8.js} +3 -0
- package/dist/v2/{server-c5kq8d5n.js → server-16kfxcxj.js} +1 -1
- package/dist/v2/{server-2qxt6qv0.js → server-3bfc26r7.js} +1 -1
- package/dist/v2/{server-e20kfytm.js → server-3qf9n5ck.js} +4 -4
- package/dist/v2/{server-fw49gc57.js → server-4h4acntc.js} +20 -4
- package/dist/v2/{server-yxe0gh3v.js → server-88yvx6r9.js} +53 -2
- package/dist/v2/{server-1ppcpsdw.js → server-brsx45r6.js} +4 -2
- package/dist/v2/{server-y7q8cds3.js → server-jxrqsn84.js} +1 -1
- package/dist/v2/{server-t5cgb15n.js → server-q93jdtz8.js} +2 -2
- package/dist/v2/{server-ttrrh27h.js → server-sb55ddgn.js} +3 -2
- package/dist/v2/{server-e14c3hd6.js → server-scp3y4dh.js} +4 -2
- package/dist/v2/{server-0qxb8r8q.js → server-sgn61hht.js} +1 -1
- package/dist/v2/{server-r7y35vm9.js → server-vjadwb3j.js} +4 -3
- package/dist/v2/server.js +4 -4
- package/dist/v2/{v2-archive-reader-jnzjavzr.js → v2-archive-reader-5ggewg8q.js} +1 -1
- package/dist/v2/{wrapup-orchestrator-jw4nre49.js → wrapup-orchestrator-36c5wyvq.js} +11 -11
- package/dist/{v2-archive-reader-b76tfeje.js → v2-archive-reader-gx5ke1d7.js} +1 -1
- package/dist/{wrapup-orchestrator-fhfazjkq.js → wrapup-orchestrator-ya31knav.js} +12 -12
- 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/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
|
@@ -72,7 +72,7 @@ import {
|
|
|
72
72
|
getRawSessionTagKeysThrough2,
|
|
73
73
|
getLegacyProtectedTailStartOrdinal2,
|
|
74
74
|
readSessionChunk2
|
|
75
|
-
} from "./index-
|
|
75
|
+
} from "./index-07rp6xcn.js";
|
|
76
76
|
import {
|
|
77
77
|
getHarness2,
|
|
78
78
|
harnessOwnsOpenCodeStore2
|
|
@@ -121,7 +121,7 @@ import {
|
|
|
121
121
|
ConfigProfilesSchema,
|
|
122
122
|
MagicContextConfigSchema,
|
|
123
123
|
LIVE_RELOAD_CONFIG_PATHS
|
|
124
|
-
} from "./index-
|
|
124
|
+
} from "./index-jjy5a5w0.js";
|
|
125
125
|
import {
|
|
126
126
|
providerMass,
|
|
127
127
|
calibrationForModelKey,
|
|
@@ -151,7 +151,7 @@ import {
|
|
|
151
151
|
LATEST_SUPPORTED_VERSION,
|
|
152
152
|
getPersistedSchemaVersion,
|
|
153
153
|
openDatabase
|
|
154
|
-
} from "./index-
|
|
154
|
+
} from "./index-z4832qfe.js";
|
|
155
155
|
import {
|
|
156
156
|
areRustHistorianSyntheticParts2,
|
|
157
157
|
isStrictGapHealingMessage2,
|
|
@@ -237,14 +237,14 @@ import {
|
|
|
237
237
|
getProjectState,
|
|
238
238
|
recordSubagentInvocation,
|
|
239
239
|
getLatestHistorianInvocationId
|
|
240
|
-
} from "./index-
|
|
240
|
+
} from "./index-n0twfvah.js";
|
|
241
241
|
import {
|
|
242
242
|
clearCompressionDepth,
|
|
243
243
|
clearCompressionDepthRange,
|
|
244
244
|
toMessageIndexSource,
|
|
245
245
|
clearIndexedMessagesInTransaction,
|
|
246
246
|
indexSourcesAfterOrdinal
|
|
247
|
-
} from "./index-
|
|
247
|
+
} from "./index-hkveze74.js";
|
|
248
248
|
import {
|
|
249
249
|
stripWellFormedLeadingTagPrefix,
|
|
250
250
|
peelLeadingMcTagNotation,
|
|
@@ -283,13 +283,13 @@ import {
|
|
|
283
283
|
getProjectChunkEmbeddingModelId2,
|
|
284
284
|
getProjectEmbeddingMaxInputTokens2,
|
|
285
285
|
embedItemsForProject2
|
|
286
|
-
} from "./index-
|
|
286
|
+
} from "./index-bamnjp2t.js";
|
|
287
287
|
import {
|
|
288
288
|
renderUserFacingFailure,
|
|
289
289
|
userFacingFailureCode,
|
|
290
290
|
promoteSessionFactsDurable,
|
|
291
291
|
embedPromotedFacts
|
|
292
|
-
} from "./index-
|
|
292
|
+
} from "./index-cwj6qhmf.js";
|
|
293
293
|
import {
|
|
294
294
|
isMarkerCandidateBasisCurrent2,
|
|
295
295
|
invalidateMarkerCandidateBasis2,
|
|
@@ -1513,7 +1513,8 @@ var EMBEDDING_USER_ONLY_FIELDS = [
|
|
|
1513
1513
|
"provider",
|
|
1514
1514
|
"fallback_provider",
|
|
1515
1515
|
"query_instruction",
|
|
1516
|
-
"document_prefix"
|
|
1516
|
+
"document_prefix",
|
|
1517
|
+
"dimensions"
|
|
1517
1518
|
];
|
|
1518
1519
|
var PERCENTAGE_THRESHOLD_REASON = "security: a repository may only raise compaction thresholds above the user's effective value; it cannot force earlier historian work or cloned-repo cost escalation.";
|
|
1519
1520
|
var TOKEN_THRESHOLD_REASON = "security: a repository may only raise execute_threshold_tokens above the user's trusted token threshold; it cannot force earlier historian work or cloned-repo cost escalation.";
|
|
@@ -4575,7 +4576,6 @@ class HiddenCompletionRefusal extends Error {
|
|
|
4575
4576
|
}
|
|
4576
4577
|
}
|
|
4577
4578
|
// src/features/magic-context/dreamer/provider-output-failure.ts
|
|
4578
|
-
import { AsyncLocalStorage } from "node:async_hooks";
|
|
4579
4579
|
import { createHash as createHash2 } from "node:crypto";
|
|
4580
4580
|
var MAX_NEAR_ZERO_OUTPUT_TOKENS = 32;
|
|
4581
4581
|
|
|
@@ -4583,52 +4583,18 @@ class DreamerProviderOutputFailureError extends Error {
|
|
|
4583
4583
|
fingerprint;
|
|
4584
4584
|
outputTokens;
|
|
4585
4585
|
reasoningTokens;
|
|
4586
|
-
quotaResetAt;
|
|
4587
4586
|
transient = true;
|
|
4588
|
-
constructor(fingerprint, outputTokens, reasoningTokens, responseText
|
|
4587
|
+
constructor(fingerprint, outputTokens, reasoningTokens, responseText) {
|
|
4589
4588
|
const preview = responseText.trim().replace(/\s+/g, " ").slice(0, 160);
|
|
4590
|
-
super(
|
|
4589
|
+
super(`dreamer provider-outage completion (output_tokens=${outputTokens}, reasoning_tokens=${reasoningTokens}): ${JSON.stringify(preview)}`);
|
|
4591
4590
|
this.fingerprint = fingerprint;
|
|
4592
4591
|
this.outputTokens = outputTokens;
|
|
4593
4592
|
this.reasoningTokens = reasoningTokens;
|
|
4594
|
-
this.quotaResetAt = quotaResetAt;
|
|
4595
4593
|
this.name = "DreamerProviderOutputFailureError";
|
|
4596
4594
|
}
|
|
4597
4595
|
}
|
|
4598
|
-
|
|
4599
|
-
|
|
4600
|
-
return primaryQuotas.getStore() ? run() : primaryQuotas.run(new Map, run);
|
|
4601
|
-
}
|
|
4602
|
-
function rememberPrimaryQuota(model, error) {
|
|
4603
|
-
const quotas = primaryQuotas.getStore();
|
|
4604
|
-
if (!quotas || model === "primary" || !(error instanceof DreamerProviderOutputFailureError) || error.quotaResetAt === undefined || error.quotaResetAt <= Date.now())
|
|
4605
|
-
return null;
|
|
4606
|
-
const cached = new DreamerProviderOutputFailureError(error.fingerprint, error.outputTokens, error.reasoningTokens, "", error.quotaResetAt);
|
|
4607
|
-
cached.message = error.message;
|
|
4608
|
-
quotas.set(model, cached);
|
|
4609
|
-
return error;
|
|
4610
|
-
}
|
|
4611
|
-
function primaryQuotaFailure(model) {
|
|
4612
|
-
const quotas = primaryQuotas.getStore();
|
|
4613
|
-
const error = quotas?.get(model);
|
|
4614
|
-
if (!error)
|
|
4615
|
-
return null;
|
|
4616
|
-
if (error.quotaResetAt === undefined || error.quotaResetAt <= Date.now()) {
|
|
4617
|
-
quotas?.delete(model);
|
|
4618
|
-
return null;
|
|
4619
|
-
}
|
|
4620
|
-
const failure = new DreamerProviderOutputFailureError(error.fingerprint, error.outputTokens, error.reasoningTokens, "", error.quotaResetAt);
|
|
4621
|
-
failure.message = error.message;
|
|
4622
|
-
return failure;
|
|
4623
|
-
}
|
|
4624
|
-
function quotaResetAt(responseText, now) {
|
|
4625
|
-
const notice = /^All [1-9]\d* account\(s\) rate-limited for [\w.-]+\. Quota resets in ((?:\d+[hms] ?)+)\. Add more accounts with `opencode auth login` or wait and retry\.$/.exec(responseText.trim());
|
|
4626
|
-
if (!notice)
|
|
4627
|
-
return;
|
|
4628
|
-
const units = { h: 3600000, m: 60000, s: 1000 };
|
|
4629
|
-
const duration = [...notice[1].matchAll(/(\d+)([hms])/g)].reduce((sum, match) => sum + Number(match[1]) * units[match[2]], 0);
|
|
4630
|
-
const resetAt = now + duration;
|
|
4631
|
-
return duration > 0 && Number.isSafeInteger(resetAt) && resetAt < 8640000000000000 ? resetAt : undefined;
|
|
4596
|
+
function isAccountPoolQuotaNotice(responseText) {
|
|
4597
|
+
return /^All [1-9]\d* account\(s\) rate-limited for [\w.-]+\. Quota resets in (?:\d+[hms] ?)+\. Add more accounts with `opencode auth login` or wait and retry\.$/.test(responseText.trim());
|
|
4632
4598
|
}
|
|
4633
4599
|
function finiteTokenCount(value) {
|
|
4634
4600
|
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;
|
|
@@ -4660,7 +4626,7 @@ function latestAssistantCompletion(messages) {
|
|
|
4660
4626
|
}
|
|
4661
4627
|
return latest;
|
|
4662
4628
|
}
|
|
4663
|
-
function providerOutputFailureFromInvalidManifest(messages, responseText
|
|
4629
|
+
function providerOutputFailureFromInvalidManifest(messages, responseText) {
|
|
4664
4630
|
const completion = latestAssistantCompletion(messages);
|
|
4665
4631
|
if (completion?.finish?.toLowerCase() !== "stop")
|
|
4666
4632
|
return null;
|
|
@@ -4670,11 +4636,10 @@ function providerOutputFailureFromInvalidManifest(messages, responseText, now =
|
|
|
4670
4636
|
const normalized = responseText.trim().replace(/\s+/g, " ").toLowerCase();
|
|
4671
4637
|
if (!normalized)
|
|
4672
4638
|
return null;
|
|
4673
|
-
|
|
4674
|
-
if (resetAt === undefined && completion.outputTokens > MAX_NEAR_ZERO_OUTPUT_TOKENS)
|
|
4639
|
+
if (!isAccountPoolQuotaNotice(responseText) && completion.outputTokens > MAX_NEAR_ZERO_OUTPUT_TOKENS)
|
|
4675
4640
|
return null;
|
|
4676
4641
|
const fingerprint = createHash2("sha256").update(normalized).digest("hex").slice(0, 16);
|
|
4677
|
-
return new DreamerProviderOutputFailureError(fingerprint, completion.outputTokens, completion.reasoningTokens, responseText
|
|
4642
|
+
return new DreamerProviderOutputFailureError(fingerprint, completion.outputTokens, completion.reasoningTokens, responseText);
|
|
4678
4643
|
}
|
|
4679
4644
|
|
|
4680
4645
|
// src/v2/hooks/hidden-child.ts
|
|
@@ -5201,6 +5166,94 @@ function toModelEntry(spec) {
|
|
|
5201
5166
|
return spec;
|
|
5202
5167
|
}
|
|
5203
5168
|
|
|
5169
|
+
// src/shared/hidden-model-cooldown.ts
|
|
5170
|
+
var MAX_SKIP_MS = 7 * 24 * 60 * 60 * 1000;
|
|
5171
|
+
var MIN_SKIP_MS = 60000;
|
|
5172
|
+
var RETRY_LATER_REASON = "provider said to retry later";
|
|
5173
|
+
|
|
5174
|
+
class HiddenModelCooldowns {
|
|
5175
|
+
now;
|
|
5176
|
+
entries = new Map;
|
|
5177
|
+
constructor(now = () => Date.now()) {
|
|
5178
|
+
this.now = now;
|
|
5179
|
+
}
|
|
5180
|
+
record(model, error) {
|
|
5181
|
+
if (!model?.includes("/"))
|
|
5182
|
+
return;
|
|
5183
|
+
const now = this.now();
|
|
5184
|
+
const delay = retryDelay(error, now);
|
|
5185
|
+
if (delay === undefined || !Number.isFinite(delay) || delay <= MIN_SKIP_MS)
|
|
5186
|
+
return;
|
|
5187
|
+
this.entries.set(model, {
|
|
5188
|
+
model,
|
|
5189
|
+
until: now + Math.min(delay, MAX_SKIP_MS),
|
|
5190
|
+
reason: RETRY_LATER_REASON
|
|
5191
|
+
});
|
|
5192
|
+
}
|
|
5193
|
+
succeeded(model) {
|
|
5194
|
+
if (model)
|
|
5195
|
+
this.entries.delete(model);
|
|
5196
|
+
}
|
|
5197
|
+
live() {
|
|
5198
|
+
const now = this.now();
|
|
5199
|
+
for (const [model, entry] of this.entries) {
|
|
5200
|
+
if (entry.until <= now)
|
|
5201
|
+
this.entries.delete(model);
|
|
5202
|
+
}
|
|
5203
|
+
return [...this.entries.values()];
|
|
5204
|
+
}
|
|
5205
|
+
startIndex(models, log) {
|
|
5206
|
+
const live = new Map(this.live().map((entry) => [entry.model, entry]));
|
|
5207
|
+
let start = models.findIndex((model) => !live.has(model));
|
|
5208
|
+
if (start < 0) {
|
|
5209
|
+
start = 0;
|
|
5210
|
+
for (let i = 1;i < models.length; i++) {
|
|
5211
|
+
if ((live.get(models[i])?.until ?? Infinity) < (live.get(models[start])?.until ?? Infinity))
|
|
5212
|
+
start = i;
|
|
5213
|
+
}
|
|
5214
|
+
}
|
|
5215
|
+
const logged = new Set;
|
|
5216
|
+
for (const model of models.slice(0, start)) {
|
|
5217
|
+
const entry = live.get(model);
|
|
5218
|
+
if (entry && !logged.has(model)) {
|
|
5219
|
+
log(`skipping ${model} until ${new Date(entry.until).toISOString()}: provider said to retry later`);
|
|
5220
|
+
logged.add(model);
|
|
5221
|
+
}
|
|
5222
|
+
}
|
|
5223
|
+
return start;
|
|
5224
|
+
}
|
|
5225
|
+
}
|
|
5226
|
+
function retryDelay(error, now, depth = 0) {
|
|
5227
|
+
if (!isRecord(error) || depth > 4)
|
|
5228
|
+
return;
|
|
5229
|
+
const data = typeof error.statusCode === "number" || typeof error.status === "number" ? error : isRecord(error.data) ? error.data : error;
|
|
5230
|
+
const status = data.statusCode ?? data.status;
|
|
5231
|
+
if (status === 412 || status === 429 || status === 503) {
|
|
5232
|
+
if (typeof data.retryAfterMs === "number")
|
|
5233
|
+
return data.retryAfterMs;
|
|
5234
|
+
const headers = data.responseHeaders;
|
|
5235
|
+
if (isRecord(headers)) {
|
|
5236
|
+
const value = Object.entries(headers).find(([name]) => name.toLowerCase() === "retry-after")?.[1];
|
|
5237
|
+
if (typeof value === "string") {
|
|
5238
|
+
const text = value.trim();
|
|
5239
|
+
if (/^\d+$/.test(text))
|
|
5240
|
+
return Number(text) * 1000;
|
|
5241
|
+
if (/^(?:(?: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(text))
|
|
5242
|
+
return Date.parse(text) - now;
|
|
5243
|
+
}
|
|
5244
|
+
}
|
|
5245
|
+
}
|
|
5246
|
+
return retryDelay(error.hostError ?? error.cause, now, depth + 1);
|
|
5247
|
+
}
|
|
5248
|
+
var hiddenModelCooldowns = new HiddenModelCooldowns;
|
|
5249
|
+
function selectHiddenModelStart(primary, fallbacks = [], note) {
|
|
5250
|
+
if (!primary)
|
|
5251
|
+
return { primary, fallbacks };
|
|
5252
|
+
const chain = [primary, ...fallbacks];
|
|
5253
|
+
const start = hiddenModelCooldowns.startIndex(chain.map((entry) => toModelEntry(entry)?.model ?? ""), note);
|
|
5254
|
+
return { primary: chain[start], fallbacks: chain.slice(start + 1) };
|
|
5255
|
+
}
|
|
5256
|
+
|
|
5204
5257
|
// src/shared/model-suggestion-retry.ts
|
|
5205
5258
|
var ABORT_CALL_TIMEOUT_MS = 3000;
|
|
5206
5259
|
function copyPromptArgs(args, body) {
|
|
@@ -5439,14 +5492,11 @@ function throwWithPromptFailure(legacyError, failedAttempts, args, timeoutMs, tr
|
|
|
5439
5492
|
const error = legacyError instanceof Error ? legacyError : new Error(extractMessage(legacyError));
|
|
5440
5493
|
const last = failedAttempts.at(-1);
|
|
5441
5494
|
const failureClass = last?.failureClass ?? "unknown";
|
|
5442
|
-
const
|
|
5443
|
-
if (quota && error !== quota && !error.message.includes(quota.message))
|
|
5444
|
-
error.message = `${quota.message}; ${error.message}`;
|
|
5445
|
-
const providerError = failureClass === "provider_error" || quota ? sanitizeDiagnosticText(`${quota ? `${quota.message}; ` : ""}${shortErr(last?.error ?? legacyError)}`).slice(0, 500) : null;
|
|
5495
|
+
const providerError = failureClass === "provider_error" ? sanitizeDiagnosticText(shortErr(last?.error ?? legacyError)).slice(0, 500) : null;
|
|
5446
5496
|
promptFailureDetails.set(error, {
|
|
5447
5497
|
failureClass,
|
|
5448
5498
|
modelAttempted: last?.attempt.label ?? null,
|
|
5449
|
-
modelsTried: failedAttempts.
|
|
5499
|
+
modelsTried: failedAttempts.map((failure) => failure.attempt.label),
|
|
5450
5500
|
providerError,
|
|
5451
5501
|
timeoutMs: failureClass === "provider_timeout" ? timeoutMs : null,
|
|
5452
5502
|
childSessionId: transport ? transport.childSessionId ?? null : args.path.id || null,
|
|
@@ -5463,6 +5513,8 @@ async function attemptOnce(client, args, timeoutMs, signal, callContext, label,
|
|
|
5463
5513
|
await promptWithTimeout(client, attemptArgs, timeoutMs, signal, transport, firstOutputTimeoutMs);
|
|
5464
5514
|
return;
|
|
5465
5515
|
} catch (error) {
|
|
5516
|
+
if (!signal?.aborted && !isPromptTimeoutError(error))
|
|
5517
|
+
hiddenModelCooldowns.record(label, error);
|
|
5466
5518
|
if (isNonRetryable(error, signal) || !allowModelSuggestions)
|
|
5467
5519
|
throw error;
|
|
5468
5520
|
const suggestion = parseModelSuggestion(error);
|
|
@@ -5503,7 +5555,19 @@ function createChainClock(options, timeoutMs) {
|
|
|
5503
5555
|
}
|
|
5504
5556
|
};
|
|
5505
5557
|
}
|
|
5558
|
+
function cooldownStart(args, options) {
|
|
5559
|
+
const model = args.body.model;
|
|
5560
|
+
if (!model)
|
|
5561
|
+
return { args, options };
|
|
5562
|
+
const selected = selectHiddenModelStart({ model: `${model.providerID}/${model.modelID}`, qualifier: args.body.variant }, options.fallbackModels, log2);
|
|
5563
|
+
const { variant: _variant, ...body } = args.body;
|
|
5564
|
+
return {
|
|
5565
|
+
args: copyPromptArgs(args, { ...body, ...modelBodyField(selected.primary) }),
|
|
5566
|
+
options: { ...options, fallbackModels: selected.fallbacks }
|
|
5567
|
+
};
|
|
5568
|
+
}
|
|
5506
5569
|
async function promptSyncWithModelSuggestionRetry(client, args, options = {}) {
|
|
5570
|
+
({ args, options } = cooldownStart(args, options));
|
|
5507
5571
|
const timeoutMs = options.timeoutMs ?? 300000;
|
|
5508
5572
|
const callContext = options.callContext ?? "subagent";
|
|
5509
5573
|
const fallbacks = options.fallbackModels ?? [];
|
|
@@ -5575,6 +5639,8 @@ async function attemptAndValidate(client, args, timeoutMs, signal, callContext,
|
|
|
5575
5639
|
try {
|
|
5576
5640
|
output = await raceWithSignal(options.fetchOutput(args, attempt), options.signal);
|
|
5577
5641
|
} catch (error) {
|
|
5642
|
+
if (!signal?.aborted && !isPromptTimeoutError(error))
|
|
5643
|
+
hiddenModelCooldowns.record(attempt.label, error);
|
|
5578
5644
|
throw {
|
|
5579
5645
|
error,
|
|
5580
5646
|
failureClass: classifyPromptFailure(error, "output", signal),
|
|
@@ -5586,7 +5652,7 @@ async function attemptAndValidate(client, args, timeoutMs, signal, callContext,
|
|
|
5586
5652
|
const text = extractLatestAssistantText(messages);
|
|
5587
5653
|
if (text) {
|
|
5588
5654
|
const failure = providerOutputFailureFromInvalidManifest(messages, text);
|
|
5589
|
-
if (failure
|
|
5655
|
+
if (failure && isAccountPoolQuotaNotice(text))
|
|
5590
5656
|
throw failure;
|
|
5591
5657
|
}
|
|
5592
5658
|
if (!extractLatestAssistantText(output)) {
|
|
@@ -5595,11 +5661,14 @@ async function attemptAndValidate(client, args, timeoutMs, signal, callContext,
|
|
|
5595
5661
|
const error = new Error(`Host recorded assistant error: ${describeAssistantError(assistantFailure.error)}`);
|
|
5596
5662
|
Object.assign(error, {
|
|
5597
5663
|
name: "DreamerProviderOutputFailureError",
|
|
5598
|
-
transient: true
|
|
5664
|
+
transient: true,
|
|
5665
|
+
hostError: assistantFailure.error
|
|
5599
5666
|
});
|
|
5667
|
+
hiddenModelCooldowns.record(attempt.label, assistantFailure.error);
|
|
5600
5668
|
throw error;
|
|
5601
5669
|
}
|
|
5602
5670
|
}
|
|
5671
|
+
hiddenModelCooldowns.succeeded(attempt.label);
|
|
5603
5672
|
const validated = await options.validateOutput(output, attempt);
|
|
5604
5673
|
return { output, validated, attempt };
|
|
5605
5674
|
} catch (error) {
|
|
@@ -5614,6 +5683,7 @@ async function attemptAndValidate(client, args, timeoutMs, signal, callContext,
|
|
|
5614
5683
|
}
|
|
5615
5684
|
}
|
|
5616
5685
|
async function promptSyncWithValidatedOutputRetry(client, args, options) {
|
|
5686
|
+
({ args, options } = cooldownStart(args, options));
|
|
5617
5687
|
const timeoutMs = options.timeoutMs ?? 300000;
|
|
5618
5688
|
const callContext = options.callContext ?? "subagent";
|
|
5619
5689
|
const fallbacks = options.fallbackModels ?? [];
|
|
@@ -5624,23 +5694,9 @@ async function promptSyncWithValidatedOutputRetry(client, args, options) {
|
|
|
5624
5694
|
const failedAttempts = [];
|
|
5625
5695
|
let firstError = null;
|
|
5626
5696
|
let lastError = null;
|
|
5627
|
-
const cooledPrimary = primaryQuotaFailure(explicitPrimaryLabel);
|
|
5628
5697
|
const clock = createChainClock(options, timeoutMs);
|
|
5629
5698
|
const primaryStartedAt = Date.now();
|
|
5630
5699
|
try {
|
|
5631
|
-
if (cooledPrimary)
|
|
5632
|
-
throw {
|
|
5633
|
-
error: cooledPrimary,
|
|
5634
|
-
failureClass: "provider_error",
|
|
5635
|
-
attempt: {
|
|
5636
|
-
label: explicitPrimaryLabel,
|
|
5637
|
-
attemptIndex: 0,
|
|
5638
|
-
isFallback: false,
|
|
5639
|
-
totalAttempts,
|
|
5640
|
-
model: baseBody.model,
|
|
5641
|
-
skipped: true
|
|
5642
|
-
}
|
|
5643
|
-
};
|
|
5644
5700
|
const budget = clock.budget(0);
|
|
5645
5701
|
return await attemptAndValidate(client, baseArgs, budget.timeoutMs, options.signal, callContext, {
|
|
5646
5702
|
label: explicitPrimaryLabel,
|
|
@@ -5655,19 +5711,13 @@ async function promptSyncWithValidatedOutputRetry(client, args, options) {
|
|
|
5655
5711
|
clock.settle(failure.error, primaryStartedAt);
|
|
5656
5712
|
firstError = failure.error;
|
|
5657
5713
|
lastError = failure.error;
|
|
5658
|
-
if (failure.error instanceof DreamerProviderOutputFailureError && failure.error.quotaResetAt !== undefined)
|
|
5659
|
-
failure.error.message = failure.error.message.replace(/^provider quota exhausted/, "primary quota exhausted");
|
|
5660
|
-
const quota = !cooledPrimary && rememberPrimaryQuota(explicitPrimaryLabel, failure.error);
|
|
5661
|
-
if (quota)
|
|
5662
|
-
log2(`[${callContext}] ${quota.message}; skipping ${explicitPrimaryLabel} for this run until reset`);
|
|
5663
5714
|
if (isNonRetryable(failure.error, options.signal)) {
|
|
5664
5715
|
throwWithPromptFailure(failure.error, failedAttempts, args, timeoutMs, options.transport);
|
|
5665
5716
|
}
|
|
5666
5717
|
if (fallbacks.length === 0) {
|
|
5667
5718
|
throwWithPromptFailure(failure.error, failedAttempts, args, timeoutMs, options.transport);
|
|
5668
5719
|
}
|
|
5669
|
-
|
|
5670
|
-
log2(`[${callContext}] primary (${explicitPrimaryLabel}) failed validation/prompt: ${shortErr(failure.error)}; ${fallbacks.length} fallback(s) configured, subject to remaining budget`);
|
|
5720
|
+
log2(`[${callContext}] primary (${explicitPrimaryLabel}) failed validation/prompt: ${shortErr(failure.error)}; ${fallbacks.length} fallback(s) configured, subject to remaining budget`);
|
|
5671
5721
|
}
|
|
5672
5722
|
for (let i = 0;i < fallbacks.length; i += 1) {
|
|
5673
5723
|
const fallback = toModelEntry(fallbacks[i]);
|
|
@@ -14521,7 +14571,7 @@ function createV1HiddenCompletionExecutor(client, db, directory) {
|
|
|
14521
14571
|
preferResponseOnMissingData: true
|
|
14522
14572
|
});
|
|
14523
14573
|
const assistantFailure = extractLatestAssistantFailure(messages);
|
|
14524
|
-
const hostError = hostErrors.get(handle.id);
|
|
14574
|
+
const hostError = assistantFailure?.error ?? hostErrors.get(handle.id);
|
|
14525
14575
|
if (assistantFailure || hostError !== undefined) {
|
|
14526
14576
|
const finish = assistantFailure?.finish ? ` (finish=${assistantFailure.finish})` : "";
|
|
14527
14577
|
const error = new Error(`Historian host recorded an assistant error${finish}: ${describeAssistantFailure(assistantFailure?.error ?? hostError)}`, hostError === undefined ? undefined : { cause: hostError });
|
|
@@ -14570,6 +14620,8 @@ function historianReasoningBudgetDiagnostic(outputTokens, tokens) {
|
|
|
14570
14620
|
return `historian ran out of output budget while reasoning (length-capped at ${outputTokens} tokens, no text${tokens ? `; ${formatRunTokenLog(tokens)}` : ""}) — set historian.maxTokens or route historian.model to a low-reasoning lane/variant`;
|
|
14571
14621
|
}
|
|
14572
14622
|
async function runValidatedHistorianPass(args) {
|
|
14623
|
+
const selected = selectHiddenModelStart(args.model, args.fallbackModels, (message) => sessionLog2(args.parentSessionId, message));
|
|
14624
|
+
args = { ...args, model: selected.primary, fallbackModels: selected.fallbacks };
|
|
14573
14625
|
const firstRun = await runHistorianPrompt({
|
|
14574
14626
|
...args,
|
|
14575
14627
|
dumpLabel: `${args.dumpLabelBase}-initial`,
|
|
@@ -14828,6 +14880,7 @@ async function runHistorianPrompt(args) {
|
|
|
14828
14880
|
}
|
|
14829
14881
|
}
|
|
14830
14882
|
completion = await executor.collect(handle, 50);
|
|
14883
|
+
hiddenModelCooldowns.succeeded(handle.attemptedModel ?? toModelEntry(modelOverride)?.model);
|
|
14831
14884
|
const lengthCapped = completion.lengthCapped;
|
|
14832
14885
|
const tokens = {
|
|
14833
14886
|
...runTokenLog(undefined, args.maxOutputTokens),
|
|
@@ -14864,6 +14917,7 @@ async function runHistorianPrompt(args) {
|
|
|
14864
14917
|
const dumpPath = dumpHistorianResponse(parentSessionId, sessionDirectory, dumpLabel ?? "historian-response", result);
|
|
14865
14918
|
return { ok: true, result, dumpPath, invocationId: invocationId ?? undefined };
|
|
14866
14919
|
} catch (modelError) {
|
|
14920
|
+
hiddenModelCooldowns.record(handle?.attemptedModel ?? toModelEntry(modelOverride)?.model, modelError);
|
|
14867
14921
|
const desc = describeError(modelError);
|
|
14868
14922
|
sessionLog2(parentSessionId, `historian prompt failed: ${desc.brief} promptLength=${prompt.length}${desc.stackHead ? ` stackHead="${desc.stackHead}"` : ""}`);
|
|
14869
14923
|
recordInvocation({
|
|
@@ -18941,4 +18995,4 @@ async function executeContextRecomp(deps, options = {}) {
|
|
|
18941
18995
|
return (await executeContextRecompWithResult(deps, options)).message;
|
|
18942
18996
|
}
|
|
18943
18997
|
|
|
18944
|
-
export { denyTaskRoutingToCallerAgents, buildHiddenAgentRegistrations, buildZenReadAgentRegistrations, buildHiddenAgentConfig, getMagicContextBuiltinCommands, formatConfigParseStatusLine, claimConfigParseFailuresOnce, isCommitRetentionPaused, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, resolveLegacyConfigSources, migrateMagicContextConfigLocations, getProtectedTokensTierOverrides, loadPluginConfigDetailed, historianRunConfig, dreamerRunConfig, pluginConfigReader, currentPluginConfigReader, withLiveDreamerOutputCap, createDreamerOutputCapSampler, COMPARTMENT_AGENT_SYSTEM_PROMPT, HISTORIAN_EDITOR_SYSTEM_PROMPT, COMPARTMENT_STRUCTURAL_SYSTEM_PROMPT, clampProducerAtomChars, producerInputTokenLimit, historianProducerReserve, producerPromptFailureReason, DREAMER_AGENT, DREAMER_RETROSPECTIVE_AGENT, DREAMER_PRIMER_INVESTIGATOR_AGENT, DREAMER_MEMORY_MAPPER_AGENT, DREAMER_CLASSIFIER_AGENT, DREAMER_DOCS_AGENT, DREAMER_REVIEWER_AGENT, createChildSessionWithFence, HiddenCompletionRefusal, DreamerProviderOutputFailureError,
|
|
18998
|
+
export { denyTaskRoutingToCallerAgents, buildHiddenAgentRegistrations, buildZenReadAgentRegistrations, buildHiddenAgentConfig, getMagicContextBuiltinCommands, formatConfigParseStatusLine, claimConfigParseFailuresOnce, isCommitRetentionPaused, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, resolveLegacyConfigSources, migrateMagicContextConfigLocations, getProtectedTokensTierOverrides, loadPluginConfigDetailed, historianRunConfig, dreamerRunConfig, pluginConfigReader, currentPluginConfigReader, withLiveDreamerOutputCap, createDreamerOutputCapSampler, COMPARTMENT_AGENT_SYSTEM_PROMPT, HISTORIAN_EDITOR_SYSTEM_PROMPT, COMPARTMENT_STRUCTURAL_SYSTEM_PROMPT, clampProducerAtomChars, producerInputTokenLimit, historianProducerReserve, producerPromptFailureReason, DREAMER_AGENT, DREAMER_RETROSPECTIVE_AGENT, DREAMER_PRIMER_INVESTIGATOR_AGENT, DREAMER_MEMORY_MAPPER_AGENT, DREAMER_CLASSIFIER_AGENT, DREAMER_DOCS_AGENT, DREAMER_REVIEWER_AGENT, createChildSessionWithFence, HiddenCompletionRefusal, DreamerProviderOutputFailureError, providerOutputFailureFromInvalidManifest, HIDDEN_HISTORIAN_AGENT, HIDDEN_DREAMER_AGENT, HIDDEN_CURATE_AGENT, hiddenAgentFor, hiddenToolLoop, HIDDEN_RUN_DISPOSED_REASON, noteChildOfDisposedInstance, hiddenChildPermissions, registerHiddenChildAgents, hiddenToolCallRefusal, HiddenAgentStepLimit, HiddenChildHook, extractLatestAssistantText, hasLengthCappedOutput, parseProviderModel, modelBodyField, toModelEntry, hiddenModelCooldowns, ModelProducedNoOutputError, noteModelActivityMonitored, noteModelOutputReceived, isPromptTimeoutError, getPromptFailureDetail, raceWithSignal, promptSyncWithValidatedOutputRetry, normalizeSDKResponse, annotateSubagentInvocationError, failedInvocationStatus, emptyTokenTotals, sumTokensFromChildMessages, recordChildInvocation, recordPromptSessionError, createPromptAsyncTransport, CTX_NOTE_LIGHT_DESCRIPTION, ACTIVE_TOOL_IDS, systemPromptFingerprint, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, setKeepSubagents, teardownChildSession, getCompartmentEvents, runTokenLog, formatRunTokenLog, buildMagicContextSection, getMuralIdentity, getMural, modelKeyAcceptsImages, resolveMuralWire, v2ToolDefinitionsHash, v2RequestToolsFingerprint, classifyRequestToolsChange, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getOpenCodeDbPath, compareOpenCodeMessagesByCanonicalOrder, startCompactionMarkerCandidatePreparation, removeMcOwnedCompactionMarkers, MARKER_SUMMARY_TEXT, markerUpdateDefinitelyDidNotCut, applyDeferredCompactionMarker, removeCompactionMarkerForSession, checkCompactionMarkerConsistency, extractM0Block, formatDate, TEMPORAL_MARKER_REPLAY_PATTERN, collectTemporalCandidates, injectTemporalMarkers, clearInjectionCache, getVisibleMemoryIds, selectHiddenMessagesAtCompactionSeam, prepareCompartmentInjection, renderCompartmentInjection, MaterializeContentionError, mustMaterialize, trimMemoriesToBudgetV2, renderMemoryBlockV2, stripMemoryMuralBlock, materializeM0, hydrateCachedM0Mural, resetPrefixTrimFallbackState, findHostCompactionWindow, capturePrefixTrimSourceOrder, prepareCachedM0M1Replay, headMessagesForSizing, rawTailAfterNewestCompartment, hasCompleteCachedM0M1, injectM0M1, resolveHiddenCompletionExecutor, createV1HiddenCompletionExecutor, readCoordinateGeneration, readCoordinateRebaseNotice, formatCoordinateRebaseNotice, rebaseSessionCoordinatesAsync, shouldWaitForNewHistorianHistory, EMPTY_READ_REPLY, noteTouchedAt, renderGlance, renderNotesById, formatWriteReply, observeNoteNudgeServe, onNoteTrigger, peekNoteNudgeText, markNoteNudgeDelivered, clearNoteNudgeTriggerAndCooldown, resetNoteNudgeCooldownOnly, clearNoteNudgeTriggerOnly, omitIncompleteFileTokenTotals, describeBoundaryDiagnostics, RECOVERY_NO_HEAD_LIMIT, deriveProtectedTailTokenTarget, selectPerRunCap, resolveOpenCodeProtectedTailBoundary, resolveWrapupProtectedTailBoundary, getRawHistoryEligibility, hasRunnableCompartmentWindow, recordHighPressureNoEligibleHead, noteTransformPassForExactOrdinalReads, runCompartmentAgent, snapRangeToCompartments, getActiveCompartmentRun, markActiveCompartmentRunPublished, registerActiveCompartmentRun, startCompartmentAgent, executeContextRecomp };
|
|
@@ -6880,6 +6880,7 @@ var BaseEmbeddingConfigSchema = object({
|
|
|
6880
6880
|
query_instruction: union([string(), literal(false)]).optional().describe("OpenAI-compatible query prefix override. A string is prepended verbatim to search queries; false disables the built-in model-family instruction. Qwen3-Embedding, gte-Qwen instruct, e5 instruct, and Nomic families have built-in recipes. Query-only changes do not re-embed stored content. User-level only; project values are ignored."),
|
|
6881
6881
|
document_prefix: string().optional().describe("OpenAI-compatible stored-document prefix override, prepended verbatim. Defaults to the model-family recipe (empty for Qwen3/gte/e5 instruct; 'search_document: ' for Nomic). Changing it changes stored vectors and triggers re-embedding. User-level only; project values are ignored."),
|
|
6882
6882
|
truncate: string().optional().describe("Optional truncate mode sent in the embedding request body (e.g. NVIDIA NIM accepts 'NONE' | 'START' | 'END'). Omitted from the request when unset."),
|
|
6883
|
+
dimensions: number().int().min(1).max(8192).optional().describe("Optional output width for Matryoshka embedding models (e.g. Qwen3-Embedding-8B accepts 768 | 1024 | 2048 | 4096; OpenAI text-embedding-3-* accept smaller widths than native). Sent as the OpenAI-compatible `dimensions` request field. Omitted from the request when unset, so the endpoint default applies. Changing it changes the produced vectors and folds into the embedding model identity, so switching widths re-embeds rather than mixing vector spaces. Not supported for the local provider, and ignored from project config like the other embedding fields (a repository cannot choose how private text is embedded)."),
|
|
6883
6884
|
max_input_tokens: number().int().positive().optional().describe("Optional maximum input tokens for chunk embeddings. Defaults conservatively to 512 when omitted."),
|
|
6884
6885
|
local_runtime: _enum(["auto", "native", "wasm"]).default("auto").describe("Local provider only: ONNX runtime selection. 'auto' uses native under Node and uses WASM under Bun versions before 1.4.0, where Bun's NAPI teardown race can panic on quit; native is restored automatically on Bun 1.4.0+. Inference runs in a dedicated worker after disabling POSIX telemetry in the native process environment. Compiled Bun hosts and hosts without a verified in-process opt-out use a subprocess instead. Windows native ONNX emits OS-controlled ETW diagnostics, not direct uploads. On Bun before 1.4.0, even explicit 'native' uses WASM because native worker teardown can crash the process. Set 'wasm' to avoid loading the native addon on newer hosts too."),
|
|
6885
6886
|
local_dtype: _enum([
|
|
@@ -6928,6 +6929,7 @@ var EmbeddingConfigSchema = BaseEmbeddingConfigSchema.transform((data) => {
|
|
|
6928
6929
|
...model ? { model } : {},
|
|
6929
6930
|
...endpoint ? { endpoint } : {},
|
|
6930
6931
|
...apiKey ? { api_key: apiKey } : {},
|
|
6932
|
+
...data.dimensions ? { dimensions: data.dimensions } : {},
|
|
6931
6933
|
...inputType ? { input_type: inputType } : {},
|
|
6932
6934
|
...queryInputType ? { query_input_type: queryInputType } : {},
|
|
6933
6935
|
...data.query_instruction !== undefined ? { query_instruction: data.query_instruction } : {},
|
|
@@ -6954,6 +6956,7 @@ var EmbeddingConfigSchema = BaseEmbeddingConfigSchema.transform((data) => {
|
|
|
6954
6956
|
provider: "openai-compatible",
|
|
6955
6957
|
model: data.model?.trim() ?? "",
|
|
6956
6958
|
endpoint: data.endpoint?.trim() ?? "",
|
|
6959
|
+
...data.dimensions ? { dimensions: data.dimensions } : {},
|
|
6957
6960
|
...apiKey ? { api_key: apiKey } : {},
|
|
6958
6961
|
...inputType ? { input_type: inputType } : {},
|
|
6959
6962
|
...queryInputType ? { query_input_type: queryInputType } : {},
|
|
@@ -61,7 +61,7 @@ import {
|
|
|
61
61
|
serializeProcessedImageMarkers,
|
|
62
62
|
getPendingPiCompactionMarkerState,
|
|
63
63
|
logPiCompactionMarkerClear
|
|
64
|
-
} from "./index-
|
|
64
|
+
} from "./index-07rp6xcn.js";
|
|
65
65
|
import {
|
|
66
66
|
stripTagPrefix,
|
|
67
67
|
isRecord,
|
|
@@ -667,6 +667,57 @@ import { createHash as createHash6 } from "node:crypto";
|
|
|
667
667
|
import { createHash as createHash4 } from "node:crypto";
|
|
668
668
|
|
|
669
669
|
// src/shared/provider-response-completion.ts
|
|
670
|
+
var SERVER_FALLBACK_USAGE_SIGNATURE_PREFIX = "cortexkit-server-fallback-usage-v1:";
|
|
671
|
+
var SERVER_FALLBACK_SIGNATURE_PREFIX = "cortexkit-server-fallback-v1:";
|
|
672
|
+
function parseServerFallbackInputTokens(json) {
|
|
673
|
+
try {
|
|
674
|
+
const payload = JSON.parse(json);
|
|
675
|
+
if (!isRecord(payload) || !Array.isArray(payload.iterations))
|
|
676
|
+
return;
|
|
677
|
+
let last;
|
|
678
|
+
for (const entry of payload.iterations) {
|
|
679
|
+
if (isRecord(entry) && entry.type === "fallback_message")
|
|
680
|
+
last = entry;
|
|
681
|
+
}
|
|
682
|
+
if (!isRecord(last))
|
|
683
|
+
return;
|
|
684
|
+
const counts = [
|
|
685
|
+
last.input_tokens,
|
|
686
|
+
last.cache_read_input_tokens ?? 0,
|
|
687
|
+
last.cache_creation_input_tokens ?? 0
|
|
688
|
+
];
|
|
689
|
+
if (!counts.every((count) => typeof count === "number" && Number.isFinite(count) && count >= 0))
|
|
690
|
+
return;
|
|
691
|
+
const inputTokens = counts.reduce((sum, count) => sum + Number(count), 0);
|
|
692
|
+
return Number.isFinite(inputTokens) ? inputTokens : undefined;
|
|
693
|
+
} catch {
|
|
694
|
+
return;
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
function readServerFallbackUsage(content) {
|
|
698
|
+
if (!Array.isArray(content))
|
|
699
|
+
return;
|
|
700
|
+
let boundary = false;
|
|
701
|
+
let invalidUsage = false;
|
|
702
|
+
for (const part of content) {
|
|
703
|
+
if (!isRecord(part) || part.type !== "reasoning")
|
|
704
|
+
continue;
|
|
705
|
+
for (const location of [part.native, part.state]) {
|
|
706
|
+
if (!isRecord(location) || typeof location.signature !== "string")
|
|
707
|
+
continue;
|
|
708
|
+
const signature = location.signature;
|
|
709
|
+
if (signature.startsWith(SERVER_FALLBACK_USAGE_SIGNATURE_PREFIX)) {
|
|
710
|
+
const inputTokens = parseServerFallbackInputTokens(signature.slice(SERVER_FALLBACK_USAGE_SIGNATURE_PREFIX.length));
|
|
711
|
+
if (inputTokens !== undefined)
|
|
712
|
+
return { kind: "usage", inputTokens };
|
|
713
|
+
invalidUsage = true;
|
|
714
|
+
} else if (signature.startsWith(SERVER_FALLBACK_SIGNATURE_PREFIX)) {
|
|
715
|
+
boundary = true;
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
return boundary || invalidUsage ? { kind: "boundary", invalidUsage } : undefined;
|
|
720
|
+
}
|
|
670
721
|
function providerResponseFailed(input) {
|
|
671
722
|
if (input.error !== undefined && input.error !== null && input.error !== "")
|
|
672
723
|
return true;
|
|
@@ -4593,4 +4644,4 @@ var ERROR_CLASSES = new Set([
|
|
|
4593
4644
|
"permission_denied",
|
|
4594
4645
|
"unknown"
|
|
4595
4646
|
]);
|
|
4596
|
-
export { advanceSessionActivity, observeSessionActivity, backfillSessionActivity, COMPARTMENT_LEASE_RENEWAL_MS, getCompartmentLeaseBlocker, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLease, releaseCompartmentLeaseBestEffort, isCompartmentLeaseHeld, isNoContentCompartment, queueM0Mutation, getMaxM0MutationId, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getCompartmentsByEndMessageId, appendCompartments, buildCompartmentBlock, saveRecompStagingPass, getRecompStaging, clearRecompStaging, getRecompPartialRange, setRecompPartialRange, escapeXmlAttr, escapeXmlContent, getUncoveredCompartmentEndsThrough, isPartialCompartmentEnd, readProjectDocsCanonical, providerResponseFailed, isSuccessfulProviderCompletion, LkgRecoveryFenceError, lkgServedArrayDigest, hasCleanLkgRecoveryFence, dirtyLkgRecoveryRevision, ownsLkgDirtyFence, invalidateCleanLkgRecoveryFence, prepareLkgCaptureFence, certifyCommittedLkgCapture, markLkgRecoveryDirty, rememberUnpublishedAutoSearchNoHint, getUnpublishedAutoSearchNoHint, forgetUnpublishedAutoSearchNoHint, registerAutoSearchWork, cancelAutoSearchWork, readSessionMeta, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, markSessionCleanupPending, retryPendingSessionCleanups, retryPendingRustSessionCleanupsForProject, clearSession, requestPendingMaterialization, pendingMaterializationOrigin, hasPendingMaterializationOrigin, clearPendingMaterialization, clearPendingMaterializationOrigin, recordSystemPromptForRequest, recordHeldHeadForRequest, bindSystemPromptResponse, isHeldHeadForRequest, deferDeliveredSystemRefresh, retirePendingSystemPromptDelivery, lkgProviderInputTotal, beginV2LkgRequest, claimLkgRequestIdentity, currentLkgRequestIdentity, noteCapturedLkgRequest, noteLkgProviderResponse, measuredLkgPrefix, clearLkgMeasuredRequest, saveLkgSlotToDb, clearPersistedLkgSlotStrict, loadPersistedLkgSlot, drainStaleLkgSlots, createDbLkgPersistence, resolveLkgModelKeys, createLkgEntryProjector, captureLkgSlot, validateAnthropicReasoningRuns, validateLkgSeam, replayLkg, coldStartRawServedIndex, coldStartUncapturedReplay, noteUncertifiedNormalLkg, hasProcessLocalLkgProof, lkgDirtyRevision, rememberLkgDirtyRevision, readPersistedLkgUntaggedInputIds, persistLkgUntaggedInputIds, noteLkgRecoveryPrefix, readLkgRecoveryPrefix, noteLkgHealthyPrefix, lkgRecoveryReplayUnproven, lkgRecoveryEntryUnproven, lkgInputIdentity, registerLkgPersistence, beginLkgPass, visitMessageContentFields, contentSnapshotValue, messageContentFields, signatureForFields, exactReusablePrefix, incrementalLkgContentDigests, lkgSlotRejection, captureSlot, getInMemorySlot, getSlot, forgetInMemorySlot, dropSlot, noteEntry, getLkgSlotHeapStats, TOOL_SWEEP_SCOPED_MARKER, useScopedToolSweep, createPreAdoptionToolSweepResolver, copySessionStateForClone, externalHistorianFailureReason, recordHistorianRun, summarizeImportance, tallyFactsByCategory, MEMORY_VISIBILITY_MUTATION_CATEGORY, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, replaceSourceContent, getSourceContents, recordSubagentInvocation, getLatestHistorianInvocationId };
|
|
4647
|
+
export { advanceSessionActivity, observeSessionActivity, backfillSessionActivity, COMPARTMENT_LEASE_RENEWAL_MS, getCompartmentLeaseBlocker, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLease, releaseCompartmentLeaseBestEffort, isCompartmentLeaseHeld, isNoContentCompartment, queueM0Mutation, getMaxM0MutationId, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getCompartmentsByEndMessageId, appendCompartments, buildCompartmentBlock, saveRecompStagingPass, getRecompStaging, clearRecompStaging, getRecompPartialRange, setRecompPartialRange, escapeXmlAttr, escapeXmlContent, getUncoveredCompartmentEndsThrough, isPartialCompartmentEnd, readProjectDocsCanonical, readServerFallbackUsage, providerResponseFailed, isSuccessfulProviderCompletion, LkgRecoveryFenceError, lkgServedArrayDigest, hasCleanLkgRecoveryFence, dirtyLkgRecoveryRevision, ownsLkgDirtyFence, invalidateCleanLkgRecoveryFence, prepareLkgCaptureFence, certifyCommittedLkgCapture, markLkgRecoveryDirty, rememberUnpublishedAutoSearchNoHint, getUnpublishedAutoSearchNoHint, forgetUnpublishedAutoSearchNoHint, registerAutoSearchWork, cancelAutoSearchWork, readSessionMeta, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, markSessionCleanupPending, retryPendingSessionCleanups, retryPendingRustSessionCleanupsForProject, clearSession, requestPendingMaterialization, pendingMaterializationOrigin, hasPendingMaterializationOrigin, clearPendingMaterialization, clearPendingMaterializationOrigin, recordSystemPromptForRequest, recordHeldHeadForRequest, bindSystemPromptResponse, isHeldHeadForRequest, deferDeliveredSystemRefresh, retirePendingSystemPromptDelivery, lkgProviderInputTotal, beginV2LkgRequest, claimLkgRequestIdentity, currentLkgRequestIdentity, noteCapturedLkgRequest, noteLkgProviderResponse, measuredLkgPrefix, clearLkgMeasuredRequest, saveLkgSlotToDb, clearPersistedLkgSlotStrict, loadPersistedLkgSlot, drainStaleLkgSlots, createDbLkgPersistence, resolveLkgModelKeys, createLkgEntryProjector, captureLkgSlot, validateAnthropicReasoningRuns, validateLkgSeam, replayLkg, coldStartRawServedIndex, coldStartUncapturedReplay, noteUncertifiedNormalLkg, hasProcessLocalLkgProof, lkgDirtyRevision, rememberLkgDirtyRevision, readPersistedLkgUntaggedInputIds, persistLkgUntaggedInputIds, noteLkgRecoveryPrefix, readLkgRecoveryPrefix, noteLkgHealthyPrefix, lkgRecoveryReplayUnproven, lkgRecoveryEntryUnproven, lkgInputIdentity, registerLkgPersistence, beginLkgPass, visitMessageContentFields, contentSnapshotValue, messageContentFields, signatureForFields, exactReusablePrefix, incrementalLkgContentDigests, lkgSlotRejection, captureSlot, getInMemorySlot, getSlot, forgetInMemorySlot, dropSlot, noteEntry, getLkgSlotHeapStats, TOOL_SWEEP_SCOPED_MARKER, useScopedToolSweep, createPreAdoptionToolSweepResolver, copySessionStateForClone, externalHistorianFailureReason, recordHistorianRun, summarizeImportance, tallyFactsByCategory, MEMORY_VISIBILITY_MUTATION_CATEGORY, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, replaceSourceContent, getSourceContents, recordSubagentInvocation, getLatestHistorianInvocationId };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
DEFAULT_LOCAL_EMBEDDING_MODEL
|
|
3
|
-
} from "./index-
|
|
3
|
+
} from "./index-jjy5a5w0.js";
|
|
4
4
|
import {
|
|
5
5
|
getSynapseLaneIdentity
|
|
6
6
|
} from "./index-hsyczpn7.js";
|
|
@@ -543,6 +543,7 @@ function getEmbeddingProviderIdentity(config) {
|
|
|
543
543
|
throw new Error("Unknown embedding provider");
|
|
544
544
|
}
|
|
545
545
|
const truncate = config.provider === "openai-compatible" ? config.truncate?.trim() : undefined;
|
|
546
|
+
const dimensions = config.provider === "openai-compatible" ? config.dimensions : undefined;
|
|
546
547
|
const documentPrefix = config.provider === "openai-compatible" ? resolveEmbeddingTextPrefixes(config.model, config.query_instruction, config.document_prefix).documentPrefix : "";
|
|
547
548
|
const localDtype = config.provider === "local" && config.local_dtype && config.local_dtype !== "fp32" ? config.local_dtype : undefined;
|
|
548
549
|
const localPooling = config.provider === "local" ? getCachedLocalEmbeddingPooling(config.model?.trim() || DEFAULT_LOCAL_EMBEDDING_MODEL) : null;
|
|
@@ -554,7 +555,8 @@ function getEmbeddingProviderIdentity(config) {
|
|
|
554
555
|
apiKeyPresent: Boolean(config.api_key?.trim()),
|
|
555
556
|
inputType: config.input_type?.trim() || "",
|
|
556
557
|
...documentPrefix ? { documentPrefix } : {},
|
|
557
|
-
...truncate ? { truncate } : {}
|
|
558
|
+
...truncate ? { truncate } : {},
|
|
559
|
+
...dimensions ? { dimensions } : {}
|
|
558
560
|
} : {
|
|
559
561
|
provider: "local",
|
|
560
562
|
model: config.model?.trim() || DEFAULT_LOCAL_EMBEDDING_MODEL,
|
|
@@ -8,7 +8,7 @@ import {
|
|
|
8
8
|
releaseCompartmentLeaseBestEffort,
|
|
9
9
|
getCompartments,
|
|
10
10
|
getLastCompartmentEndMessage
|
|
11
|
-
} from "./index-
|
|
11
|
+
} from "./index-n0twfvah.js";
|
|
12
12
|
import {
|
|
13
13
|
inRootAsyncContext2
|
|
14
14
|
} from "./index-gzy5w8ya.js";
|
|
@@ -20,7 +20,7 @@ import {
|
|
|
20
20
|
getHistorianFailureState,
|
|
21
21
|
clearEmergencyRecovery,
|
|
22
22
|
prepareRawSessionOrdinals2
|
|
23
|
-
} from "./index-
|
|
23
|
+
} from "./index-07rp6xcn.js";
|
|
24
24
|
import {
|
|
25
25
|
pushNotification2
|
|
26
26
|
} from "./index-x8a7jmkh.js";
|
|
@@ -32,14 +32,14 @@ import {
|
|
|
32
32
|
getActiveCompartmentRun,
|
|
33
33
|
markActiveCompartmentRunPublished,
|
|
34
34
|
registerActiveCompartmentRun
|
|
35
|
-
} from "./index-
|
|
35
|
+
} from "./index-h8g08nxs.js";
|
|
36
36
|
import {
|
|
37
37
|
sendStatusNotification2
|
|
38
38
|
} from "./index-r9agn061.js";
|
|
39
39
|
import {
|
|
40
40
|
setRecompStarting2,
|
|
41
41
|
setRecompTerminal2
|
|
42
|
-
} from "./index-
|
|
42
|
+
} from "./index-97bjd14c.js";
|
|
43
43
|
|
|
44
44
|
// src/hooks/magic-context/wrapup-orchestrator.ts
|
|
45
45
|
import * as crypto from "node:crypto";
|