@remnic/core 10.0.122 → 10.0.123
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/access-admin-ops-surface.js +84 -83
- package/dist/access-cli.js +84 -83
- package/dist/access-cli.js.map +1 -1
- package/dist/access-extraction-force-flush.js +84 -83
- package/dist/access-http-briefing.js +84 -83
- package/dist/access-http-query.js +84 -83
- package/dist/access-http.js +84 -83
- package/dist/access-identity-continuity-surface.js +84 -83
- package/dist/access-lcm-surface.js +84 -83
- package/dist/access-mcp.js +84 -83
- package/dist/access-observe-write-category.js +8 -8
- package/dist/access-observe-write-surface.js +84 -83
- package/dist/access-offline-manifest.js +5 -5
- package/dist/access-operations-batch.js +84 -83
- package/dist/access-operations.js +84 -83
- package/dist/access-recall-concurrency.js +84 -83
- package/dist/access-recall-response.js +84 -83
- package/dist/access-recall-surface.js +84 -83
- package/dist/access-schema.js +7 -7
- package/dist/access-service.js +84 -83
- package/dist/active-recall.js +13 -13
- package/dist/adapters/index.js +4 -4
- package/dist/adapters/registry.js +2 -2
- package/dist/briefing.js +8 -8
- package/dist/calibration.js +3 -3
- package/dist/{capsule-crypto-GWVG7LGC.js → capsule-crypto-7FJQINUR.js} +2 -2
- package/dist/causal-consolidation.js +9 -9
- package/dist/{chunk-SEOJHETP.js → chunk-2NGTY22Z.js} +7 -6
- package/dist/{chunk-SEOJHETP.js.map → chunk-2NGTY22Z.js.map} +1 -1
- package/dist/{chunk-OWHERGF2.js → chunk-2NLLXCJG.js} +2 -2
- package/dist/{chunk-NLYLOLQW.js → chunk-3B7EF4MP.js} +3 -3
- package/dist/{chunk-HOYYVQN2.js → chunk-3OEZA5TR.js} +2 -2
- package/dist/{chunk-UCD7NQKZ.js → chunk-3S7VJJTG.js} +2 -2
- package/dist/{chunk-B2RECSSR.js → chunk-53VLXNAO.js} +2 -2
- package/dist/{chunk-5RONA5FF.js → chunk-7DFJ4JX2.js} +4 -4
- package/dist/{chunk-BUKK5SWA.js → chunk-7LCGFUMB.js} +4 -4
- package/dist/{chunk-5PCUUGLT.js → chunk-7P72BY4F.js} +2 -2
- package/dist/{chunk-FAAWURSH.js → chunk-AC6F3ADA.js} +2 -2
- package/dist/{chunk-6GQFMR6A.js → chunk-AM5ZNSUK.js} +2 -2
- package/dist/{chunk-744WDDFX.js → chunk-B5LNHYSG.js} +2 -2
- package/dist/{chunk-OJPCASE5.js → chunk-CHZMU6HA.js} +2 -2
- package/dist/{chunk-DWUKVXMU.js → chunk-CKUDZMC3.js} +2 -2
- package/dist/{chunk-HBNMJ26J.js → chunk-EGLJALMG.js} +5 -5
- package/dist/{chunk-P5KJOXWH.js → chunk-EOJF66EQ.js} +2 -2
- package/dist/{chunk-CPWYYRJ2.js → chunk-GFZRBHLH.js} +2 -2
- package/dist/{chunk-IFYWNSSU.js → chunk-GSRRD7ZJ.js} +2 -2
- package/dist/{chunk-4RASUAN3.js → chunk-HXFIILGF.js} +4 -4
- package/dist/{chunk-L5PM7B3I.js → chunk-IFFCHE3O.js} +1 -1
- package/dist/{chunk-L5PM7B3I.js.map → chunk-IFFCHE3O.js.map} +1 -1
- package/dist/{chunk-4VAUQBFJ.js → chunk-IWULSPDY.js} +3 -3
- package/dist/{chunk-C5PEYREE.js → chunk-JLUOSKCU.js} +2 -2
- package/dist/{chunk-A6KNCOHQ.js → chunk-JWFBN2LM.js} +2 -2
- package/dist/{chunk-VPARMYWA.js → chunk-KBO44266.js} +5 -5
- package/dist/{chunk-QOWLC5P6.js → chunk-KU3K2WNM.js} +10 -10
- package/dist/{chunk-RDCKC5MI.js → chunk-LP326T2D.js} +3 -3
- package/dist/{chunk-WRTLTOHA.js → chunk-MFKWQJRQ.js} +2 -2
- package/dist/{chunk-IARHAE4J.js → chunk-NMQF4CAA.js} +2 -2
- package/dist/{chunk-FGI6GJA5.js → chunk-PJIJA3MK.js} +3 -3
- package/dist/{chunk-N72KBIZ2.js → chunk-Q5Q3IHPP.js} +16 -10
- package/dist/chunk-Q5Q3IHPP.js.map +1 -0
- package/dist/{chunk-Z6EMZNKI.js → chunk-QQ4GEUCX.js} +2 -2
- package/dist/{chunk-7POUQFKI.js → chunk-R6DTQYSK.js} +3 -3
- package/dist/{chunk-XYZXO6VO.js → chunk-SC76A2ZT.js} +5 -5
- package/dist/{chunk-W2B25HUU.js → chunk-SMCMHPFY.js} +2 -2
- package/dist/{chunk-CLF4TBUS.js → chunk-T4Q57NRP.js} +2 -2
- package/dist/{chunk-WQUGCOKF.js → chunk-TFA6HPOA.js} +4 -4
- package/dist/{chunk-ZZ5S2SFB.js → chunk-TS3ILFYM.js} +3 -3
- package/dist/{chunk-TNPUVR6U.js → chunk-TVMPYREI.js} +8 -8
- package/dist/{chunk-OYHEVL4A.js → chunk-UDUJIKFQ.js} +3 -3
- package/dist/{chunk-P7FC7N5Z.js → chunk-UJAOI56X.js} +2 -2
- package/dist/{chunk-K4P2MUVI.js → chunk-UTY3HL57.js} +2 -2
- package/dist/chunk-V24YLFJW.js +72 -0
- package/dist/chunk-V24YLFJW.js.map +1 -0
- package/dist/{chunk-X6QQNDIW.js → chunk-VIWACB5U.js} +4 -4
- package/dist/{chunk-EHJI3L7T.js → chunk-VKS2WV2M.js} +2 -2
- package/dist/{chunk-SH4R3FVM.js → chunk-VYX7W6EB.js} +2 -2
- package/dist/{chunk-ZMIRHXJE.js → chunk-WGYORDDM.js} +120 -120
- package/dist/{chunk-FA7SLQ5X.js → chunk-WUQH7BDU.js} +1 -1
- package/dist/chunk-WUQH7BDU.js.map +1 -0
- package/dist/{chunk-CNCN5UN4.js → chunk-WY7QVTBD.js} +2 -2
- package/dist/{chunk-5JDLDYST.js → chunk-X33UXMUS.js} +3 -3
- package/dist/{chunk-UVYI6VIX.js → chunk-X7Y7WX73.js} +1 -1
- package/dist/{chunk-SED6JMID.js → chunk-XN3F3V5H.js} +7 -7
- package/dist/{chunk-EMMJQASU.js → chunk-Y6RTVJJK.js} +2 -2
- package/dist/{chunk-YGFHQT3E.js → chunk-Y7LKZQ4T.js} +2 -2
- package/dist/{chunk-ZDE54VUB.js → chunk-Z7GJNZTY.js} +2 -2
- package/dist/{chunk-SVP57SAR.js → chunk-ZBK3UBMB.js} +4 -4
- package/dist/{chunk-ZQLJNZZ7.js → chunk-ZGEBQW2J.js} +4 -4
- package/dist/cli.js +84 -83
- package/dist/coding/export-okf-codegraph.js +7 -7
- package/dist/compounding/engine.js +9 -9
- package/dist/config.js +13 -13
- package/dist/connectors/codex-materialize-runner.js +8 -8
- package/dist/connectors/index.js +8 -8
- package/dist/convergence-refresh.js +10 -10
- package/dist/conversation-index/backend.js +2 -2
- package/dist/corpus-watermark.js +10 -10
- package/dist/deep-recall-http-glue.js +8 -8
- package/dist/deep-recall.js +2 -2
- package/dist/entity-retrieval.js +8 -8
- package/dist/explicit-capture.js +84 -83
- package/dist/extraction-error-classification.d.ts +2 -0
- package/dist/extraction-error-classification.d.ts.map +1 -1
- package/dist/extraction-error-classification.js +1 -1
- package/dist/extraction-reply-diagnostic.d.ts +31 -0
- package/dist/extraction-reply-diagnostic.d.ts.map +1 -0
- package/dist/extraction-reply-diagnostic.js +13 -0
- package/dist/extraction-reply-diagnostic.js.map +1 -0
- package/dist/extraction.d.ts +0 -1
- package/dist/extraction.d.ts.map +1 -1
- package/dist/extraction.js +15 -14
- package/dist/{first-start-migration-FILJH3RO.js → first-start-migration-U4K2P7KF.js} +4 -4
- package/dist/harmonic-retrieval.js +8 -8
- package/dist/index.js +112 -111
- package/dist/lcm/index.js +3 -3
- package/dist/local-llm-helpers.d.ts +1 -0
- package/dist/local-llm-helpers.d.ts.map +1 -1
- package/dist/local-llm-helpers.js +1 -1
- package/dist/local-llm.js +3 -3
- package/dist/location/index.js +9 -9
- package/dist/maintenance/memory-governance.js +8 -8
- package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +8 -8
- package/dist/maintenance/rebuild-memory-projection-runner.js +10 -10
- package/dist/maintenance/rebuild-memory-projection.js +9 -9
- package/dist/namespaces/migrate.js +9 -9
- package/dist/namespaces/search.js +5 -5
- package/dist/namespaces/storage.js +8 -8
- package/dist/offline-sync-changeset-generations.js +3 -3
- package/dist/offline-sync-embedding-generation.js +2 -2
- package/dist/offline-sync-snapshot-stream.js +5 -5
- package/dist/offline-sync.js +7 -7
- package/dist/operator-doctor-corpus.js +11 -11
- package/dist/operator-toolkit.js +20 -20
- package/dist/orchestration/backlog-scheduler.js +85 -84
- package/dist/orchestration/backlog-scheduler.js.map +1 -1
- package/dist/orchestration/buffer-drain-runner.js +85 -84
- package/dist/orchestration/maintenance.js +19 -19
- package/dist/orchestrator.js +84 -83
- package/dist/recall-navigation.js +84 -83
- package/dist/resume-bundles.js +16 -16
- package/dist/search/factory.js +4 -4
- package/dist/search/index.js +6 -6
- package/dist/semantic-consolidation.js +9 -9
- package/dist/semantic-rule-promotion.js +8 -8
- package/dist/semantic-rule-verifier.js +8 -8
- package/dist/source-agent-qualifier.js +8 -8
- package/dist/standup/build.js +8 -8
- package/dist/storage.js +7 -7
- package/dist/summarizer.js +4 -4
- package/dist/support-passport/index.js +4 -4
- package/dist/transcript.js +2 -2
- package/dist/transfer/backup.js +2 -2
- package/dist/transfer/capsule-export.js +2 -2
- package/dist/transfer/capsule-import.js +2 -2
- package/dist/transfer/export-okf.js +8 -8
- package/dist/verified-recall.js +8 -8
- package/dist/who-knows-cli.js +9 -9
- package/dist/who-knows.js +8 -8
- package/package.json +2 -2
- package/src/extraction-error-classification.ts +2 -0
- package/src/extraction-reply-diagnostic-wiring.test.ts +87 -0
- package/src/extraction-reply-diagnostic.test.ts +130 -0
- package/src/extraction-reply-diagnostic.ts +105 -0
- package/src/extraction.ts +7 -16
- package/src/local-llm-headers-timeout.test.ts +24 -1
- package/src/local-llm-helpers.ts +1 -1
- package/src/local-llm.ts +3 -3
- package/dist/chunk-FA7SLQ5X.js.map +0 -1
- package/dist/chunk-N72KBIZ2.js.map +0 -1
- /package/dist/{capsule-crypto-GWVG7LGC.js.map → capsule-crypto-7FJQINUR.js.map} +0 -0
- /package/dist/{chunk-OWHERGF2.js.map → chunk-2NLLXCJG.js.map} +0 -0
- /package/dist/{chunk-NLYLOLQW.js.map → chunk-3B7EF4MP.js.map} +0 -0
- /package/dist/{chunk-HOYYVQN2.js.map → chunk-3OEZA5TR.js.map} +0 -0
- /package/dist/{chunk-UCD7NQKZ.js.map → chunk-3S7VJJTG.js.map} +0 -0
- /package/dist/{chunk-B2RECSSR.js.map → chunk-53VLXNAO.js.map} +0 -0
- /package/dist/{chunk-5RONA5FF.js.map → chunk-7DFJ4JX2.js.map} +0 -0
- /package/dist/{chunk-BUKK5SWA.js.map → chunk-7LCGFUMB.js.map} +0 -0
- /package/dist/{chunk-5PCUUGLT.js.map → chunk-7P72BY4F.js.map} +0 -0
- /package/dist/{chunk-FAAWURSH.js.map → chunk-AC6F3ADA.js.map} +0 -0
- /package/dist/{chunk-6GQFMR6A.js.map → chunk-AM5ZNSUK.js.map} +0 -0
- /package/dist/{chunk-744WDDFX.js.map → chunk-B5LNHYSG.js.map} +0 -0
- /package/dist/{chunk-OJPCASE5.js.map → chunk-CHZMU6HA.js.map} +0 -0
- /package/dist/{chunk-DWUKVXMU.js.map → chunk-CKUDZMC3.js.map} +0 -0
- /package/dist/{chunk-HBNMJ26J.js.map → chunk-EGLJALMG.js.map} +0 -0
- /package/dist/{chunk-P5KJOXWH.js.map → chunk-EOJF66EQ.js.map} +0 -0
- /package/dist/{chunk-CPWYYRJ2.js.map → chunk-GFZRBHLH.js.map} +0 -0
- /package/dist/{chunk-IFYWNSSU.js.map → chunk-GSRRD7ZJ.js.map} +0 -0
- /package/dist/{chunk-4RASUAN3.js.map → chunk-HXFIILGF.js.map} +0 -0
- /package/dist/{chunk-4VAUQBFJ.js.map → chunk-IWULSPDY.js.map} +0 -0
- /package/dist/{chunk-C5PEYREE.js.map → chunk-JLUOSKCU.js.map} +0 -0
- /package/dist/{chunk-A6KNCOHQ.js.map → chunk-JWFBN2LM.js.map} +0 -0
- /package/dist/{chunk-VPARMYWA.js.map → chunk-KBO44266.js.map} +0 -0
- /package/dist/{chunk-QOWLC5P6.js.map → chunk-KU3K2WNM.js.map} +0 -0
- /package/dist/{chunk-RDCKC5MI.js.map → chunk-LP326T2D.js.map} +0 -0
- /package/dist/{chunk-WRTLTOHA.js.map → chunk-MFKWQJRQ.js.map} +0 -0
- /package/dist/{chunk-IARHAE4J.js.map → chunk-NMQF4CAA.js.map} +0 -0
- /package/dist/{chunk-FGI6GJA5.js.map → chunk-PJIJA3MK.js.map} +0 -0
- /package/dist/{chunk-Z6EMZNKI.js.map → chunk-QQ4GEUCX.js.map} +0 -0
- /package/dist/{chunk-7POUQFKI.js.map → chunk-R6DTQYSK.js.map} +0 -0
- /package/dist/{chunk-XYZXO6VO.js.map → chunk-SC76A2ZT.js.map} +0 -0
- /package/dist/{chunk-W2B25HUU.js.map → chunk-SMCMHPFY.js.map} +0 -0
- /package/dist/{chunk-CLF4TBUS.js.map → chunk-T4Q57NRP.js.map} +0 -0
- /package/dist/{chunk-WQUGCOKF.js.map → chunk-TFA6HPOA.js.map} +0 -0
- /package/dist/{chunk-ZZ5S2SFB.js.map → chunk-TS3ILFYM.js.map} +0 -0
- /package/dist/{chunk-TNPUVR6U.js.map → chunk-TVMPYREI.js.map} +0 -0
- /package/dist/{chunk-OYHEVL4A.js.map → chunk-UDUJIKFQ.js.map} +0 -0
- /package/dist/{chunk-P7FC7N5Z.js.map → chunk-UJAOI56X.js.map} +0 -0
- /package/dist/{chunk-K4P2MUVI.js.map → chunk-UTY3HL57.js.map} +0 -0
- /package/dist/{chunk-X6QQNDIW.js.map → chunk-VIWACB5U.js.map} +0 -0
- /package/dist/{chunk-EHJI3L7T.js.map → chunk-VKS2WV2M.js.map} +0 -0
- /package/dist/{chunk-SH4R3FVM.js.map → chunk-VYX7W6EB.js.map} +0 -0
- /package/dist/{chunk-ZMIRHXJE.js.map → chunk-WGYORDDM.js.map} +0 -0
- /package/dist/{chunk-CNCN5UN4.js.map → chunk-WY7QVTBD.js.map} +0 -0
- /package/dist/{chunk-5JDLDYST.js.map → chunk-X33UXMUS.js.map} +0 -0
- /package/dist/{chunk-UVYI6VIX.js.map → chunk-X7Y7WX73.js.map} +0 -0
- /package/dist/{chunk-SED6JMID.js.map → chunk-XN3F3V5H.js.map} +0 -0
- /package/dist/{chunk-EMMJQASU.js.map → chunk-Y6RTVJJK.js.map} +0 -0
- /package/dist/{chunk-YGFHQT3E.js.map → chunk-Y7LKZQ4T.js.map} +0 -0
- /package/dist/{chunk-ZDE54VUB.js.map → chunk-Z7GJNZTY.js.map} +0 -0
- /package/dist/{chunk-SVP57SAR.js.map → chunk-ZBK3UBMB.js.map} +0 -0
- /package/dist/{chunk-ZQLJNZZ7.js.map → chunk-ZGEBQW2J.js.map} +0 -0
- /package/dist/{first-start-migration-FILJH3RO.js.map → first-start-migration-U4K2P7KF.js.map} +0 -0
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
|
|
4
|
+
import {
|
|
5
|
+
buildUnusableReplyDiagnostic,
|
|
6
|
+
formatUnusableReplyDiagnostic,
|
|
7
|
+
} from "./extraction-reply-diagnostic.js";
|
|
8
|
+
|
|
9
|
+
const SECRET = "SECRETVALUE-4821";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Builds and renders the diagnostic for `reply`, then asserts no sentinel
|
|
13
|
+
* substring appears anywhere in either form; `allowedKeys` lists the key names
|
|
14
|
+
* expected to survive, and any other extracted key fails the assert.
|
|
15
|
+
*/
|
|
16
|
+
function assertNoContent(reply: string, sentinels: string[], allowedKeys: string[] = []): void {
|
|
17
|
+
const diag = buildUnusableReplyDiagnostic(reply, undefined, 0);
|
|
18
|
+
const rendered = `${JSON.stringify(diag)} ${formatUnusableReplyDiagnostic(diag)}`;
|
|
19
|
+
for (const sentinel of sentinels) assert.equal(rendered.includes(sentinel), false, `leaked ${sentinel}`);
|
|
20
|
+
assert.deepEqual(diag.topLevelKeys.filter((k) => !allowedKeys.includes(k)), []);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** The most common failure mode: prose with no JSON. Pins that the whole reply is exactly one candidate and every rendered field is content-free. */
|
|
24
|
+
test("commentary: no braces, nothing parses (the whole reply is the one candidate the extractor tries)", () => {
|
|
25
|
+
const reply = `I read the conversation about ${SECRET} and have no durable facts to report.`;
|
|
26
|
+
assert.deepEqual(buildUnusableReplyDiagnostic(reply, "stop", 0), {
|
|
27
|
+
replyChars: reply.length,
|
|
28
|
+
finishReason: "stop",
|
|
29
|
+
startsWithBrace: false,
|
|
30
|
+
jsonCandidates: 1,
|
|
31
|
+
parsedAnyJson: false,
|
|
32
|
+
unrecognizedPayloads: 0,
|
|
33
|
+
topLevelKeys: [],
|
|
34
|
+
partialFacts: 0,
|
|
35
|
+
});
|
|
36
|
+
assertNoContent(reply, [SECRET, "durable facts", "conversation"]);
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
/** A refusal is textually indistinguishable from commentary; only the client-supplied finish reason lets an operator tell them apart. */
|
|
40
|
+
test("refusal: no JSON, finish reason carried", () => {
|
|
41
|
+
const reply = `I'm sorry, I can't help with ${SECRET}.`;
|
|
42
|
+
const diag = buildUnusableReplyDiagnostic(reply, "content_filter", 0);
|
|
43
|
+
assert.equal(diag.finishReason, "content_filter");
|
|
44
|
+
assert.equal(diag.parsedAnyJson, false);
|
|
45
|
+
assert.equal(diag.startsWithBrace, false);
|
|
46
|
+
assertNoContent(reply, [SECRET, "sorry"]);
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
/** Key names may be logged but values must never be: hostile key shapes are filtered and values are never read at all. */
|
|
50
|
+
test("valid JSON of the wrong shape: parsed, shape rejected, safe keys kept, hostile keys omitted", () => {
|
|
51
|
+
const long = "k".repeat(33);
|
|
52
|
+
const reply = JSON.stringify({ summary: SECRET, "user@example.com": 1, [long]: 2, "has space": 3, result_set: [SECRET] });
|
|
53
|
+
const diag = buildUnusableReplyDiagnostic(reply, "stop", 0);
|
|
54
|
+
assert.equal(diag.startsWithBrace, true);
|
|
55
|
+
assert.equal(diag.parsedAnyJson, true);
|
|
56
|
+
assert.ok(diag.unrecognizedPayloads >= 1);
|
|
57
|
+
assert.deepEqual(diag.topLevelKeys, ["summary", "result_set"]);
|
|
58
|
+
assertNoContent(reply, [SECRET, "user@example.com", long, "has space"], ["summary", "result_set"]);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
/** Bounds the worst case so a model echoing many keys cannot bloat the warn line; keys come from the first parse so repeated runs stay stable. */
|
|
62
|
+
test("top-level keys are capped at 8 and come from the first parsed candidate", () => {
|
|
63
|
+
const first = Object.fromEntries(Array.from({ length: 12 }, (_, i) => [`key${i}`, i]));
|
|
64
|
+
const reply = `${JSON.stringify(first)}\n${JSON.stringify({ other: 1 })}`;
|
|
65
|
+
const diag = buildUnusableReplyDiagnostic(reply, undefined, 0);
|
|
66
|
+
assert.deepEqual(diag.topLevelKeys, ["key0", "key1", "key2", "key3", "key4", "key5", "key6", "key7"]);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
/** Pins the parser treating a top-level array as keyless: index keys like "0" must not surface as if they were payload names. */
|
|
70
|
+
test("a JSON array parses but exposes no keys", () => {
|
|
71
|
+
const diag = buildUnusableReplyDiagnostic(`[{"a":"${SECRET}"}]`, undefined, 0);
|
|
72
|
+
assert.equal(diag.parsedAnyJson, true);
|
|
73
|
+
assert.deepEqual(diag.topLevelKeys, []);
|
|
74
|
+
assert.equal(diag.startsWithBrace, false);
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
/** The cut-off case from the issue: brace at position zero but nothing parseable, with partialFacts echoing what upstream salvage already recovered. */
|
|
78
|
+
test("truncated JSON: starts with a brace, never parses", () => {
|
|
79
|
+
const reply = `{"facts":[{"content":"${SECRET} is the`;
|
|
80
|
+
const diag = buildUnusableReplyDiagnostic(reply, "length", 2);
|
|
81
|
+
assert.equal(diag.startsWithBrace, true);
|
|
82
|
+
assert.equal(diag.parsedAnyJson, false);
|
|
83
|
+
assert.equal(diag.finishReason, "length");
|
|
84
|
+
assert.equal(diag.partialFacts, 2);
|
|
85
|
+
assert.deepEqual(diag.topLevelKeys, []);
|
|
86
|
+
assertNoContent(reply, [SECRET, "is the"]);
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
/** Zero state: the HTTP-refusal site builds this from an empty reply, so the line reads "no candidates tried" without implying a malformed one. */
|
|
90
|
+
test("empty reply", () => {
|
|
91
|
+
assert.deepEqual(buildUnusableReplyDiagnostic("", undefined, 0), {
|
|
92
|
+
replyChars: 0,
|
|
93
|
+
finishReason: undefined,
|
|
94
|
+
startsWithBrace: false,
|
|
95
|
+
jsonCandidates: 0,
|
|
96
|
+
parsedAnyJson: false,
|
|
97
|
+
unrecognizedPayloads: 0,
|
|
98
|
+
topLevelKeys: [],
|
|
99
|
+
partialFacts: 0,
|
|
100
|
+
});
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
/** Fenced JSON parses through the fence but starts with a backtick, so startsWithBrace stays false — the signature of "JSON arrived, wrapped". */
|
|
104
|
+
test("fenced json block of the wrong shape: parsed through the fence, content absent", () => {
|
|
105
|
+
const reply = "```json\n" + JSON.stringify({ note: SECRET }) + "\n```";
|
|
106
|
+
const diag = buildUnusableReplyDiagnostic(reply, "stop", 0);
|
|
107
|
+
assert.equal(diag.startsWithBrace, false);
|
|
108
|
+
assert.equal(diag.parsedAnyJson, true);
|
|
109
|
+
assert.ok(diag.unrecognizedPayloads >= 1);
|
|
110
|
+
assert.deepEqual(diag.topLevelKeys, ["note"]);
|
|
111
|
+
assertNoContent(reply, [SECRET], ["note"]);
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
/** finish_reason is untrusted wire data from the local server; only identifier-shaped values survive validation, everything else is omitted rather than logged. */
|
|
115
|
+
test("finish reason that is not identifier-shaped is omitted", () => {
|
|
116
|
+
for (const hostile of ["x y", "a".repeat(33), `${SECRET}!`]) {
|
|
117
|
+
assert.equal(buildUnusableReplyDiagnostic("hello", hostile, 0).finishReason, undefined);
|
|
118
|
+
}
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
/** Pins the exact rendering so log greps and parsers survive refactors of either module. */
|
|
122
|
+
test("rendered line has a stable greppable shape", () => {
|
|
123
|
+
const line = formatUnusableReplyDiagnostic(
|
|
124
|
+
buildUnusableReplyDiagnostic('{"answer":"x"}', "stop", 0),
|
|
125
|
+
);
|
|
126
|
+
assert.equal(
|
|
127
|
+
line,
|
|
128
|
+
"extractWithLocalLlm: unusable local reply replyChars=14 finishReason=stop startsWithBrace=true jsonCandidates=1 parsedAnyJson=true unrecognizedPayloads=1 topLevelKeys=answer partialFacts=0",
|
|
129
|
+
);
|
|
130
|
+
});
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
|
|
3
|
+
import { extractJsonCandidates } from "./json-extract.js";
|
|
4
|
+
|
|
5
|
+
const PAYLOAD_KEYS = ["facts", "entities", "profileUpdates", "questions", "relationships", "identityReflection"];
|
|
6
|
+
const SAFE_NAME = z.string().regex(/^[A-Za-z_][A-Za-z0-9_]{0,31}$/);
|
|
7
|
+
const JsonObject = z.record(z.string(), z.unknown());
|
|
8
|
+
const MAX_TOP_LEVEL_KEYS = 8;
|
|
9
|
+
|
|
10
|
+
export type JsonValue = z.infer<ReturnType<typeof z.json>>;
|
|
11
|
+
|
|
12
|
+
/** True when a parsed JSON value is an object carrying at least one extraction-result key. */
|
|
13
|
+
export function looksLikeExtractionResultPayload(parsed: JsonValue): boolean {
|
|
14
|
+
const object = JsonObject.safeParse(parsed);
|
|
15
|
+
return object.success && PAYLOAD_KEYS.some((key) => key in object.data);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Identifier-shaped top-level key names of a parsed object, in insertion order,
|
|
20
|
+
* capped at MAX_TOP_LEVEL_KEYS. Keys failing the identifier shape (emails,
|
|
21
|
+
* long strings, anything that could carry or point at content) are dropped, so
|
|
22
|
+
* the array is safe to log by construction.
|
|
23
|
+
*/
|
|
24
|
+
function safeTopLevelKeys(parsed: JsonValue): string[] {
|
|
25
|
+
const object = JsonObject.safeParse(parsed);
|
|
26
|
+
const keys: string[] = [];
|
|
27
|
+
if (!object.success) return keys;
|
|
28
|
+
for (const key of Object.keys(object.data)) {
|
|
29
|
+
if (keys.length === MAX_TOP_LEVEL_KEYS) break;
|
|
30
|
+
if (SAFE_NAME.safeParse(key).success) keys.push(key);
|
|
31
|
+
}
|
|
32
|
+
return keys;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* What an unusable local-LLM extraction reply looked like, without any of its
|
|
37
|
+
* content (the reply may hold user data). Every field is a count, a boolean, or
|
|
38
|
+
* an identifier-shaped name (`finishReason`, JSON key names); anything else is omitted.
|
|
39
|
+
*/
|
|
40
|
+
export interface UnusableReplyDiagnostic {
|
|
41
|
+
replyChars: number;
|
|
42
|
+
finishReason: string | undefined;
|
|
43
|
+
startsWithBrace: boolean;
|
|
44
|
+
/** Candidates the extractor tried; the whole reply counts as one when non-empty. */
|
|
45
|
+
jsonCandidates: number;
|
|
46
|
+
parsedAnyJson: boolean;
|
|
47
|
+
/** Candidates that parsed as JSON but carry no extraction-result key. */
|
|
48
|
+
unrecognizedPayloads: number;
|
|
49
|
+
/** From the first candidate that parsed. */
|
|
50
|
+
topLevelKeys: string[];
|
|
51
|
+
partialFacts: number;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** `content` is the trimmed reply; `finishReason` is whatever the client recorded (validated here). */
|
|
55
|
+
export function buildUnusableReplyDiagnostic(
|
|
56
|
+
content: string,
|
|
57
|
+
finishReason: string | undefined,
|
|
58
|
+
partialFacts: number,
|
|
59
|
+
): UnusableReplyDiagnostic {
|
|
60
|
+
const candidates = extractJsonCandidates(content);
|
|
61
|
+
let parsedAnyJson = false;
|
|
62
|
+
let unrecognizedPayloads = 0;
|
|
63
|
+
let topLevelKeys: string[] = [];
|
|
64
|
+
for (const candidate of candidates) {
|
|
65
|
+
let parsed: JsonValue;
|
|
66
|
+
try {
|
|
67
|
+
parsed = JSON.parse(candidate);
|
|
68
|
+
} catch {
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
if (!parsedAnyJson) topLevelKeys = safeTopLevelKeys(parsed);
|
|
72
|
+
parsedAnyJson = true;
|
|
73
|
+
if (!looksLikeExtractionResultPayload(parsed)) unrecognizedPayloads++;
|
|
74
|
+
}
|
|
75
|
+
const reason = SAFE_NAME.safeParse(finishReason);
|
|
76
|
+
return {
|
|
77
|
+
replyChars: content.length,
|
|
78
|
+
finishReason: reason.success ? reason.data : undefined,
|
|
79
|
+
startsWithBrace: content.startsWith("{"),
|
|
80
|
+
jsonCandidates: candidates.length,
|
|
81
|
+
parsedAnyJson,
|
|
82
|
+
unrecognizedPayloads,
|
|
83
|
+
topLevelKeys,
|
|
84
|
+
partialFacts,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Render one greppable warn line from a diagnostic. Only reads fields already
|
|
90
|
+
* reduced to counts, booleans, and validated names, so reply content cannot
|
|
91
|
+
* reach the log through formatting.
|
|
92
|
+
*/
|
|
93
|
+
export function formatUnusableReplyDiagnostic(d: UnusableReplyDiagnostic): string {
|
|
94
|
+
return [
|
|
95
|
+
"extractWithLocalLlm: unusable local reply",
|
|
96
|
+
`replyChars=${d.replyChars}`,
|
|
97
|
+
`finishReason=${d.finishReason ?? "none"}`,
|
|
98
|
+
`startsWithBrace=${d.startsWithBrace}`,
|
|
99
|
+
`jsonCandidates=${d.jsonCandidates}`,
|
|
100
|
+
`parsedAnyJson=${d.parsedAnyJson}`,
|
|
101
|
+
`unrecognizedPayloads=${d.unrecognizedPayloads}`,
|
|
102
|
+
`topLevelKeys=${d.topLevelKeys.join(",")}`,
|
|
103
|
+
`partialFacts=${d.partialFacts}`,
|
|
104
|
+
].join(" ");
|
|
105
|
+
}
|
package/src/extraction.ts
CHANGED
|
@@ -39,6 +39,7 @@ import { applyGroundingWithConnector, headerConnector, renderExtractionConversat
|
|
|
39
39
|
import { isMemoryCategory } from "./write-envelope.js";
|
|
40
40
|
export { classifyExtractionThrownError, classifyFallbackParseFailure, formatExtractionParseFailureLog } from "./extraction-error-classification.js";
|
|
41
41
|
import { LocalLlmRejectedError, classifyExtractionThrownError, classifyFallbackParseFailure, formatExtractionParseFailureLog, localRejectionStatus, type LocalFailureDiag } from "./extraction-error-classification.js";
|
|
42
|
+
import { buildUnusableReplyDiagnostic, formatUnusableReplyDiagnostic, looksLikeExtractionResultPayload } from "./extraction-reply-diagnostic.js";
|
|
42
43
|
import { AMBIENT_CAPTURE_PROMPT_SECTION_COMPACT, clampAmbientCaptureConfidence } from "./ambient-provenance.js";
|
|
43
44
|
import {
|
|
44
45
|
CONSOLIDATION_RESPONSE_SCHEMA,
|
|
@@ -275,20 +276,6 @@ export class ExtractionEngine {
|
|
|
275
276
|
|| (result.relationships?.length ?? 0) > 0;
|
|
276
277
|
}
|
|
277
278
|
|
|
278
|
-
private looksLikeExtractionResultPayload(parsed: any): boolean {
|
|
279
|
-
return !!parsed &&
|
|
280
|
-
typeof parsed === "object" &&
|
|
281
|
-
!Array.isArray(parsed) &&
|
|
282
|
-
(
|
|
283
|
-
"facts" in parsed ||
|
|
284
|
-
"entities" in parsed ||
|
|
285
|
-
"profileUpdates" in parsed ||
|
|
286
|
-
"questions" in parsed ||
|
|
287
|
-
"relationships" in parsed ||
|
|
288
|
-
"identityReflection" in parsed
|
|
289
|
-
);
|
|
290
|
-
}
|
|
291
|
-
|
|
292
279
|
private normalizeExtractionResultPayload(parsed: any): ExtractionResult {
|
|
293
280
|
const entities: ExtractedEntityResult[] = Array.isArray(parsed?.entities)
|
|
294
281
|
? parsed.entities
|
|
@@ -1515,7 +1502,10 @@ ${truncatedConversation}`;
|
|
|
1515
1502
|
);
|
|
1516
1503
|
if (!response?.content) {
|
|
1517
1504
|
const rejected = localRejectionStatus(failureDiag);
|
|
1518
|
-
if (rejected !== undefined)
|
|
1505
|
+
if (rejected !== undefined) {
|
|
1506
|
+
log.warn(formatUnusableReplyDiagnostic(buildUnusableReplyDiagnostic("", failureDiag.finishReason, 0)));
|
|
1507
|
+
throw new LocalLlmRejectedError(rejected); // the endpoint is up and refuses this input
|
|
1508
|
+
}
|
|
1519
1509
|
log.debug("extractWithLocalLlm: chatCompletion returned null or empty content");
|
|
1520
1510
|
return null;
|
|
1521
1511
|
}
|
|
@@ -1528,7 +1518,7 @@ ${truncatedConversation}`;
|
|
|
1528
1518
|
try {
|
|
1529
1519
|
log.debug(`extractWithLocalLlm: attempting JSON parse, candidate length=${candidate.length}`);
|
|
1530
1520
|
const parsed = JSON.parse(candidate);
|
|
1531
|
-
if (!
|
|
1521
|
+
if (!looksLikeExtractionResultPayload(parsed)) {
|
|
1532
1522
|
continue;
|
|
1533
1523
|
}
|
|
1534
1524
|
|
|
@@ -1551,6 +1541,7 @@ ${truncatedConversation}`;
|
|
|
1551
1541
|
log.debug(`extractWithLocalLlm: extracted ${partial.facts.length} partial facts from truncated JSON`);
|
|
1552
1542
|
return partial;
|
|
1553
1543
|
}
|
|
1544
|
+
log.warn(formatUnusableReplyDiagnostic(buildUnusableReplyDiagnostic(content, failureDiag.finishReason, partial.facts.length)));
|
|
1554
1545
|
throw new LocalLlmRejectedError(); // the endpoint answered and nothing in the answer is usable
|
|
1555
1546
|
}
|
|
1556
1547
|
|
|
@@ -12,7 +12,7 @@ import {
|
|
|
12
12
|
} from "undici";
|
|
13
13
|
|
|
14
14
|
import { LocalLlmClient } from "./local-llm.js";
|
|
15
|
-
import { probeFetch } from "./local-llm-helpers.js";
|
|
15
|
+
import { probeFetch, type LocalLlmChatCompletionOptions } from "./local-llm-helpers.js";
|
|
16
16
|
import { classifyAnalysisProviderError } from "./activity/timeline/analysis-provider.js";
|
|
17
17
|
import { ChatTransport } from "./local-llm-transport.js";
|
|
18
18
|
import { initLogger, resetLogger } from "./logger.js";
|
|
@@ -214,6 +214,29 @@ test("chat completion passes an undici dispatcher to fetch", async () => {
|
|
|
214
214
|
}
|
|
215
215
|
});
|
|
216
216
|
|
|
217
|
+
/** finish_reason must land on the failureDiag object the caller handed in, not only on the return value — the extraction diagnostic reads it there after a null or unusable reply. */
|
|
218
|
+
test("failureDiag carries the completion's finish_reason (issue #3387)", { concurrency: false }, async () => {
|
|
219
|
+
const original = globalThis.fetch;
|
|
220
|
+
// SAFETY: the stub satisfies the only fetch call this client makes.
|
|
221
|
+
globalThis.fetch = (async () =>
|
|
222
|
+
new Response(JSON.stringify({ choices: [{ message: { content: "partial" }, finish_reason: "length" }] }), {
|
|
223
|
+
status: 200,
|
|
224
|
+
headers: { "content-type": "application/json" },
|
|
225
|
+
})) as typeof fetch;
|
|
226
|
+
const client = new LocalLlmClient(createConfig());
|
|
227
|
+
|
|
228
|
+
try {
|
|
229
|
+
primeClient(client);
|
|
230
|
+
const options: LocalLlmChatCompletionOptions = { failureDiag: {} };
|
|
231
|
+
const result = await client.chatCompletion([{ role: "user", content: "test" }], options);
|
|
232
|
+
assert.equal(result?.content, "partial");
|
|
233
|
+
assert.equal(options.failureDiag?.finishReason, "length");
|
|
234
|
+
} finally {
|
|
235
|
+
globalThis.fetch = original;
|
|
236
|
+
await dispatcherOf(client).close();
|
|
237
|
+
}
|
|
238
|
+
});
|
|
239
|
+
|
|
217
240
|
test("runtime honors a per-request dispatcher (regression canary for #2148)", async () => {
|
|
218
241
|
// The fix assumes fetch applies `init.dispatcher`. If a future runtime
|
|
219
242
|
// silently ignores it, the 300s cap returns with no other signal — so
|
package/src/local-llm-helpers.ts
CHANGED
|
@@ -23,7 +23,7 @@ export interface LocalLlmChatCompletionOptions {
|
|
|
23
23
|
* callers can classify it (e.g. HTTP 429 → rate-limited) in memory
|
|
24
24
|
* instead of seeing only null. Never logged.
|
|
25
25
|
*/
|
|
26
|
-
failureDiag?: { lastError?: unknown };
|
|
26
|
+
failureDiag?: { lastError?: unknown; finishReason?: string };
|
|
27
27
|
}
|
|
28
28
|
|
|
29
29
|
export interface LocalLlmChatCompletionResult {
|
package/src/local-llm.ts
CHANGED
|
@@ -1151,10 +1151,9 @@ export class LocalLlmClient {
|
|
|
1151
1151
|
this.consecutive400s = 0;
|
|
1152
1152
|
this.nativeSchemaGate.recordSuccess(requestBody, requestModel);
|
|
1153
1153
|
|
|
1154
|
+
// SAFETY: OpenAI-compatible wire format; every field is optional and read defensively below.
|
|
1154
1155
|
const data = JSON.parse(responseBody) as {
|
|
1155
|
-
choices?: Array<{
|
|
1156
|
-
message?: { content?: string; reasoning_content?: string };
|
|
1157
|
-
}>;
|
|
1156
|
+
choices?: Array<{ message?: { content?: string; reasoning_content?: string }; finish_reason?: string }>;
|
|
1158
1157
|
usage?: {
|
|
1159
1158
|
prompt_tokens?: number;
|
|
1160
1159
|
completion_tokens?: number;
|
|
@@ -1170,6 +1169,7 @@ export class LocalLlmClient {
|
|
|
1170
1169
|
// `reasoning_content` and leave `content` empty. Fall back to
|
|
1171
1170
|
// reasoning_content so engram still gets a usable result.
|
|
1172
1171
|
const msg = data.choices?.[0]?.message;
|
|
1172
|
+
if (options.failureDiag) options.failureDiag.finishReason = data.choices?.[0]?.finish_reason;
|
|
1173
1173
|
const content = msg?.content || msg?.reasoning_content || "";
|
|
1174
1174
|
if (!content) {
|
|
1175
1175
|
log.warn(`local LLM returned empty content.${options.redactProviderErrors ? "" : ` choices=${JSON.stringify(data.choices)?.slice(0, 200)}`}`);
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/local-llm-helpers.ts"],"sourcesContent":["import type { ResponseFormatJSONSchema } from \"openai/resources/shared\";\nimport type { Agent } from \"undici\";\nimport { log } from \"./logger.js\";\nimport { directProbeDispatcher } from \"./local-llm-transport.js\";\nimport type { LocalLlmRequestPriority } from \"./local-llm.js\";\n\nexport interface LocalLlmChatCompletionOptions {\n temperature?: number;\n maxTokens?: number;\n responseFormat?: { type: string } | ResponseFormatJSONSchema;\n timeoutMs?: number;\n operation?: string;\n forceDisableThinking?: boolean;\n disableThinking?: boolean;\n priority?: LocalLlmRequestPriority;\n signal?: AbortSignal;\n redactProviderErrors?: boolean;\n /** Per-request model; defaults to config.localLlmModel. */\n model?: string;\n /**\n * Optional out-box for the terminal failure cause (issue #2891): on a\n * failed request the client records the last provider error here so\n * callers can classify it (e.g. HTTP 429 → rate-limited) in memory\n * instead of seeing only null. Never logged.\n */\n failureDiag?: { lastError?: unknown };\n}\n\nexport interface LocalLlmChatCompletionResult {\n content: string;\n usage?: { promptTokens: number; completionTokens: number; totalTokens: number };\n}\nexport function isAbortError(err: unknown): boolean {\n if (!err || typeof err !== \"object\") return false;\n const maybe = err as { name?: string; message?: string };\n return (\n maybe.name === \"AbortError\" ||\n maybe.message === \"This operation was aborted\" ||\n maybe.message === \"The operation was aborted\"\n );\n}\n\n/** Caller signal combined with a client-wide shutdown signal, so a daemon\n * stop aborts in-flight requests and retry loops at once — even for\n * callers that pass no signal of their own. */\nexport function combineClientAbortSignals(\n caller: AbortSignal | undefined,\n shutdown: AbortSignal | undefined,\n): AbortSignal | undefined {\n if (shutdown === undefined) return caller;\n if (caller === undefined) return shutdown;\n return AbortSignal.any([caller, shutdown]);\n}\n\nexport function waitForRetryBackoff(backoffMs: number, signal?: AbortSignal): Promise<boolean> {\n return new Promise((resolve) => {\n let settled = false;\n let timer: NodeJS.Timeout | undefined;\n const onAbort = (): void => {\n if (settled) return;\n settled = true;\n if (timer) clearTimeout(timer);\n signal?.removeEventListener(\"abort\", onAbort);\n resolve(false);\n };\n const onTimer = (): void => {\n if (settled) return;\n settled = true;\n signal?.removeEventListener(\"abort\", onAbort);\n resolve(true);\n };\n timer = setTimeout(onTimer, backoffMs);\n if (signal) {\n if (signal.aborted) onAbort();\n else signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n });\n}\n\nexport function normalizeBackendTripReason(reason: string): string {\n const cleaned = reason.replace(/\\s+/g, \" \").replace(/^[-:–—\\s]+/, \"\").trim();\n if (!cleaned) return \"unknown local backend failure\";\n return cleaned.length > 160 ? `${cleaned.slice(0, 157)}...` : cleaned;\n}\n\nexport function extractNonRecoverableBackendReason(reason: string): string | null {\n const match = reason.match(\n /Failed to load model|Library not loaded|different Team IDs|code signature|llm_engine_mlx_amphibian/i,\n );\n return match?.[0] ?? null;\n}\n\nexport function extractNonRecoverableBackendReasonFromErrorText(errorText: string): string | null {\n const directReason = extractNonRecoverableBackendReason(errorText);\n if (directReason) return directReason;\n try {\n const parsed = JSON.parse(errorText) as { error?: { message?: string } };\n return extractNonRecoverableBackendReason(parsed?.error?.message ?? \"\");\n } catch {\n return null;\n }\n}\n\n/**\n * Flatten a fetch rejection into one line, including the `cause` undici hides\n * the real reason behind (`fetch failed` alone says nothing).\n */\nexport function describeFetchFailure(err: unknown): string {\n const name = err instanceof Error ? err.name : \"\";\n const message = err instanceof Error ? err.message : String(err);\n const cause: unknown = err instanceof Error ? (err as Error & { cause?: unknown }).cause : undefined;\n const causeText = cause instanceof Error\n ? ` (cause: ${cause.name}: ${cause.message}${\n typeof (cause as Error & { code?: unknown }).code === \"string\"\n ? ` [${String((cause as Error & { code?: unknown }).code)}]`\n : \"\"\n })`\n : cause === undefined\n ? \"\"\n : ` (cause: ${String(cause)})`;\n return `${name ? `${name}: ` : \"\"}${message}${causeText}`;\n}\n\n/**\n * What to record when every availability probe failed.\n *\n * A probe that TIMED OUT is not evidence the backend is down: the budget is a\n * fixed 2s and a busy event loop can burn it before the socket is scheduled,\n * so the backend looks dead while it answers other callers in single-digit ms.\n * Caching that verdict took extraction offline for a whole health-check\n * interval at a time (issue #2210), so a timeout leaves availability UNKNOWN —\n * this call fails, the next one re-probes instead of reading a stale false.\n *\n * A backend that ANSWERED and said no is a real verdict and stays cached, or\n * the daemon re-probes a known-bad endpoint on every request.\n */\nexport function resolveUnavailableVerdict(args: {\n baseUrl: string;\n sawAbortedProbe: boolean;\n wasAvailable: boolean | null;\n}): { cacheVerdict: boolean; warning: string | null } {\n if (args.sawAbortedProbe) {\n return {\n cacheVerdict: false,\n warning:\n `local LLM availability probe timed out at ${args.baseUrl} (event loop busy?); treating availability as ` +\n \"unknown and re-probing on the next request rather than marking the backend down\",\n };\n }\n return {\n cacheVerdict: true,\n // Surfaced at warn, not debug: extraction stops silently when this flips,\n // and the daemon emits no debug at all unless configured for it.\n warning: args.wasAvailable !== false ? `local LLM became unavailable at ${args.baseUrl}` : null,\n };\n}\n\nexport interface ProbeFetchResult {\n ok: boolean;\n data: unknown;\n status: number | null;\n /** The probe hit its own budget rather than getting an answer. */\n aborted?: boolean;\n}\n\n/**\n * One health-probe request.\n *\n * Every failure is logged with its cause: a transport error and a 404 both\n * returned `ok: false` with nothing recorded, so an unreachable backend was\n * indistinguishable from a wrong path and an availability failure had no\n * diagnosable reason at all (§22, issue #2210).\n */\nexport async function probeFetch(\n url: string,\n options: { timeoutMs: number; headers: Record<string, string>; signal?: AbortSignal },\n): Promise<ProbeFetchResult> {\n const controller = new AbortController();\n const requestSignal = options.signal\n ? AbortSignal.any([options.signal, controller.signal])\n : controller.signal;\n const timeout = setTimeout(() => controller.abort(), options.timeoutMs);\n try {\n const init: RequestInit & { dispatcher?: Agent } = { signal: requestSignal, headers: options.headers };\n const dispatcher = directProbeDispatcher();\n if (dispatcher) init.dispatcher = dispatcher;\n const response = await fetch(url, init);\n clearTimeout(timeout);\n if (!response.ok) {\n log.debug(`local LLM probe: ${url} returned HTTP ${response.status}`);\n return { ok: false, data: null, status: response.status };\n }\n const contentType = response.headers.get(\"content-type\");\n const data = contentType?.includes(\"application/json\") ? await response.json() : await response.text();\n return { ok: true, data, status: response.status };\n } catch (err) {\n clearTimeout(timeout);\n const aborted = isAbortError(err);\n log.debug(\n `local LLM probe: ${url} ${aborted ? `timed out after ${options.timeoutMs}ms` : \"failed\"}: ${describeFetchFailure(err)}`,\n );\n return { ok: false, data: null, status: null, aborted };\n }\n}\n\ninterface PendingProbe {\n promise: Promise<boolean>;\n controller: AbortController;\n /** Callers still awaiting this sequence; at zero the sequence is aborted. */\n waiters: number;\n}\n\n/**\n * Collapses concurrent probe sequences onto one in-flight run.\n *\n * A timed-out availability probe deliberately caches nothing (issue #2210),\n * which removed the false verdict that used to absorb concurrent callers:\n * every queued request would then run its own full probe sequence, on a host\n * already slow enough to blow the probe budget.\n *\n * Cancellation is refcounted rather than shared: one caller walking away must\n * not abort a sequence the others are still waiting on, so the underlying task\n * is aborted only once every waiter has gone.\n */\nexport class SingleFlightProbe {\n private pending: PendingProbe | null = null;\n\n run(task: (signal: AbortSignal) => Promise<boolean>, signal?: AbortSignal): Promise<boolean> {\n let active = this.pending;\n if (!active) {\n const controller = new AbortController();\n const created: PendingProbe = { promise: Promise.resolve(false), controller, waiters: 0 };\n created.promise = task(controller.signal).finally(() => {\n if (this.pending === created) this.pending = null;\n });\n this.pending = created;\n active = created;\n }\n const entry = active;\n entry.waiters += 1;\n let released = false;\n const release = () => {\n if (released) return;\n released = true;\n entry.waiters -= 1;\n if (entry.waiters > 0) return;\n // Detach BEFORE aborting. `pending` would otherwise still point at this\n // doomed entry until the task's own `finally` runs a microtask later, and\n // a caller arriving in that window would join an aborted sequence and\n // read its `false` as a verdict.\n if (this.pending === entry) this.pending = null;\n entry.controller.abort();\n };\n if (!signal) return entry.promise.finally(release);\n return new Promise<boolean>((resolve, reject) => {\n const onAbort = () => {\n release();\n resolve(false);\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n entry.promise.then(\n (value) => {\n signal.removeEventListener(\"abort\", onAbort);\n release();\n resolve(value);\n },\n (err: unknown) => {\n signal.removeEventListener(\"abort\", onAbort);\n release();\n reject(err instanceof Error ? err : new Error(String(err)));\n },\n );\n });\n }\n}\n"],"mappings":";;;;;;;;AAgCO,SAAS,aAAa,KAAuB;AAClD,MAAI,CAAC,OAAO,OAAO,QAAQ,SAAU,QAAO;AAC5C,QAAM,QAAQ;AACd,SACE,MAAM,SAAS,gBACf,MAAM,YAAY,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