@bendyline/gezel-sdk 1.1.13 → 1.1.14

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/checks.d.ts CHANGED
@@ -58,12 +58,17 @@ declare function runSniff(name: StepSniffName, content: string): boolean;
58
58
  * factual chat. It catches invention, not a wrong source copied faithfully.
59
59
  *
60
60
  * Citations it reads: `[n]` markers resolved through a Sources / References
61
- * list, and inline `(source: path)` notes. Cited URLs, `knowledge://`
62
- * references and PDF or Office files cannot be read here as text, so a
63
- * sentence citing only those counts as cited but unverified, never as
64
- * invented. `sources` adds material the facts
65
- * may come from without being cited (a contract's supplied brief), so a true
66
- * but uncited detail reads as a citation slip rather than an invention.
61
+ * list, inline `(source: path)` notes, bracketed paths, and a parenthesis
62
+ * holding only file names when those files exist (`(win-fulfillment.md)`).
63
+ * Cited URLs, `knowledge://` references and PDF or Office files cannot be
64
+ * read here as text, so a sentence citing only those counts as cited but
65
+ * unverified, never as invented. `sources` adds material the facts may come
66
+ * from without being cited (a contract's supplied brief), so a true but
67
+ * uncited detail reads as a citation slip rather than an invention.
68
+ *
69
+ * An HTML document or source is read as the text its reader sees
70
+ * (`htmlAsMarkdown`), so its styles and head are not facts and its headings,
71
+ * lists and links cite the way their Markdown forms do.
67
72
  */
68
73
  interface ClaimsGroundedOptions {
69
74
  /** Files or folders the facts may come from, cited or not. */
@@ -97,6 +102,8 @@ interface ClaimsGroundedResult extends CheckResult {
97
102
  };
98
103
  problems: string[];
99
104
  }
105
+ /** The `n -> reference` entries a document's own Sources / References section defines. */
106
+ declare function sourceListReferences(markdown: string): ReadonlyMap<number, string>;
100
107
  declare function claimsGrounded(ws: WorkspaceLike, file: string, opts?: ClaimsGroundedOptions): Promise<ClaimsGroundedResult>;
101
108
 
102
109
  /**
@@ -472,6 +479,13 @@ declare function citationsResolve(ws: WorkspaceLike, file: string, opts?: {
472
479
  * like a missing file.
473
480
  */
474
481
  resolveKnowledge?: (uri: string) => Promise<boolean>;
482
+ /**
483
+ * The document is a plan: a missing path it marks as new or to be
484
+ * created is forgiven like a known path (it never counts toward the
485
+ * minimum). Off for sources, where "a new study `x.pdf`" would launder
486
+ * a fabrication.
487
+ */
488
+ proposed?: boolean;
475
489
  }): Promise<CitationsResult>;
476
490
  /** Spec for {@link valuesSubsetOf}. */
477
491
  interface ValuesSubsetSpec {
@@ -963,4 +977,4 @@ declare function workspaceFromGezel(g: {
963
977
  };
964
978
  }): WorkspaceLike;
965
979
 
