@konneal/engine 0.2.180 → 0.2.184

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/ask-7DFXT4DJ.js +16 -0
  2. package/dist/{chunk-FNQ7UOEB.js → chunk-5HCVX34C.js} +1 -1
  3. package/dist/{chunk-ZHT4456M.js → chunk-7RZ2D64X.js} +1 -1
  4. package/dist/{chunk-HWWJAJWM.js → chunk-QYTCQIA6.js} +3 -0
  5. package/dist/{chunk-D7MO4RVQ.js → chunk-XMUG75ZV.js} +1 -1
  6. package/dist/{chunk-ROXOL4GF.js → chunk-XO26UIFH.js} +5 -5
  7. package/dist/{chunk-CLDMP5YH.js → chunk-XTWH3PS6.js} +21 -4
  8. package/dist/{chunk-KINFFYQH.js → chunk-YGQCVPX6.js} +6 -0
  9. package/dist/{chunk-MUWO2EV6.js → chunk-YQQ3W5CE.js} +5 -5
  10. package/dist/{chunk-UMF7Y6JH.js → chunk-ZFOODZWO.js} +238 -8
  11. package/dist/config.d.ts +3 -0
  12. package/dist/{env-CNO44VN2.js → env-BZWHCSCL.js} +1 -1
  13. package/dist/env.d.ts +2 -0
  14. package/dist/openapi-surface.gen.d.ts +1 -1
  15. package/dist/openapi-types.d.ts +160 -0
  16. package/dist/search-4FWS4HVI.js +14 -0
  17. package/dist/{tools-UCUNOJR4.js → tools-BTH6YAOB.js} +5 -5
  18. package/dist/userDocuments.d.ts +72 -0
  19. package/dist/worker_mcp/src/index.js +2 -2
  20. package/dist/worker_public/src/config.js +1 -1
  21. package/dist/worker_public/src/index.js +82 -11
  22. package/dist/worker_public/src/requestScope.js +2 -2
  23. package/package.json +1 -1
  24. package/workers/worker_public/migrations/0020_user_documents.sql +18 -0
  25. package/workers/worker_public/openapi.yaml +72 -0
  26. package/workers/worker_public/schema.sql +16 -0
  27. package/workers/worker_public/src/ask.ts +11 -2
  28. package/workers/worker_public/src/config.ts +3 -0
  29. package/workers/worker_public/src/env.ts +2 -0
  30. package/workers/worker_public/src/index.ts +48 -1
  31. package/workers/worker_public/src/openapi-surface.gen.ts +24 -0
  32. package/workers/worker_public/src/ports/cloudflare/adapters.ts +3 -0
  33. package/workers/worker_public/src/ports/vector.ts +3 -0
  34. package/workers/worker_public/src/stages/index.ts +2 -0
  35. package/workers/worker_public/src/stages/types.ts +3 -0
  36. package/workers/worker_public/src/stages/userLane.ts +22 -0
  37. package/workers/worker_public/src/userDocuments.ts +329 -0
  38. package/workers/worker_public/wrangler.toml +8 -0
  39. package/dist/ask-TOJKDMU7.js +0 -16
  40. package/dist/search-KNPPTHMG.js +0 -14
@@ -0,0 +1,16 @@
1
+ import {
2
+ handleAsk
3
+ } from "./chunk-ZFOODZWO.js";
4
+ import "./chunk-IRCDOFP4.js";
5
+ import "./chunk-XO26UIFH.js";
6
+ import "./chunk-XTWH3PS6.js";
7
+ import "./chunk-7RZ2D64X.js";
8
+ import "./chunk-XMUG75ZV.js";
9
+ import "./chunk-ETLSWSZ7.js";
10
+ import "./chunk-5HCVX34C.js";
11
+ import "./chunk-QYTCQIA6.js";
12
+ import "./chunk-3FYJM7LH.js";
13
+ import "./chunk-YGQCVPX6.js";
14
+ export {
15
+ handleAsk
16
+ };
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  DATASETS,
3
3
  datasetAllowed
4
- } from "./chunk-HWWJAJWM.js";
4
+ } from "./chunk-QYTCQIA6.js";
5
5
  import {
6
6
  P
7
7
  } from "./chunk-3FYJM7LH.js";
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  answerEffort,
3
3
  effortBudget
4
- } from "./chunk-HWWJAJWM.js";
4
+ } from "./chunk-QYTCQIA6.js";
5
5
 
6
6
  // workers/worker_public/src/ai.ts