966
- export { type CellType, type CheckResult, type CitationsResult, type ClaimsGroundedOptions, type ClaimsGroundedResult, type CodebaseReviewReportOptions, type CodebaseReviewReportResult, type CorpusCoverageLedger, type CorpusCoverageMergeResult, type CorpusCoverageShardInput, type CsvShapeResult, type CsvShapeSpec, type EntitiesResult, type EntitySpec, type ExplainableSniff, type FigureCheckOptions, type FigureCheckResult, type FigureFinding, type FigureFindingKind, GateScriptResult, type GroundingFact, type GroundingResult, IMG_EXT, type ImageRefsReport, type InlineScript, type JsonPathEqualsResult, type JsonScalar, type JudgeVerdict, MIN_INLINE_JS_BYTES, MIN_JUDGE_EVIDENCE_SUBSTRING, type MarkdownHeadingsMatchResult, type ParsedTable, type PlanRow, type PlanStructureResult, type PlanStructureSpec, type ReadingLevelResult, type RecordFieldSpec, type RecordSchemaResult, type RecordSchemaSpec, type ScriptValidation, type SecurityReportOptions, type SecurityReportResult, type StepSniffName, type TableShapeResult, type TableShapeSpec, type UnsupportedClaimPattern, type UnsupportedClaimViolation, type UnsupportedClaimsResult, type ValuesSubsetResult, type ValuesSubsetSpec, type WordBandResult, type WorkspaceLike, buildJudgePrompt, checkFigures, citationsResolve, citedPathKey, claimsGrounded, cleanCitedPath, codebaseReviewReport, containsPattern, countDistinctMatches, createCitedPathChecker, cssMinBytes, csvShape, dataTableSniff, detectTypeScriptOnlySyntax, detectUnclosedScript, esmImports, explainSniff, extractInlineScripts, extractMoneyAmounts, fileCountByExt, fileMinBytes, fileMinLines, findImageRefs, frontmatterList, gateResult, grepMatches, htmlCompleteSniff, htmlGameSniff, imageRefsResolve, inlineJsBytes, isRealIsoDate, jsonPathEquals, jsonValid, listedFiles, markdownHeadingsMatch, mergeCorpusCoverageShards, namedEntitiesConsistent, normalizeDigitGroups, normalizeInlineEmphasis, normalizeTypography, notContainsPattern, parseCsv, parseJudgeVerdict, parseMarkdownTable, planStructure, readingLevel, recordSchema, requireOrderedSections, resolveRelative, runSniff, securityReport, standaloneJsParses, tableShape, totalMinBytes, unsupportedClaims, validateJudgeEvidence, validateScriptSyntax, valueGrounding, valuesSubsetOf, wordBand, workspaceFromGezel, wrapperReturnHint };
980
+ export { type CellType, type CheckResult, type CitationsResult, type ClaimsGroundedOptions, type ClaimsGroundedResult, type CodebaseReviewReportOptions, type CodebaseReviewReportResult, type CorpusCoverageLedger, type CorpusCoverageMergeResult, type CorpusCoverageShardInput, type CsvShapeResult, type CsvShapeSpec, type EntitiesResult, type EntitySpec, type ExplainableSniff, type FigureCheckOptions, type FigureCheckResult, type FigureFinding, type FigureFindingKind, GateScriptResult, type GroundingFact, type GroundingResult, IMG_EXT, type ImageRefsReport, type InlineScript, type JsonPathEqualsResult, type JsonScalar, type JudgeVerdict, MIN_INLINE_JS_BYTES, MIN_JUDGE_EVIDENCE_SUBSTRING, type MarkdownHeadingsMatchResult, type ParsedTable, type PlanRow, type PlanStructureResult, type PlanStructureSpec, type ReadingLevelResult, type RecordFieldSpec, type RecordSchemaResult, type RecordSchemaSpec, type ScriptValidation, type SecurityReportOptions, type SecurityReportResult, type StepSniffName, type TableShapeResult, type TableShapeSpec, type UnsupportedClaimPattern, type UnsupportedClaimViolation, type UnsupportedClaimsResult, type ValuesSubsetResult, type ValuesSubsetSpec, type WordBandResult, type WorkspaceLike, buildJudgePrompt, checkFigures, citationsResolve, citedPathKey, claimsGrounded, cleanCitedPath, codebaseReviewReport, containsPattern, countDistinctMatches, createCitedPathChecker, cssMinBytes, csvShape, dataTableSniff, detectTypeScriptOnlySyntax, detectUnclosedScript, esmImports, explainSniff, extractInlineScripts, extractMoneyAmounts, fileCountByExt, fileMinBytes, fileMinLines, findImageRefs, frontmatterList, gateResult, grepMatches, htmlCompleteSniff, htmlGameSniff, imageRefsResolve, inlineJsBytes, isRealIsoDate, jsonPathEquals, jsonValid, listedFiles, markdownHeadingsMatch, mergeCorpusCoverageShards, namedEntitiesConsistent, normalizeDigitGroups, normalizeInlineEmphasis, normalizeTypography, notContainsPattern, parseCsv, parseJudgeVerdict, parseMarkdownTable, planStructure, readingLevel, recordSchema, requireOrderedSections, resolveRelative, runSniff, securityReport, sourceListReferences, standaloneJsParses, tableShape, totalMinBytes, unsupportedClaims, validateJudgeEvidence, validateScriptSyntax, valueGrounding, valuesSubsetOf, wordBand, workspaceFromGezel, wrapperReturnHint };
package/dist/checks.js CHANGED
@@ -695,6 +695,7 @@ var MONTHS = [
695
695
  "november",
696
696
  "december"
697
697
  ];
698
+ var MONTH_NAME = MONTHS.map((m) => m[0].toUpperCase() + m.slice(1)).join("|");
698
699
  var SMALL_NUMBERS = [
699
700
  "zero",
700
701
  "one",
@@ -742,6 +743,26 @@ var NAME_JOINERS = /* @__PURE__ */ new Set([
742
743
  "the",
743
744
  "and"
744
745
  ]);
746
+ var MONTH_BEFORE_DAY = new RegExp(
747
+ `\\b(${MONTH_NAME})\\s+(?:\\d{1,2}(?:st|nd|rd|th)?\\s*[-\u2013\u2014]\\s*)?$`
748
+ );
749
+ var MONTH_AFTER_DAY = new RegExp(
750
+ `^\\s+(?:of\\s+)?(${MONTH_NAME})\\b(?:,?\\s+(1\\d{3}|20\\d{2})\\b)?`
751
+ );
752
+ var YEAR_AFTER_DAY = /^,?\s+(1\d{3}|20\d{2})\b/;
753
+ function dayOfMonth(before, after, digits) {
754
+ const day = Number(digits);
755
+ if (!/^\d{1,2}$/.test(digits) || day < 1 || day > 31) return void 0;
756
+ const monthOf = (name) => MONTHS.indexOf((name ?? "").toLowerCase()) + 1;
757
+ const lead = MONTH_BEFORE_DAY.exec(before);
758
+ if (lead) {
759
+ const year = YEAR_AFTER_DAY.exec(after)?.[1];
760
+ return { month: monthOf(lead[1]), ...year ? { year } : {} };
761
+ }
762
+ const trail = MONTH_AFTER_DAY.exec(after);
763
+ if (trail) return { month: monthOf(trail[1]), ...trail[2] ? { year: trail[2] } : {} };
764
+ return void 0;
765
+ }
745
766
  var CLOCK_TIME = /(?<![\d:.])((?:[01]?\d|2[0-3]):[0-5]\d(?::[0-5]\d)?)(?![\d:])/g;
746
767
  var APPROXIMATE = /(?:[~≈]\s*|\b(?:about|around|roughly|approximately|approx\.|nearly|almost|circa|some)\s+)(?:\d[\d,.]*\s*(?:[-–—]|to)\s*)?$/i;
747
768
  var ENUMERATOR_LABEL = /(?:\b(?:step|phase|slide|part|stage|round|option|item|section|chapter|no\.)\s*|[#§]\s*)$/i;
@@ -754,7 +775,7 @@ function extractClaims(text) {
754
775
  const claims = [];
755
776
  const seen = /* @__PURE__ */ new Set();
756
777
  const add = (kind, value, flags = {}) => {
757
- const key = `${kind}:${value.toLowerCase()}`;
778
+ const key = `${kind}:${value.toLowerCase()}${flags.day ? `@${flags.day.month}` : ""}`;
758
779
  if (!seen.has(key)) {
759
780
  seen.add(key);
760
781
  claims.push({
@@ -762,7 +783,8 @@ function extractClaims(text) {
762
783
  value,
763
784
  ...flags.approx ? { approx: true } : {},
764
785
  ...flags.percent ? { percent: true } : {},
765
- ...flags.clock ? { clock: true } : {}
786
+ ...flags.clock ? { clock: true } : {},
787
+ ...flags.day ? { day: flags.day } : {}
766
788
  });
767
789
  }
768
790
  };
@@ -778,17 +800,20 @@ function extractClaims(text) {
778
800
  const digits = (m[1] ?? "").replace(/,/g, "");
779
801
  const value = Number(digits);
780
802
  const at = m.index ?? 0;
781
- if (isEnumerator(numeric.slice(0, at), numeric.slice(at + m[0].length), value)) continue;
803
+ const before = numeric.slice(0, at);
804
+ const after = numeric.slice(at + m[0].length);
805
+ if (isEnumerator(before, after, value)) continue;
782
806
  if (/^(1[0-9]{3}|20[0-9]{2})$/.test(digits) && !(m[1] ?? "").includes(",")) add("year", digits);
783
- else if (Number.isFinite(value))
807
+ else if (Number.isFinite(value)) {
808
+ const day = dayOfMonth(before, after, digits);
784
809
  add("number", digits, {
785
810
  approx: APPROXIMATE.test(unquoted.slice(Math.max(0, at - 24), at)),
786
- percent: /^\s*(?:%|percent\b)/i.test(unquoted.slice(at + m[0].length))
811
+ percent: /^\s*(?:%|percent\b)/i.test(unquoted.slice(at + m[0].length)),
812
+ ...day ? { day } : {}
787
813
  });
814
+ }
788
815
  }
789
- for (const m of unquoted.matchAll(
790
- /\b(January|February|March|April|May|June|July|August|September|October|November|December)\b/g
791
- )) {
816
+ for (const m of unquoted.matchAll(new RegExp(`\\b(${MONTH_NAME})\\b`, "g"))) {
792
817
  if (m.index !== 0 || m[1] !== "May") add("month", m[1] ?? "");
793
818
  }
794
819
  const raw = unquoted.split(/\s+/);
@@ -861,6 +886,11 @@ function claimFound(claim, evidence) {
861
886
  return new RegExp(`\\b\\d{4}-${month}\\b`).test(evidence);
862
887
  }
863
888
  if (kind !== "number") return false;
889
+ if (claim.day) {
890
+ const pad = (n) => String(n).padStart(2, "0");
891
+ const iso = `(?<!\\d)${claim.day.year ?? "\\d{4}"}-${pad(claim.day.month)}-${pad(Number(value))}(?!\\d)`;
892
+ if (new RegExp(iso).test(evidence)) return true;
893
+ }
864
894
  if (claim.clock) {
865
895
  const other = /^0\d:/.test(value) ? value.slice(1) : /^\d:/.test(value) ? `0${value}` : "";
866
896
  return other !== "" && claimPattern(kind, other).test(evidence);
@@ -1083,6 +1113,185 @@ function describeGroundingProblems(problems, max = 8) {
1083
1113
  return lines.join("\n");
1084
1114
  }
1085
1115
 
1116
+ // ../core/src/checks/html-text.ts
1117
+ var HTML_FILE = /\.x?html?$/i;
1118
+ var HTML_START = /^\s*(?:<!doctype\s+html|<html[\s>])/i;
1119
+ function isHtmlDocument(path, content) {
1120
+ return HTML_FILE.test(path) || HTML_START.test(content);
1121
+ }
1122
+ var HIDDEN = /<(head|title|style|script|noscript|template)\b[^>]*>[\s\S]*?<\/\1\s*>/gi;
1123
+ var COMMENT = /<!--[\s\S]*?(?:-->|$)/g;
1124
+ var TOKEN = /<(\/?)([a-z][\w:-]*)((?:[^>"']|"[^"]*"|'[^']*')*)>|<[!?][^>]*>|[^<]+|</gi;
1125
+ var BLOCK = /* @__PURE__ */ new Set([
1126
+ "address",
1127
+ "article",
1128
+ "aside",
1129
+ "blockquote",
1130
+ "body",
1131
+ "br",
1132
+ "caption",
1133
+ "center",
1134
+ "dd",
1135
+ "details",
1136
+ "dialog",
1137
+ "div",
1138
+ "dl",
1139
+ "dt",
1140
+ "fieldset",
1141
+ "figcaption",
1142
+ "figure",
1143
+ "footer",
1144
+ "form",
1145
+ "header",
1146
+ "hgroup",
1147
+ "hr",
1148
+ "html",
1149
+ "main",
1150
+ "nav",
1151
+ "ol",
1152
+ "p",
1153
+ "section",
1154
+ "summary",
1155
+ "table",
1156
+ "tbody",
1157
+ "tfoot",
1158
+ "thead",
1159
+ "ul"
1160
+ ]);
1161
+ var NAMED_ENTITIES = {
1162
+ amp: "&",
1163
+ lt: "<",
1164
+ gt: ">",
1165
+ quot: '"',
1166
+ apos: "'",
1167
+ nbsp: " ",
1168
+ ndash: "\u2013",
1169
+ mdash: "\u2014",
1170
+ hellip: "\u2026",
1171
+ lsquo: "\u2018",
1172
+ rsquo: "\u2019",
1173
+ ldquo: "\u201C",
1174
+ rdquo: "\u201D",
1175
+ middot: "\xB7",
1176
+ bull: "\u2022",
1177
+ rarr: "\u2192",
1178
+ larr: "\u2190",
1179
+ times: "\xD7",
1180
+ minus: "\u2212",
1181
+ deg: "\xB0",
1182
+ percnt: "%",
1183
+ euro: "\u20AC",
1184
+ pound: "\xA3",
1185
+ cent: "\xA2",
1186
+ yen: "\xA5",
1187
+ copy: "\xA9",
1188
+ reg: "\xAE",
1189
+ trade: "\u2122"
1190
+ };
1191
+ function decodeEntities(text) {
1192
+ return text.replace(/&(?:#(\d+)|#x([0-9a-f]+)|([a-z]+));/gi, (whole, dec, hex, name) => {
1193
+ if (dec || hex) {
1194
+ const code = dec ? Number(dec) : Number.parseInt(hex, 16);
1195
+ return code > 0 && code <= 1114111 ? String.fromCodePoint(code === 160 ? 32 : code) : whole;
1196
+ }
1197
+ return NAMED_ENTITIES[String(name).toLowerCase()] ?? whole;
1198
+ });
1199
+ }
1200
+ function attribute(attrs, name) {
1201
+ const m = new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, "i").exec(attrs);
1202
+ return m ? decodeEntities(m[1] ?? m[2] ?? m[3] ?? "") : null;
1203
+ }
1204
+ function htmlAsMarkdown(html) {
1205
+ const source = html.replace(COMMENT, "").replace(HIDDEN, "");
1206
+ const out = [];
1207
+ const lists = [];
1208
+ const links = [];
1209
+ let pre = 0;
1210
+ let cell = 0;
1211
+ let marker = -1;
1212
+ const newline = () => {
1213
+ if (cell > 0) {
1214
+ out.push(" ");
1215
+ return;
1216
+ }
1217
+ if (marker >= 0 && out.slice(marker).every((part) => !part.trim())) return;
1218
+ marker = -1;
1219
+ out.push("\n");
1220
+ };
1221
+ for (const m of source.matchAll(TOKEN)) {
1222
+ const [whole, slash, rawName, attrs = ""] = m;
1223
+ if (!rawName) {
1224
+ if (whole.startsWith("<") && whole.length > 1) continue;
1225
+ const text = decodeEntities(whole);
1226
+ out.push(pre > 0 ? text : text.replace(/\s+/g, " "));
1227
+ continue;
1228
+ }
1229
+ const name = rawName.toLowerCase();
1230
+ const closing = slash === "/";
1231
+ const heading = /^h([1-6])$/.exec(name);
1232
+ if (heading) {
1233
+ out.push(closing ? "\n" : `
1234
+ ${"#".repeat(Number(heading[1]))} `);
1235
+ } else if (name === "pre") {
1236
+ pre = Math.max(0, pre + (closing ? -1 : 1));
1237
+ out.push("\n```\n");
1238
+ } else if (name === "code") {
1239
+ if (pre === 0) out.push("`");
1240
+ } else if (name === "strong" || name === "b") {
1241
+ out.push("**");
1242
+ } else if (name === "ol" || name === "ul") {
1243
+ if (closing) lists.pop();
1244
+ else {
1245
+ const start = Number(attribute(attrs, "start"));
1246
+ lists.push({
1247
+ ordered: name === "ol",
1248
+ n: Number.isInteger(start) && start > 0 ? start - 1 : 0
1249
+ });
1250
+ }
1251
+ newline();
1252
+ } else if (name === "li") {
1253
+ if (!closing) {
1254
+ const list = lists.at(-1);
1255
+ out.push(list?.ordered ? `
1256
+ ${++list.n}. ` : "\n- ");
1257
+ marker = out.length;
1258
+ }
1259
+ } else if (name === "tr") {
1260
+ out.push(closing ? "\n" : "\n|");
1261
+ } else if (name === "td" || name === "th") {
1262
+ cell = Math.max(0, cell + (closing ? -1 : 1));
1263
+ out.push(closing ? " |" : " ");
1264
+ } else if (name === "a") {
1265
+ if (!closing) {
1266
+ links.push({ href: attribute(attrs, "href"), start: out.length });
1267
+ continue;
1268
+ }
1269
+ const link = links.pop();
1270
+ if (!link) continue;
1271
+ const text = out.splice(link.start).join("");
1272
+ if (link.href?.startsWith("#") && /^\s*\[?\d{1,3}\]?\s*$/.test(text)) {
1273
+ out.push(`[${text.replace(/[^\d]/g, "")}]`);
1274
+ } else if (link.href && !link.href.startsWith("#") && !/^javascript:/i.test(link.href)) {
1275
+ out.push(`[${text.trim()}](${link.href.replace(/\s/g, "%20")})`);
1276
+ } else out.push(text);
1277
+ } else if (BLOCK.has(name)) {
1278
+ newline();
1279
+ }
1280
+ }
1281
+ const lines = [];
1282
+ let fenced = false;
1283
+ for (const line of out.join("").split("\n")) {
1284
+ if (line === "```") fenced = !fenced;
1285
+ else if (fenced) {
1286
+ lines.push(line);
1287
+ continue;
1288
+ }
1289
+ const tidy = line.replace(/\s+/g, " ").trim();
1290
+ if (tidy) lines.push(tidy);
1291
+ }
1292
+ return lines.join("\n");
1293
+ }
1294
+
1086
1295
  // ../core/src/checks/workspace-exists.ts
1087
1296
  function createCitedPathChecker(ws) {
1088
1297
  let listing = null;
@@ -1120,9 +1329,19 @@ var INLINE_SOURCE = /\((?:source|sources|src)\s*:\s*([^)]+)\)/gi;
1120
1329
  var HAS_INLINE_SOURCE = /\((?:source|sources|src)\s*:/i;
1121
1330
  var BRACKETED_PATH = /\[((?:[\w.-]+\/)*[\w.-]+\.[a-z][a-z0-9]{0,5})\](?!\()/gi;
1122
1331
  var URL_LIKE = /^(?:[a-z][\w+.-]*:\/\/|mailto:)/i;
1332
+ var FILE_NAME = /\.(?:md|markdown|txt|csv|tsv|jsonl?|ya?ml|toml|ini|html?|xml|log|rst|pdf|docx?|pptx?|xlsx?|odt|odp|ods|rtf|epub|[cm]?[jt]sx?|py|rb|go|rs|java|kt|cs|cpp|c|h|sh|sql)$/i;
1123
1333
  var MAX_FOLDER_FILES = 50;
1124
1334
  var TEXT_FILE = /\.(?:md|markdown|txt|csv|tsv|json|ya?ml|html?|xml|log|rst)$/i;
1125
1335
  var BINARY_DOCUMENT = /\.(?:pdf|docx?|pptx?|xlsx?|odt|odp|ods|rtf|epub)$/i;
1336
+ var BARE_PARENTHETICAL = /(?<![\]\w])\(([^()\n]{1,240})\)/g;
1337
+ var FILE_TOKEN = /^(?:\.?\/)?(?:[\w.-]+\/)*[\w.-]+\.[a-z][a-z0-9]{0,5}(?::[\d:–-]+)?$/i;
1338
+ function bareFileNames(list) {
1339
+ const items = list.split(/[,;]|\band\b/).map((raw) => raw.trim().replace(/^`+|`+$/g, ""));
1340
+ const names = items.every(
1341
+ (item) => FILE_TOKEN.test(item) && FILE_NAME.test(item.replace(/:[\d:–-]+$/, "")) && !BINARY_DOCUMENT.test(item)
1342
+ );
1343
+ return names ? items : [];
1344
+ }
1126
1345
  function refFromLine(text) {
1127
1346
  const link = /\]\(([^)\s]+)\)/.exec(text)?.[1];
1128
1347
  if (link) return link;
@@ -1130,9 +1349,17 @@ function refFromLine(text) {
1130
1349
  if (ticked) return ticked;
1131
1350
  const url = /\b(?:https?:\/\/|knowledge:\/\/)[^\s)>\]]+/i.exec(text)?.[0];
1132
1351
  if (url) return url;
1133
- const path = /(?:^|\s)((?:[\w.-]+\/)*[\w.-]+\.[a-z][a-z0-9]{0,5})\b/i.exec(text)?.[1];
1352
+ const path = /(?:^|[\s(])((?:[\w.-]+\/)*[\w.-]+\.[a-z][a-z0-9]{0,5})\b/i.exec(text)?.[1];
1134
1353
  return path ?? null;
1135
1354
  }
1355
+ function tableReference(line) {
1356
+ if (!/^\s*\|/.test(line)) return null;
1357
+ const cells = line.trim().replace(/^\||\|$/g, "").split("|").map((cell) => cell.trim());
1358
+ const index = cells.findIndex((cell) => /^\[?\d{1,3}\]?\.?$/.test(cell));
1359
+ if (index === -1) return null;
1360
+ const ref = refFromLine(cells.slice(index + 1).join(" "));
1361
+ return ref ? { n: Number(/\d+/.exec(cells[index])[0]), ref } : null;
1362
+ }
1136
1363
  function splitReferences(markdown) {
1137
1364
  const lines = markdown.split("\n");
1138
1365
  const refs = /* @__PURE__ */ new Map();
@@ -1147,6 +1374,11 @@ function splitReferences(markdown) {
1147
1374
  continue;
1148
1375
  }
1149
1376
  if (level > 0) {
1377
+ const row = tableReference(line);
1378
+ if (row) {
1379
+ if (!refs.has(row.n)) refs.set(row.n, row.ref);
1380
+ continue;
1381
+ }
1150
1382
  const inline = [...line.matchAll(/\[(\d{1,3})\]\s*:?\s*/g)];
1151
1383
  if (inline.length > 1) {
1152
1384
  inline.forEach((m2, i) => {
@@ -1169,25 +1401,32 @@ function splitReferences(markdown) {
1169
1401
  }
1170
1402
  return { body: body.join("\n"), refs };
1171
1403
  }
1172
- function numberInlineSources(body, refs) {
1404
+ function sourceListReferences(markdown) {
1405
+ return splitReferences(markdown).refs;
1406
+ }
1407
+ function numberInlineSources(body, refs, citable) {
1173
1408
  const byRef = new Map([...refs].map(([n, ref]) => [ref.toLowerCase(), n]));
1174
1409
  let next = Math.max(0, ...refs.keys()) + 1;
1410
+ const numberFor = (ref) => {
1411
+ const key = ref.toLowerCase();
1412
+ let n = byRef.get(key);
1413
+ if (n === void 0) {
1414
+ n = next++;
1415
+ refs.set(n, ref);
1416
+ byRef.set(key, n);
1417
+ }
1418
+ return n;
1419
+ };
1175
1420
  const bracketed = body.replace(BRACKETED_PATH, (_whole, path) => `(source: ${path})`);
1176
- return bracketed.replace(INLINE_SOURCE, (_whole, list) => {
1177
- const numbers = [];
1178
- for (const raw of list.split(/[,;]/)) {
1179
- const ref = refFromLine(raw) ?? raw.trim().replace(/^`+|`+$/g, "");
1180
- if (!ref) continue;
1181
- const key = ref.toLowerCase();
1182
- let n = byRef.get(key);
1183
- if (n === void 0) {
1184
- n = next++;
1185
- refs.set(n, ref);
1186
- byRef.set(key, n);
1187
- }
1188
- numbers.push(n);
1189
- }
1190
- return numbers.length > 0 ? `[${numbers.join(", ")}]` : "";
1421
+ const noted = bracketed.replace(INLINE_SOURCE, (_whole, list) => {
1422
+ const items = list.split(/[,;]/).map((raw) => refFromLine(raw) ?? raw.trim().replace(/^`+|`+$/g, "")).filter((ref) => ref !== "");
1423
+ const isSource = (ref) => URL_LIKE.test(ref) || ref.includes("/") || FILE_NAME.test(ref);
1424
+ const named = items.some(isSource) ? items.filter(isSource) : items;
1425
+ return named.length > 0 ? `[${named.map(numberFor).join(", ")}]` : "";
1426
+ });
1427
+ return noted.replace(BARE_PARENTHETICAL, (whole, list) => {
1428
+ const cited = bareFileNames(list).filter((name) => citable.has(name));
1429
+ return cited.length > 0 ? `[${cited.map(numberFor).join(", ")}]` : whole;
1191
1430
  });
1192
1431
  }
1193
1432
  function declaredSources(body) {
@@ -1211,15 +1450,31 @@ function derivedFromNeighbors(sentences, i) {
1211
1450
  const sourced = sentences.slice(Math.max(0, i - DERIVATION_WINDOW), i + DERIVATION_WINDOW + 1).flatMap((s) => s.checks.filter((c) => c.kind === "number" && c.found)).map((c) => Number(c.value)).filter(Number.isFinite);
1212
1451
  return unfound.every((c) => isDerivedNumber(c.value, sourced));
1213
1452
  }
1214
- async function readSource(ws, ref) {
1453
+ var readable = (path, text) => isHtmlDocument(path, text) ? htmlAsMarkdown(text) : text;
1454
+ async function readSource(ws, ref, self) {
1215
1455
  const path = cleanCitedPath(ref);
1216
- if (!path) return null;
1456
+ const isSelf = (f) => cleanCitedPath(f).toLowerCase() === self;
1457
+ if (!path || isSelf(path)) return null;
1217
1458
  const text = await ws.read(path).catch(() => null);
1218
- if (text !== null) return text;
1459
+ if (text !== null) return readable(path, text);
1460
+ const listing = (await ws.list().catch(() => [])).filter((f) => !isSelf(f));
1461
+ if (!path.includes("/")) {
1462
+ const name = path.toLowerCase();
1463
+ const named = listing.filter((f) => cleanCitedPath(f).toLowerCase().split("/").at(-1) === name);
1464
+ if (named.length === 1) {
1465
+ const found = await ws.read(named[0]).catch(() => null);
1466
+ if (found !== null) return readable(named[0], found);
1467
+ }
1468
+ }
1219
1469
  const prefix = `${path.replace(/\/+$/, "")}/`;
1220
- const files = (await ws.list().catch(() => [])).filter((f) => cleanCitedPath(f).startsWith(prefix) && TEXT_FILE.test(f)).slice(0, MAX_FOLDER_FILES);
1470
+ const files = listing.filter((f) => cleanCitedPath(f).startsWith(prefix) && TEXT_FILE.test(f)).slice(0, MAX_FOLDER_FILES);
1221
1471
  if (files.length === 0) return null;
1222
- const parts = await Promise.all(files.map((f) => ws.read(f).catch(() => null)));
1472
+ const parts = await Promise.all(
1473
+ files.map(async (f) => {
1474
+ const part = await ws.read(f).catch(() => null);
1475
+ return part === null ? null : readable(f, part);
1476
+ })
1477
+ );
1223
1478
  const joined = parts.filter((p) => p !== null).join("\n\n");
1224
1479
  return joined.length > 0 ? joined : null;
1225
1480
  }
@@ -1236,12 +1491,28 @@ async function claimsGrounded(ws, file, opts = {}) {
1236
1491
  sources: { read: [], missing: [], unverifiable: [] },
1237
1492
  problems: []
1238
1493
  };
1239
- const content = await ws.read(file);
1240
- if (content === null) {
1494
+ const raw = await ws.read(file);
1495
+ if (raw === null) {
1241
1496
  return { ...empty, ok: false, detail: `${file} not found \u2014 write the deliverable first.` };
1242
1497
  }
1243
- const { body, refs } = splitReferences(content);
1244
- const text = numberInlineSources(body, refs);
1498
+ const self = cleanCitedPath(file).toLowerCase();
1499
+ const sourceTexts = /* @__PURE__ */ new Map();
1500
+ const source = (ref) => {
1501
+ let text2 = sourceTexts.get(ref);
1502
+ if (!text2) {
1503
+ text2 = readSource(ws, ref, self);
1504
+ sourceTexts.set(ref, text2);
1505
+ }
1506
+ return text2;
1507
+ };
1508
+ const { body, refs } = splitReferences(readable(file, raw));
1509
+ const citable = /* @__PURE__ */ new Set();
1510
+ for (const m of body.matchAll(BARE_PARENTHETICAL)) {
1511
+ for (const name of bareFileNames(m[1])) {
1512
+ if (!citable.has(name) && await source(name) !== null) citable.add(name);
1513
+ }
1514
+ }
1515
+ const text = numberInlineSources(body, refs, citable);
1245
1516
  const evidence = [];
1246
1517
  const opaque = /* @__PURE__ */ new Set();
1247
1518
  const read = [];
@@ -1253,12 +1524,12 @@ async function claimsGrounded(ws, file, opts = {}) {
1253
1524
  unverifiable.push(ref);
1254
1525
  continue;
1255
1526
  }
1256
- const source = await readSource(ws, ref);
1257
- if (source === null) {
1527
+ const sourceText = await source(ref);
1528
+ if (sourceText === null) {
1258
1529
  missing.push(ref);
1259
1530
  continue;
1260
1531
  }
1261
- evidence.push({ n, text: source, ref });
1532
+ evidence.push({ n, text: sourceText, ref });
1262
1533
  read.push(ref);
1263
1534
  }
1264
1535
  let extra = Math.max(0, ...refs.keys()) + 1;
@@ -1266,9 +1537,9 @@ async function claimsGrounded(ws, file, opts = {}) {
1266
1537
  if (refs.size > 0 && [...refs.values()].some((r) => r.toLowerCase() === ref.toLowerCase())) {
1267
1538
  continue;
1268
1539
  }
1269
- const source = await readSource(ws, ref);
1270
- if (source === null) continue;
1271
- evidence.push({ n: extra++, text: source, ref });
1540
+ const sourceText = await source(ref);
1541
+ if (sourceText === null) continue;
1542
+ evidence.push({ n: extra++, text: sourceText, ref });
1272
1543
  read.push(ref);
1273
1544
  }
1274
1545
  const grounding = groundText(text, evidence, {
@@ -1732,6 +2003,18 @@ function extractCitations(text, re) {
1732
2003
  function cleanCitation(raw) {
1733
2004
  return raw.trim().replace(/^[<'"`(]+/, "").replace(/[>'"`).,;:]+$/, "");
1734
2005
  }
2006
+ var PROPOSED_MARKER = /\b(?:new|creates?|created|creating|to be (?:added|created)|will (?:be )?(?:add(?:ed)?|create[ds]?))\b/i;
2007
+ function proposedCitations(content, re) {
2008
+ const proposed = /* @__PURE__ */ new Set();
2009
+ for (const line of stripFencedBlocks(content).split("\n")) {
2010
+ if (!PROPOSED_MARKER.test(line)) continue;
2011
+ for (const cite of extractCitations(line, re)) {
2012
+ const clean = normalizeForKnownMatch(cleanCitation(cite));
2013
+ if (clean) proposed.add(clean);
2014
+ }
2015
+ }
2016
+ return proposed;
2017
+ }
1735
2018
  function normalizeForKnownMatch(p) {
1736
2019
  return p.trim().replace(/\\/g, "/").replace(/^\.\//, "").replace(/^\//, "").replace(/^workspace\//i, "").replace(/\/+$/, "").toLowerCase();
1737
2020
  }
@@ -1774,6 +2057,7 @@ async function citationsResolve(ws, file, opts = {}) {
1774
2057
  const citedPathExists = createCitedPathChecker(ws);
1775
2058
  const corpus = opts.corpus ? new Set(opts.corpus.map((c) => c.toLowerCase())) : null;
1776
2059
  const known = new Set((opts.knownPaths ?? []).map(normalizeForKnownMatch).filter(Boolean));
2060
+ const proposed = opts.proposed ? proposedCitations(content, re) : /* @__PURE__ */ new Set();
1777
2061
  const resolved = [];
1778
2062
  const unresolved = [];
1779
2063
  const urls = [];
@@ -1790,8 +2074,9 @@ async function citationsResolve(ws, file, opts = {}) {
1790
2074
  continue;
1791
2075
  }
1792
2076
  if (corpus?.has(c.toLowerCase()) || await citedPathExists(c)) resolved.push(c);
1793
- else if (known.has(normalizeForKnownMatch(c)) || globMatchesKnown(c, known)) forgiven.push(c);
1794
- else unresolved.push(c);
2077
+ else if (known.has(normalizeForKnownMatch(c)) || globMatchesKnown(c, known) || proposed.has(normalizeForKnownMatch(c))) {
2078
+ forgiven.push(c);
2079
+ } else unresolved.push(c);
1795
2080
  }
1796
2081
  if (cites.length - forgiven.length < min) {
1797
2082
  return {
@@ -3470,6 +3755,7 @@ export {
3470
3755
  resolveRelative,
3471
3756
  runSniff,
3472
3757
  securityReport,
3758
+ sourceListReferences,
3473
3759
  standaloneJsParses,
3474
3760
  tableShape,
3475
3761
  totalMinBytes,
package/dist/page.d.ts CHANGED
@@ -357,28 +357,80 @@ interface GezelActionFormOptions {
357
357
  /** A declared page tool; ordinary validation and write policy still apply. */
358
358
  tool: string;
359
359
  fields: GezelActionField[];
360
+ /**
361
+ * `dialog` draws a key that opens the form in a modal; `inline` is an always-open
362
+ * form for a settings panel; `disclosure` (the default) is an expandable card.
363
+ * Fixed when the form is created. Hosts before component version 2 draw a disclosure.
364
+ */
365
+ presentation?: 'disclosure' | 'dialog' | 'inline';
366
+ /** Dialog only: the key's label when it should differ from the dialog title. */
367
+ buttonLabel?: string;
368
+ /** Dialog only: draw the key as the view's one filled primary action. */
369
+ primary?: boolean;
370
+ /** Dialog only: false hides the key, for a dialog the page opens with `open()` from its own row controls. */
371
+ trigger?: boolean;
360
372
  submitLabel?: string;
361
373
  successMessage?: string;
374
+ /** Disclosure only: start expanded. */
362
375
  open?: boolean;
363
376
  clearOnSave?: boolean;
364
377
  /** Map form fields into the tool's declared input, for example one card into a cards array. */
365
378
  mapInput?: (values: Record<string, string | number>) => Record<string, unknown>;
366
379
  onSaved?: (result: GezelPageToolResult) => void | Promise<void>;
367
380
  }
381
+ interface GezelActionFormHandle extends GezelPageComponent<GezelActionFormOptions> {
382
+ /**
383
+ * Open the dialog (or expand the disclosure) and focus its first field. Passing
384
+ * values first resets every field to its default, then fills the named ones, so a
385
+ * row's Edit control can open the form for that record. Version 2.
386
+ */
387
+ open?(values?: Record<string, string | number>): void;
388
+ /** Close the dialog or collapse the disclosure. Ignored while a save is pending. Version 2. */
389
+ close?(): void;
390
+ /** Reset every field to its default and then fill the named ones; a settings panel shows current values this way. Version 2. */
391
+ reset?(values?: Record<string, string | number>): void;
392
+ }
393
+ interface GezelTab {
394
+ id: string;
395
+ label: string;
396
+ /** The page-owned element this tab shows; the component hides the others. */
397
+ panel: string | HTMLElement;
398
+ /** A short count beside the label, such as open items. Empty and 0 are not drawn. */
399
+ badge?: string | number;
400
+ }
401
+ interface GezelTabsOptions {
402
+ tabs: GezelTab[];
403
+ /** Accessible name of the tab row. */
404
+ label?: string;
405
+ /** The first tab when neither this nor a remembered choice applies. */
406
+ selected?: string;
407
+ /** False stops recording the choice in the page URL's `#tab=` fragment. */
408
+ remember?: boolean;
409
+ onChange?: (id: string) => void;
410
+ }
411
+ interface GezelTabsHandle extends GezelPageComponent<GezelTabsOptions> {
412
+ select(id: string): void;
413
+ selected(): string | null;
414
+ }
368
415
  interface GezelCollectionFilterOptions {
369
416
  container: string | HTMLElement;
370
417
  selector: string;
371
418
  label?: string;
372
419
  placeholder?: string;
420
+ /** Hide the search box while the collection has fewer items than this and nothing is typed. Version 2. */
421
+ minItems?: number;
373
422
  }
374
423
  interface GezelPageComponents {
375
- version: 1;
424
+ /** 2 adds dialog and inline action forms and `tabs`. */
425
+ version: 1 | 2;
376
426
  /** Searches rendered items, retaining their controls and refreshing after data updates. */
377
427
  collectionFilter(target: string | HTMLElement, options: GezelCollectionFilterOptions): GezelPageComponent<GezelCollectionFilterOptions>;
378
428
  /** Wrap existing content, retaining its DOM, and add a responsive fullscreen companion. */
379
429
  appLayout(content: string | HTMLElement, options?: GezelAppLayoutOptions): GezelPageComponent<GezelAppLayoutOptions>;
380
430
  /** Accessible, validated form invoking one declared action, with busy/error/success states. */
381
- actionForm(target: string | HTMLElement, options: GezelActionFormOptions): GezelPageComponent<GezelActionFormOptions>;
431
+ actionForm(target: string | HTMLElement, options: GezelActionFormOptions): GezelActionFormHandle;
432
+ /** Underline tabs over page-owned panels: keyboard support, badges, and a remembered choice. Version 2. */
433
+ tabs?(target: string | HTMLElement, options: GezelTabsOptions): GezelTabsHandle;
382
434
  /** Native, project-bound chat. No transcript or send API is exposed to page scripts. */
383
435
  chat(target: string | HTMLElement, options?: GezelChatOptions): GezelPageComponent<GezelChatOptions> & {
384
436
  ready: Promise<void>;
@@ -482,4 +534,4 @@ declare global {
482
534
  }
483
535
  }
484
536
 
485
- export { GEZEL_PAGE_API_VERSION, type GezelActionField, type GezelActionFormOptions, type GezelAppLayoutOptions, type GezelChatOptions, type GezelCollectionFilterOptions, type GezelDemoConversation, type GezelDemoConversationContext, type GezelDemoOptions, type GezelDemoReply, type GezelFileAdderOptions, type GezelFileCardOptions, type GezelImportResult, type GezelImportTarget, type GezelPageApi, type GezelPageComponent, type GezelPageComponents, type GezelPageDataApi, type GezelPageDirEntry, type GezelPageError, type GezelPageErrorCode, type GezelPageFile, type GezelPageInfo, type GezelPageMode, type GezelPageReadOptions, type GezelPageReadSource, type GezelPageSourceOptions, type GezelPageTable, type GezelPageTableQuery, type GezelPageTableSchema, type GezelPageTablesApi, type GezelPageTheme, type GezelPageToolReaction, type GezelPageToolResult, type GezelPageToolsApi, type GezelPageUiApi, type GezelPageWatchEvent, type GezelPageWatchOptions };
537
+ export { GEZEL_PAGE_API_VERSION, type GezelActionField, type GezelActionFormHandle, type GezelActionFormOptions, type GezelAppLayoutOptions, type GezelChatOptions, type GezelCollectionFilterOptions, type GezelDemoConversation, type GezelDemoConversationContext, type GezelDemoOptions, type GezelDemoReply, type GezelFileAdderOptions, type GezelFileCardOptions, type GezelImportResult, type GezelImportTarget, type GezelPageApi, type GezelPageComponent, type GezelPageComponents, type GezelPageDataApi, type GezelPageDirEntry, type GezelPageError, type GezelPageErrorCode, type GezelPageFile, type GezelPageInfo, type GezelPageMode, type GezelPageReadOptions, type GezelPageReadSource, type GezelPageSourceOptions, type GezelPageTable, type GezelPageTableQuery, type GezelPageTableSchema, type GezelPageTablesApi, type GezelPageTheme, type GezelPageToolReaction, type GezelPageToolResult, type GezelPageToolsApi, type GezelPageUiApi, type GezelPageWatchEvent, type GezelPageWatchOptions, type GezelTab, type GezelTabsHandle, type GezelTabsOptions };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bendyline/gezel-sdk",
3
- "version": "1.1.13",
3
+ "version": "1.1.14",
4
4
  "description": "SDK for scripts that run in the Gezel sandbox: the gezel object and the defineScript helper.",
5
5
  "license": "MIT",
6
6
  "keywords": [
@@ -63,7 +63,7 @@
63
63
  "!dist/**/*.map"
64
64
  ],
65
65
  "devDependencies": {
66
- "@bendyline/gezel": "1.2.13",
66
+ "@bendyline/gezel": "1.2.14",
67
67
  "tsup": "^8.5.1",
68
68
  "typescript": "^6.0.3",
69
69
  "vitest": "^4.1.10"