7
7
  var delay = (ms) => new Promise((r) => setTimeout(r, ms));
@@ -124,6 +124,9 @@ var THRESHOLDS = {
124
124
  /** Federated-ISO discount — the public corpus answers by default;
125
125
  * internal ISO passages compete but don't preempt. */
126
126
  federateDiscount: 0.95,
127
+ /** the member's own imported documents: how many lane hits may join
128
+ * the pool (TODO.sota/20 slice 4) — their content, their question */
129
+ userLaneK: 3,
127
130
  /** Standard-reference nudge (L5): when the question asks about an
128
131
  * invoked ISO/IEC standard, chunks that CARRY such a citation (their
129
132
  * text contains an ISO/IEC identifier) get a spread-scaled boost —
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  LIMITS,
3
3
  sha256Hex
4
- } from "./chunk-HWWJAJWM.js";
4
+ } from "./chunk-QYTCQIA6.js";
5
5
  import {
6
6
  P
7
7
  } from "./chunk-3FYJM7LH.js";
@@ -1,12 +1,12 @@
1
1
  import {
2
2
  embed
3
- } from "./chunk-ZHT4456M.js";
3
+ } from "./chunk-7RZ2D64X.js";
4
4
  import {
5
5
  standardKeysFrom
6
- } from "./chunk-FNQ7UOEB.js";
6
+ } from "./chunk-5HCVX34C.js";
7
7
  import {
8
8
  THRESHOLDS
9
- } from "./chunk-HWWJAJWM.js";
9
+ } from "./chunk-QYTCQIA6.js";
10
10
  import {
11
11
  P
12
12
  } from "./chunk-3FYJM7LH.js";
@@ -15,7 +15,7 @@ import {
15
15
  portIndex,
16
16
  portModelRunner,
17
17
  portStore
18
- } from "./chunk-KINFFYQH.js";
18
+ } from "./chunk-YGQCVPX6.js";
19
19
 
20
20
  // workers/worker_public/src/refs.ts
21
21
  var REF = /\[\[(u:(?:u:)?[A-Za-z0-9_-]+)\]\]/g;
@@ -1509,7 +1509,7 @@ async function runFind(env, args) {
1509
1509
  };
1510
1510
  }
1511
1511
  try {
1512
- const { portStore: portStore2 } = await import("./env-CNO44VN2.js");
1512
+ const { portStore: portStore2 } = await import("./env-BZWHCSCL.js");
1513
1513
  const res = await portStore2(env).prepare(compiled.sql).bind(...compiled.params).all();
1514
1514
  const rows = res?.results ?? [];
1515
1515
  const body = rows.length ? rows.map((r) => JSON.stringify(r)).join("\n") : "No rows matched. Either the predicates are too narrow or the data is absent \u2014 state which, and consider widening.";
@@ -1,11 +1,11 @@
1
1
  import {
2
2
  embed,
3
3
  rerank
4
- } from "./chunk-ZHT4456M.js";
4
+ } from "./chunk-7RZ2D64X.js";
5
5
  import {
6
6
  bubbleConfirmPage,
7
7
  isAllowedBubbleOrigin
8
- } from "./chunk-D7MO4RVQ.js";
8
+ } from "./chunk-XMUG75ZV.js";
9
9
  import {
10
10
  DATASETS,
11
11
  LIMITS,
@@ -15,7 +15,7 @@ import {
15
15
  processExpansion,
16
16
  sha256Hex,
17
17
  today
18
- } from "./chunk-HWWJAJWM.js";
18
+ } from "./chunk-QYTCQIA6.js";
19
19
  import {
20
20
  P
21
21
  } from "./chunk-3FYJM7LH.js";
@@ -25,7 +25,7 @@ import {
25
25
  portIndex,
26
26
  portModelRunner,
27
27
  portStore
28
- } from "./chunk-KINFFYQH.js";
28
+ } from "./chunk-YGQCVPX6.js";
29
29
 
30
30
  // node_modules/@pubid/pubid/dist/grammar/engine.js
31
31
  var ParseFailed = class extends Error {
@@ -22705,6 +22705,22 @@ var federate = {
22705
22705
  }
22706
22706
  };
22707
22707
 
22708
+ // workers/worker_public/src/stages/userLane.ts
22709
+ var userLane = {
22710
+ name: "user-lane",
22711
+ when: (c) => !!c.opts.userDocs,
22712
+ run: async (c) => {
22713
+ const fed = await c.opts.userDocs(c.rq).catch(() => []);
22714
+ const seen = new Set(c.hits.map((h) => h.id));
22715
+ for (const h of fed) {
22716
+ if (!seen.has(h.id)) {
22717
+ c.hits.push({ ...h });
22718
+ seen.add(h.id);
22719
+ }
22720
+ }
22721
+ }
22722
+ };
22723
+
22708
22724
  // workers/worker_public/src/stages/seal.ts
22709
22725
  async function familyChunks(env, familyNumber, query, keep) {
22710
22726
  const match2 = ftsMatchQuery(query) ?? `"${familyNumber}"`;
@@ -23526,6 +23542,7 @@ var STAGES = [
23526
23542
  poolOpen,
23527
23543
  lexicalUnion,
23528
23544
  federate,
23545
+ userLane,
23529
23546
  seal,
23530
23547
  licenseScope,
23531
23548
  overviewDemote,
@@ -108,6 +108,9 @@ function cfVectorIndex(index) {
108
108
  async upsert(vectors) {
109
109
  for (const group of by20(vectors)) await ix.upsert(group);
110
110
  },
111
+ async deleteIds(ids) {
112
+ for (const group of by20(ids)) await ix.deleteByIds(group);
113
+ },
111
114
  async getByIds(ids) {
112
115
  const out = [];
113
116
  for (const group of by20(ids)) {
@@ -181,7 +184,10 @@ function portRuntime(ctx) {
181
184
  }
182
185
 
183
186
  export {
187
+ cfModelRunner,
188
+ cfVectorIndex,
184
189
  cfBlobs,
190
+ cfStore,
185
191
  portModelRunner,
186
192
  portIndex,
187
193
  portKv,
@@ -6,27 +6,27 @@ import {
6
6
  sessionFrom,
7
7
  telemetry,
8
8
  understandQuery
9
- } from "./chunk-CLDMP5YH.js";
9
+ } from "./chunk-XTWH3PS6.js";
10
10
  import {
11
11
  corsHeaders,
12
12
  err,
13
13
  json,
14
14
  readJson,
15
15
  validateQuery
16
- } from "./chunk-D7MO4RVQ.js";
16
+ } from "./chunk-XMUG75ZV.js";
17
17
  import {
18
18
  entitlementScope,
19
19
  standardKeysFrom
20
- } from "./chunk-FNQ7UOEB.js";
20
+ } from "./chunk-5HCVX34C.js";
21
21
  import {
22
22
  LIMITS,
23
23
  MODELS,
24
24
  num,
25
25
  sha256Hex
26
- } from "./chunk-HWWJAJWM.js";
26
+ } from "./chunk-QYTCQIA6.js";
27
27
  import {
28
28
  portModelRunner
29
- } from "./chunk-KINFFYQH.js";
29
+ } from "./chunk-YGQCVPX6.js";
30
30
 
31
31
  // workers/worker_public/src/search.ts
32
32
  async function handleSearch(env, ctx, req, tier, key) {
@@ -33,7 +33,7 @@ import {
33
33
  tableRetyped,
34
34
  toolNote,
35
35
  verdictNote
36
- } from "./chunk-ROXOL4GF.js";
36
+ } from "./chunk-XO26UIFH.js";
37
37
  import {
38
38
  NO_CONTEXT,
39
39
  STAGE_NAMES,
@@ -76,18 +76,18 @@ import {
76
76
  tokenBudget,
77
77
  understandQuery,
78
78
  usageTotal
79
- } from "./chunk-CLDMP5YH.js";
79
+ } from "./chunk-XTWH3PS6.js";
80
80
  import {
81
81
  embed,
82
82
  generateOnce
83
- } from "./chunk-ZHT4456M.js";
83
+ } from "./chunk-7RZ2D64X.js";
84
84
  import {
85
85
  corsHeaders,
86
86
  err,
87
87
  json,
88
88
  readJson,
89
89
  validateQuery
90
- } from "./chunk-D7MO4RVQ.js";
90
+ } from "./chunk-XMUG75ZV.js";
91
91
  import {
92
92
  cacheableAnswer,
93
93
  canonicalRefusal,
@@ -100,7 +100,7 @@ import {
100
100
  requestSalt,
101
101
  resolveRequestScope,
102
102
  standardKeysFrom
103
- } from "./chunk-FNQ7UOEB.js";
103
+ } from "./chunk-5HCVX34C.js";
104
104
  import {
105
105
  LIMITS,
106
106
  MODELS,
@@ -111,14 +111,16 @@ import {
111
111
  requestEffort,
112
112
  roleModel,
113
113
  sha256Hex
114
- } from "./chunk-HWWJAJWM.js";
114
+ } from "./chunk-QYTCQIA6.js";
115
115
  import {
116
116
  P
117
117
  } from "./chunk-3FYJM7LH.js";
118
118
  import {
119
+ cfModelRunner,
120
+ cfVectorIndex,
119
121
  portModelRunner,
120
122
  portStore
121
- } from "./chunk-KINFFYQH.js";
123
+ } from "./chunk-YGQCVPX6.js";
122
124
 
123
125
  // workers/worker_public/src/internal_gateway.ts
124
126
  async function retrieveInternal(service, auth, query) {
@@ -1675,6 +1677,227 @@ function partitionSubsets(hits, k = SPECULATIVE_SUBSETS) {
1675
1677
  // workers/worker_public/prompts/speculative-verify.md
1676
1678
  var speculative_verify_default = "You answer questions about legal-metrology publications for {{PUBLISHER_NAME}}. Candidate draft answers were prepared in parallel, each from a PARTIAL view of the evidence (a subset of the passages); you see every candidate beside the FULL passages. Produce the final answer.\n\nRules:\n1. Compare the candidates against the full passages. Adopt the candidate best supported by the evidence as your starting point; correct every claim the full passages contradict or fail to support, and fold in anything the other candidates got right that the adopted one missed.\n2. Ground every factual claim in the numbered passages and cite them inline as [1], [2], \u2026 exactly as the passages are numbered below. Never cite a passage that is not there.\n3. Quote verbatim \u2014 with quotation marks \u2014 when a clause's exact wording matters (definitions, thresholds, requirements); a quotation must appear word-for-word in the passages.\n4. Numeric and table values come from the passages exactly; never retype a table as markdown \u2014 refer to the table and cite it.\n5. If the passages do not answer the question, say so plainly instead of guessing.\n6. Be complete but compact: answer the question, cite, stop.\n";
1677
1679
 
1680
+ // workers/worker_public/src/userDocuments.ts
1681
+ var USER_DOC_LIMIT = 10;
1682
+ var USER_DOC_MAX_BYTES = 20 * 1024 * 1024;
1683
+ var ACCEPTED_MIMES = /* @__PURE__ */ new Set(["image/png", "image/jpeg", "image/webp", "application/pdf"]);
1684
+ function userDocumentChunkId(docId) {
1685
+ return `ud-${docId}`;
1686
+ }
1687
+ async function listUserDocuments(store, sub) {
1688
+ const res = await store.prepare("SELECT id, owner_sub, name, kind, status, bytes, r2_key, fields, error, created_at, updated_at FROM user_documents WHERE owner_sub = ?1 ORDER BY created_at DESC").bind(sub).all();
1689
+ return { documents: res.results ?? [] };
1690
+ }
1691
+ async function getUserDocument(store, sub, id) {
1692
+ const row = await store.prepare("SELECT id, owner_sub, name, kind, status, bytes, r2_key, fields, error, created_at, updated_at FROM user_documents WHERE id = ?1 AND owner_sub = ?2").bind(id, sub).first();
1693
+ return row ?? null;
1694
+ }
1695
+ async function quotaRefusal(store, sub) {
1696
+ const row = await store.prepare("SELECT COUNT(*) AS n FROM user_documents WHERE owner_sub = ?1").bind(sub).first();
1697
+ const n = Number(row?.n ?? 0);
1698
+ if (n >= USER_DOC_LIMIT) {
1699
+ return new Response(JSON.stringify({ error: { code: "quota_exceeded", message: `You hold the maximum of ${USER_DOC_LIMIT} documents. Delete one to import another.` } }), { status: 403, headers: { "content-type": "application/json" } });
1700
+ }
1701
+ return null;
1702
+ }
1703
+ async function createImport(ports, waitUntil, sub, file) {
1704
+ const mime = file.type || "";
1705
+ if (!ACCEPTED_MIMES.has(mime)) {
1706
+ return { error: new Response(JSON.stringify({ error: { code: "invalid_type", message: "Upload a PNG, JPEG, WebP image or a PDF." } }), { status: 415, headers: { "content-type": "application/json" } }) };
1707
+ }
1708
+ if (file.size > USER_DOC_MAX_BYTES) {
1709
+ return { error: new Response(JSON.stringify({ error: { code: "too_large", message: `Documents are limited to ${Math.floor(USER_DOC_MAX_BYTES / (1024 * 1024))} MB.` } }), { status: 413, headers: { "content-type": "application/json" } }) };
1710
+ }
1711
+ const refused = await quotaRefusal(ports.store, sub);
1712
+ if (refused) return { error: refused };
1713
+ const id = crypto.randomUUID();
1714
+ const r2Key = `${sub}/${id}`;
1715
+ const bytes = new Uint8Array(await file.arrayBuffer());
1716
+ await ports.blobs.put(r2Key, bytes.buffer, mime);
1717
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1718
+ const row = {
1719
+ id,
1720
+ owner_sub: sub,
1721
+ name: file.name || "document",
1722
+ kind: null,
1723
+ status: "importing",
1724
+ bytes: bytes.byteLength,
1725
+ r2_key: r2Key,
1726
+ fields: null,
1727
+ error: null,
1728
+ created_at: now,
1729
+ updated_at: now
1730
+ };
1731
+ await ports.store.prepare(
1732
+ "INSERT INTO user_documents (id, owner_sub, name, kind, status, bytes, r2_key, fields, error, created_at, updated_at) VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11)"
1733
+ ).bind(id, sub, row.name, row.kind, row.status, row.bytes, row.r2_key, row.fields, row.error, now, now).run();
1734
+ waitUntil(processImport(ports, row, mime, bytes).catch(() => {
1735
+ }));
1736
+ return { document: row };
1737
+ }
1738
+ async function processImport(ports, row, mime, bytes) {
1739
+ const setStatus = async (status, fields, error) => {
1740
+ await ports.store.prepare("UPDATE user_documents SET status = ?1, kind = ?2, fields = ?3, error = ?4, updated_at = ?5 WHERE id = ?6").bind(status, fields ? extractKind(fields) : null, fields ? JSON.stringify(fields) : null, error, (/* @__PURE__ */ new Date()).toISOString(), row.id).run();
1741
+ };
1742
+ try {
1743
+ let text;
1744
+ if (mime === "application/pdf") {
1745
+ text = await pdfTextLayer(bytes);
1746
+ if (!text || text.replace(/\s+/g, "").length < 40) {
1747
+ await setStatus("no_text_layer", null, "This PDF has no extractable text layer. Export page images (PNG/JPEG) and import those \u2014 the vision lane reads them directly.");
1748
+ return;
1749
+ }
1750
+ } else {
1751
+ text = await visionTranscribe(ports.model, mime, bytes);
1752
+ if (!text || text.replace(/\s+/g, "").length < 20) {
1753
+ await setStatus("failed", null, "The vision lane could not read this image. Try a sharper photo.");
1754
+ return;
1755
+ }
1756
+ }
1757
+ const extraction = await structureDocument(ports.model, row.name, mime, text);
1758
+ const fieldsLine = Object.entries(extraction.fields).map(([k, v]) => `${k}: ${v}`).join("; ");
1759
+ const chunkText = `Member document (${extraction.kind}) \u2014 ${row.name}. ${fieldsLine}. ${extraction.summary}
1760
+
1761
+ ${extraction.text.slice(0, 8e3)}`;
1762
+ const [vector] = await ports.model.embed([chunkText]);
1763
+ await ports.lane.upsert([
1764
+ {
1765
+ id: userDocumentChunkId(row.id),
1766
+ values: vector,
1767
+ metadata: {
1768
+ user_sub: row.owner_sub,
1769
+ doc_id: `ud-${row.id}`,
1770
+ docidentifier: `Member document \u2014 ${row.name}`,
1771
+ doctype: "user",
1772
+ doc_number: extraction.kind,
1773
+ edition: "",
1774
+ language: "en",
1775
+ clause_anchor: "",
1776
+ clause_title: row.name.slice(0, 120),
1777
+ tier: "member",
1778
+ corpus: "user_docs",
1779
+ text_ref: "",
1780
+ kind: extraction.kind,
1781
+ name: row.name.slice(0, 120),
1782
+ chunk_text: chunkText.slice(0, 1800)
1783
+ }
1784
+ }
1785
+ ]);
1786
+ await setStatus("ready", { kind: extraction.kind, ...extraction.fields, summary: extraction.summary }, null);
1787
+ } catch (e) {
1788
+ await setStatus("failed", null, String(e).slice(0, 200)).catch(() => {
1789
+ });
1790
+ }
1791
+ }
1792
+ function extractKind(fields) {
1793
+ return fields.kind || "other";
1794
+ }
1795
+ async function visionTranscribe(model, mime, bytes) {
1796
+ let binary = "";
1797
+ const CHUNK = 32768;
1798
+ for (let i = 0; i < bytes.length; i += CHUNK) binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK));
1799
+ const dataUrl = `data:${mime};base64,${btoa(binary)}`;
1800
+ const res = await model.run({
1801
+ model: MODELS.member,
1802
+ messages: [
1803
+ { role: "system", content: "Transcribe everything you can read in this document image \u2014 certificate numbers, holders, models, values, dates, clause references. Transcribe first; organize nothing." },
1804
+ { role: "user", content: [{ type: "image_url", image_url: { url: dataUrl } }] }
1805
+ ],
1806
+ maxTokens: 2048,
1807
+ effort: "low",
1808
+ temperature: 0.15
1809
+ });
1810
+ return res.text ?? "";
1811
+ }
1812
+ async function structureDocument(model, name, mime, text) {
1813
+ const res = await model.run({
1814
+ model: MODELS.member,
1815
+ messages: [
1816
+ { role: "system", content: `You classify and structure an imported metrology document. Answer with ONE JSON object: {"kind": "certificate"|"test_report"|"other", "fields": {\u2026short typed fields\u2026}, "summary": "one paragraph a retrieval engine can answer from"}. Certificates carry certificate numbers (like R60/2021-XX1-24.01), holders, models, issue dates. Test reports carry measured values, uncertainties, instruments, clause references. Fields use snake_case names, values verbatim from the text. Never invent a value the text does not carry.` },
1817
+ { role: "user", content: `Document name: ${name}
1818
+ Format: ${mime}
1819
+
1820
+ Text:
1821
+ ${text.slice(0, 12e3)}` }
1822
+ ],
1823
+ maxTokens: 2048,
1824
+ effort: "low",
1825
+ temperature: 0.15
1826
+ });
1827
+ const raw = res.text ?? "";
1828
+ const m = /\{[\s\S]*\}/.exec(raw);
1829
+ if (!m) throw new Error("the structuring call returned no JSON object");
1830
+ const parsed = JSON.parse(m[0]);
1831
+ const fields = {};
1832
+ for (const [k, v] of Object.entries(parsed.fields ?? {})) {
1833
+ if (typeof v === "string" || typeof v === "number") fields[k.slice(0, 40)] = String(v).slice(0, 200);
1834
+ }
1835
+ const kind = parsed.kind === "certificate" || parsed.kind === "test_report" ? parsed.kind : "other";
1836
+ return { kind, fields, summary: String(parsed.summary ?? "").slice(0, 1200), text };
1837
+ }
1838
+ async function pdfTextLayer(bytes) {
1839
+ const raw = new TextDecoder("latin1").decode(bytes);
1840
+ const parts = [];
1841
+ const streamRe = /stream\r?\n?/g;
1842
+ let m;
1843
+ while (m = streamRe.exec(raw)) {
1844
+ const start = m.index + m[0].length;
1845
+ const end = raw.indexOf("endstream", start);
1846
+ if (end < 0) break;
1847
+ const chunk = raw.slice(start, end);
1848
+ streamRe.lastIndex = end;
1849
+ let content = "";
1850
+ if (chunk.charCodeAt(0) === 120) {
1851
+ try {
1852
+ const ds = new DecompressionStream("deflate");
1853
+ const stream = new Blob([new Uint8Array([...chunk].map((c) => c.charCodeAt(0) & 255))]).stream().pipeThrough(ds);
1854
+ content = await new Response(stream).text();
1855
+ } catch {
1856
+ continue;
1857
+ }
1858
+ } else if (/\bTj\b|\bTJ\b/.test(chunk)) {
1859
+ content = chunk;
1860
+ } else {
1861
+ continue;
1862
+ }
1863
+ parts.push(pdfTextOps(content));
1864
+ if (parts.join("").length > 2e5) break;
1865
+ }
1866
+ return parts.join("\n");
1867
+ }
1868
+ function pdfTextOps(content) {
1869
+ const out = [];
1870
+ const re = /\((?:\\.|[^\\()])*\)/g;
1871
+ let m;
1872
+ while (m = re.exec(content)) {
1873
+ let s = m[0].slice(1, -1);
1874
+ s = s.replace(/\\([nrtbf()/\\])/g, (_, c) => ({ n: "\n", r: "", t: " ", b: "", f: "", "(": "(", ")": ")", "/": "/", "\\": "\\" })[c] ?? c);
1875
+ s = s.replace(/\\([0-7]{1,3})/g, (_, o) => String.fromCharCode(parseInt(o, 8)));
1876
+ if (s.trim()) out.push(s);
1877
+ }
1878
+ return out.join(" ");
1879
+ }
1880
+ async function queryUserLane(model, lane, sub, query, k) {
1881
+ const [vector] = await model.embed([query]);
1882
+ const matches = await lane.query({ vector, topK: k, filter: { user_sub: sub } });
1883
+ return matches.map((m) => ({
1884
+ id: m.id,
1885
+ score: m.score,
1886
+ metadata: m.metadata,
1887
+ text: String(m.metadata?.chunk_text ?? "")
1888
+ }));
1889
+ }
1890
+ async function deleteUserDocument(ports, sub, id) {
1891
+ const row = await getUserDocument(ports.store, sub, id);
1892
+ if (!row) return null;
1893
+ if (row.r2_key) await ports.blobs.delete(row.r2_key).catch(() => {
1894
+ });
1895
+ await ports.lane.deleteIds([userDocumentChunkId(id)]).catch(() => {
1896
+ });
1897
+ await ports.store.prepare("DELETE FROM user_documents WHERE id = ?1 AND owner_sub = ?2").bind(id, sub).run();
1898
+ return row;
1899
+ }
1900
+
1678
1901
  // workers/worker_public/src/operations.ts
1679
1902
  function isOperationIntent(query) {
1680
1903
  return /\b(operations?|endpoints?)\b/i.test(query);
@@ -2179,6 +2402,7 @@ async function handleAsk(env, ctx, req, tier, key) {
2179
2402
  const requestSaltStr = requestSalt(scope, memoryUsed);
2180
2403
  const salt = requestSaltStr ? `${requestSaltStr}|effort:${effort}` : `effort:${effort}`;
2181
2404
  const federate = (member || keyLicensed) && service && isoOn ? (q2) => retrieveInternal(service, fedAuth, q2) : void 0;
2405
+ const userDocs = member && env.USER_DOCS_INDEX ? (q2) => queryUserLane(cfModelRunner(env.AI), cfVectorIndex(env.USER_DOCS_INDEX), member.sub, q2, THRESHOLDS.userLaneK) : void 0;
2182
2406
  const ns = tier === "key" ? `k:${key.id}` : member ? `m:${member.sub}` : "anon";
2183
2407
  const model = member ? MODELS.member : MODELS.anon;
2184
2408
  const prev = typeof body?.prev === "string" ? body.prev.slice(0, 800) : void 0;
@@ -2734,6 +2958,7 @@ Answer account questions from these records ONLY: name the record when you use i
2734
2958
  prev,
2735
2959
  understanding,
2736
2960
  federate,
2961
+ userDocs,
2737
2962
  warmEmbed,
2738
2963
  graphDocNumbers,
2739
2964
  sealScope: declaredScoped ? docScope : null,
@@ -2768,7 +2993,7 @@ Answer account questions from these records ONLY: name the record when you use i
2768
2993
  if (grade === "weak" && understanding?.docidentifier) {
2769
2994
  const broaden = `${understanding.standalone_query || q2.query} ${understanding.docidentifier}`.trim();
2770
2995
  const tc = Date.now();
2771
- const second = await retrieve(env, q2.query, { prev, understanding, queryOverride: broaden, federate, datasetScope: narrowed ? corpora : null, standardKeys, sealScope: declaredScoped ? docScope : null, lexicalBoost, ...routeSubset ? { stageSubset: routeSubset } : {} });
2996
+ const second = await retrieve(env, q2.query, { prev, understanding, queryOverride: broaden, federate, userDocs, datasetScope: narrowed ? corpora : null, standardKeys, sealScope: declaredScoped ? docScope : null, lexicalBoost, ...routeSubset ? { stageSubset: routeSubset } : {} });
2772
2997
  const grade2 = await gradeRetrieval(env.AI, roleModel(env, "grader"), q2.query, second.hits.map((h) => h.text));
2773
2998
  stageTiming.corrective = Date.now() - tc;
2774
2999
  if (grade2 === "good") retrieved = second;
@@ -3299,6 +3524,11 @@ Answer account questions from these records ONLY: name the record when you use i
3299
3524
 
3300
3525
  export {
3301
3526
  handleMemories,
3527
+ USER_DOC_LIMIT,
3528
+ listUserDocuments,
3529
+ getUserDocument,
3530
+ createImport,
3531
+ deleteUserDocument,
3302
3532
  scoreFaithfulness,
3303
3533
  checkQuoteAnchors,
3304
3534
  scoreJudge,
package/dist/config.d.ts CHANGED
@@ -74,6 +74,9 @@ export declare const THRESHOLDS: {
74
74
  /** Federated-ISO discount — the public corpus answers by default;
75
75
  * internal ISO passages compete but don't preempt. */
76
76
  readonly federateDiscount: 0.95;
77
+ /** the member's own imported documents: how many lane hits may join
78
+ * the pool (TODO.sota/20 slice 4) — their content, their question */
79
+ readonly userLaneK: 3;
77
80
  /** Standard-reference nudge (L5): when the question asks about an
78
81
  * invoked ISO/IEC standard, chunks that CARRY such a citation (their
79
82
  * text contains an ISO/IEC identifier) get a spread-scaled boost —
@@ -6,7 +6,7 @@ import {
6
6
  portModelRunner,
7
7
  portRuntime,
8
8
  portStore
9
- } from "./chunk-KINFFYQH.js";
9
+ } from "./chunk-YGQCVPX6.js";
10
10
  export {
11
11
  hasLane,
12
12
  portBlobs,
package/dist/env.d.ts CHANGED
@@ -21,6 +21,8 @@ export interface Env {
21
21
  INDEX_VERSION: string;
22
22
  UNIT_ASSETS: R2Bucket;
23
23
  CHAT_UPLOADS: R2Bucket;
24
+ USER_DOCS: R2Bucket;
25
+ USER_DOCS_INDEX: any;
24
26
  ANON_DAY_ASK: string;
25
27
  ANON_DAY_SEARCH: string;
26
28
  KEY_DAY_ASK_DEFAULT: string;
@@ -3,7 +3,7 @@ export interface OpenApiRoute {
3
3
  pattern: string;
4
4
  operationId: string;
5
5
  }
6
- export type OpenApiOperationId = "credits" | "creditsAlias" | "askAnonymous" | "askKeyed" | "search" | "searchKeyed" | "verify" | "verifyKeyed" | "research" | "researchKeyed" | "mcp" | "datasets" | "keyUsage" | "health" | "listConversations" | "createConversation" | "getConversation" | "renameConversation" | "deleteConversation" | "appendMessage" | "shareConversation" | "getShared" | "uploadAttachment" | "listAttachments" | "getAttachment" | "deleteAttachment" | "listMemories" | "createMemory" | "deleteMemory" | "listProjects" | "createProject" | "deleteProject" | "listProjectFiles" | "attachProjectFile" | "detachProjectFile" | "laneQuery" | "laneKeyed" | "feedback" | "adminEnrich" | "adminEnrichAlias" | "adminSection" | "adminFamilySummary" | "adminSectionAlias" | "adminFamilySummaryAlias" | "adminVectors" | "adminCaption" | "adminVisionJudge" | "adminJudge" | "adminJudgeAlias" | "adminRevokeKey" | "authMe" | "authLogin" | "authCallback" | "authLogout" | "authLogoutLink" | "adminStats" | "adminListKeys" | "adminCreateKey";
6
+ export type OpenApiOperationId = "credits" | "creditsAlias" | "askAnonymous" | "askKeyed" | "search" | "searchKeyed" | "verify" | "verifyKeyed" | "research" | "researchKeyed" | "mcp" | "datasets" | "keyUsage" | "health" | "listConversations" | "createConversation" | "getConversation" | "renameConversation" | "deleteConversation" | "appendMessage" | "shareConversation" | "getShared" | "uploadAttachment" | "listAttachments" | "getAttachment" | "deleteAttachment" | "listMemories" | "createMemory" | "deleteMemory" | "listUserDocuments" | "createUserDocument" | "getUserDocument" | "deleteUserDocument" | "listProjects" | "createProject" | "deleteProject" | "listProjectFiles" | "attachProjectFile" | "detachProjectFile" | "laneQuery" | "laneKeyed" | "feedback" | "adminEnrich" | "adminEnrichAlias" | "adminSection" | "adminFamilySummary" | "adminSectionAlias" | "adminFamilySummaryAlias" | "adminVectors" | "adminCaption" | "adminVisionJudge" | "adminJudge" | "adminJudgeAlias" | "adminRevokeKey" | "authMe" | "authLogin" | "authCallback" | "authLogout" | "authLogoutLink" | "adminStats" | "adminListKeys" | "adminCreateKey";
7
7
  export declare const OPENAPI_SURFACE: readonly (Omit<OpenApiRoute, "operationId"> & {
8
8
  operationId: OpenApiOperationId;
9
9
  })[];