@floless/app 0.147.0 → 0.148.0

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.
@@ -1634,7 +1634,7 @@ function appVersion() {
1634
1634
  return resolveVersion({
1635
1635
  isSea: isSea(),
1636
1636
  sqVersionXml: readSqVersionXml(),
1637
- define: true ? "0.147.0" : void 0,
1637
+ define: true ? "0.148.0" : void 0,
1638
1638
  pkgVersion: readPkgVersion()
1639
1639
  });
1640
1640
  }
@@ -1650,7 +1650,7 @@ function resolveChannel(s) {
1650
1650
  function appChannel() {
1651
1651
  return resolveChannel({
1652
1652
  isSea: isSea(),
1653
- define: true ? "0.147.0" : void 0,
1653
+ define: true ? "0.148.0" : void 0,
1654
1654
  // argv[1] is the entry the runtime actually loaded (…/dist/floless-server.cjs), which is what
1655
1655
  // carries the npx cache prefix. Absent under the SEA exe, which never reaches the npx branch.
1656
1656
  modulePath: process.argv[1]
@@ -101777,9 +101777,48 @@ function memberLabel(member) {
101777
101777
  const id2 = String(member.id ?? "");
101778
101778
  return profile ? `${profile} (${id2})` : id2;
101779
101779
  }
101780
+ function cutOutsideValues(text9, max2) {
101781
+ if (text9.length <= max2) return text9;
101782
+ if (max2 < 1) return "";
101783
+ const values2 = [...text9.matchAll(FEET_INCHES_VALUE)].map((m) => [m.index, m.index + m[0].length]);
101784
+ const outside = (at) => values2.every(([start2, end]) => at <= start2 || at >= end);
101785
+ for (let at = Math.min(max2 - 1, text9.length); at > 0; at -= 1) {
101786
+ if (!/\s/.test(text9[at] ?? "") || !outside(at)) continue;
101787
+ const kept = text9.slice(0, at).trimEnd();
101788
+ if (kept) return `${kept}\u2026`;
101789
+ }
101790
+ return "\u2026";
101791
+ }
101780
101792
  function sentence(parts) {
101781
101793
  const text9 = parts.filter(Boolean).join(" ").replace(/\s+/g, " ").trim();
101782
- return truncateAtWord(text9, MAX_QUESTION2);
101794
+ return cutOutsideValues(text9, MAX_QUESTION2);
101795
+ }
101796
+ function sentenceKeepingEnds(ask2, label2, reason, list3) {
101797
+ const clean3 = (value) => value ? value.replace(/\s+/g, " ").trim() : "";
101798
+ const join131 = (...parts) => parts.filter(Boolean).join(" ");
101799
+ const tail2 = clean3(list3);
101800
+ const why = clean3(reason);
101801
+ const labels = [clean3(label2), ...labelCuts(clean3(label2))];
101802
+ const render = (shown, withReason) => join131(clean3(ask2(shown)), withReason ? why : "", tail2);
101803
+ for (const withReason of why ? [true, false] : [false]) {
101804
+ for (const shown of labels) {
101805
+ const question = render(shown, withReason);
101806
+ if (question.length <= MAX_QUESTION2) return question;
101807
+ }
101808
+ }
101809
+ return cutOutsideValues(render("\u2026", false), MAX_QUESTION2);
101810
+ }
101811
+ function labelCuts(label2) {
101812
+ const values2 = [...label2.matchAll(FEET_INCHES_VALUE)].map((m) => [m.index, m.index + m[0].length]);
101813
+ const outside = (at) => values2.every(([start2, end]) => at <= start2 || at >= end);
101814
+ const cuts = [];
101815
+ for (let at = label2.length - 1; at > 0; at -= 1) {
101816
+ if (!/\s/.test(label2[at] ?? "") || !outside(at)) continue;
101817
+ const kept = label2.slice(0, at).trimEnd();
101818
+ if (kept) cuts.push(`${kept}\u2026`);
101819
+ }
101820
+ cuts.push("\u2026");
101821
+ return [...new Set(cuts)];
101783
101822
  }
101784
101823
  function sheetList(checked2) {
101785
101824
  if (!checked2.length) return false;
@@ -101865,7 +101904,7 @@ function deriveContractRfis(model) {
101865
101904
  kind: "unknown-elevation",
101866
101905
  status: "open",
101867
101906
  silent: false,
101868
- question: sentence([`What is the top-of-steel elevation at the ${fact.end === 0 ? "start" : "end"} of ${memberLabel(raw)}?`, fact.why, sheetList(fact.checked)]),
101907
+ question: sentenceKeepingEnds((shown) => `What is the top-of-steel elevation at the ${fact.end === 0 ? "start" : "end"} of ${shown}?`, memberLabel(raw), fact.why, sheetList(fact.checked)),
101869
101908
  subjects: [{ memberId: raw.id, end: fact.end }],
101870
101909
  checked: fact.checked,
101871
101910
  drawingTarget: targets[0],
@@ -101955,11 +101994,12 @@ function deriveContractRfis(model) {
101955
101994
  id: rfiId(gapKey),
101956
101995
  gapKey,
101957
101996
  kind: "unknown-elevation",
101958
- question: sentence([
101959
- isAssumed(z11) ? `Is the top-of-steel elevation at the ${end === 0 ? "start" : "end"} of ${label2} correct?` : `What is the top-of-steel elevation at the ${end === 0 ? "start" : "end"} of ${label2}?`,
101997
+ question: sentenceKeepingEnds(
101998
+ (shown) => isAssumed(z11) ? `Is the top-of-steel elevation at the ${end === 0 ? "start" : "end"} of ${shown} correct?` : `What is the top-of-steel elevation at the ${end === 0 ? "start" : "end"} of ${shown}?`,
101999
+ label2,
101960
102000
  why || "The read did not record what the set says about it.",
101961
102001
  sheetList(checked2)
101962
- ]),
102002
+ ),
101963
102003
  subjects: [{ memberId: raw.id, end }],
101964
102004
  checked: checked2,
101965
102005
  silent: !why,
@@ -102434,7 +102474,7 @@ function boundRfis(all) {
102434
102474
  }
102435
102475
  return { rows: kept, omitted };
102436
102476
  }
102437
- var import_node_crypto29, ID_HEX, MAX_QUESTION2, MAX_LEGACY_GAP_ALIASES, RFI_CLASS_LIMITS, MAX_NAMED_VALUES, MAX_GROUP_SUBJECTS, isObj8, rfiId, TEMPLATE_REASON, isUnknown, isAssumed, isUnresolvedElevation, markerGapIdentity, untracedMemberGapKey, unknownSizeGapKey, rfiIdForGapKey, mm3, MAX_NAMED_ID, namedId, usableNote;
102477
+ var import_node_crypto29, ID_HEX, MAX_QUESTION2, MAX_LEGACY_GAP_ALIASES, RFI_CLASS_LIMITS, MAX_NAMED_VALUES, MAX_GROUP_SUBJECTS, isObj8, rfiId, TEMPLATE_REASON, isUnknown, isAssumed, isUnresolvedElevation, FEET_INCHES_VALUE, markerGapIdentity, untracedMemberGapKey, unknownSizeGapKey, rfiIdForGapKey, mm3, MAX_NAMED_ID, namedId, usableNote;
102438
102478
  var init_steel_read_rfis = __esm({
102439
102479
  "steel-read-rfis.ts"() {
102440
102480
  "use strict";
@@ -102504,6 +102544,7 @@ var init_steel_read_rfis = __esm({
102504
102544
  isUnknown = (z11) => isObj8(z11) && z11.unknown === true;
102505
102545
  isAssumed = (z11) => isObj8(z11) && z11.assumed === true;
102506
102546
  isUnresolvedElevation = (z11) => isUnknown(z11) || isAssumed(z11);
102547
+ FEET_INCHES_VALUE = /\d+\s*'\s*-?\s*\d+(?:\s+\d+\/\d+)?\s*"?|\d+\s+\d+\/\d+\s*"/g;
102507
102548
  markerGapIdentity = (kind2, sourceHash, pageId, elementId) => compositeGapIdentity(kind2, [sourceHash, pageId, elementId]);
102508
102549
  untracedMemberGapKey = (observationId, memberId) => compositeGapIdentity("untraced-member", [observationId, memberId]).gapKey;
102509
102550
  unknownSizeGapKey = (memberId) => `unknown-size:${memberId}`;
@@ -103264,18 +103305,25 @@ function placeUnprovenElevation(input2) {
103264
103305
  return { kind: "unplaceable", reason: "plan-states-no-elevation" };
103265
103306
  }
103266
103307
  const elevationMm = input2.plan.elevationMm;
103308
+ const serverWhy = input2.plan.basis === "level-with-other-end" ? levelledToOtherEndWhy(cited.sheet) : placedAtPlanWhy(cited.sheet);
103267
103309
  return {
103268
103310
  kind: "place",
103269
103311
  elevation: {
103270
103312
  known: elevationMm,
103271
103313
  assumed: true,
103272
- why: input2.plan.basis === "level-with-other-end" ? levelledToOtherEndWhy(cited.sheet) : placedAtPlanWhy(cited.sheet),
103314
+ why: withReaderAccount(serverWhy, input2.elevation),
103273
103315
  checked: mergeChecked(cited, input2.elevation),
103274
103316
  ...carriedCandidates(input2.elevation)
103275
103317
  },
103276
103318
  placed: { discardedZ: "known" in input2.elevation ? input2.elevation.known : elevationMm, cited }
103277
103319
  };
103278
103320
  }
103321
+ function withReaderAccount(serverWhy, elevation2) {
103322
+ if (!("unknown" in elevation2)) return serverWhy;
103323
+ const account = typeof elevation2.why === "string" ? elevation2.why.replace(/\s+/g, " ").trim() : "";
103324
+ if (!account || TEMPLATE_REASON.test(account)) return serverWhy;
103325
+ return `${serverWhy}${READER_ACCOUNT_LEAD}${account}`;
103326
+ }
103279
103327
  function carriedCandidates(elevation2) {
103280
103328
  return "unknown" in elevation2 && elevation2.candidates?.length ? { candidates: elevation2.candidates } : {};
103281
103329
  }
@@ -103294,14 +103342,16 @@ function citablePage(observations2, pageOf) {
103294
103342
  }
103295
103343
  return null;
103296
103344
  }
103297
- var MAX_CHECKED_PAGES, placedAtPlanWhy, levelledToOtherEndWhy, unplaceableWhy;
103345
+ var MAX_CHECKED_PAGES, placedAtPlanWhy, levelledToOtherEndWhy, READER_ACCOUNT_LEAD, unplaceableWhy;
103298
103346
  var init_elevation_resolution = __esm({
103299
103347
  "elevation-resolution.ts"() {
103300
103348
  "use strict";
103301
103349
  init_steel_model_v2();
103350
+ init_steel_read_rfis();
103302
103351
  MAX_CHECKED_PAGES = 20;
103303
- placedAtPlanWhy = (sheet) => `The drawings do not settle this endpoint's height: ${sheet} is a plan view and nothing read there gives it an elevation. It has been placed at a plan elevation so the member is built and can be seen, but a plan elevation is a cut plane, not a stated top of steel \u2014 it is unverified until someone confirms it.`;
103304
- levelledToOtherEndWhy = (sheet) => `The drawings do not settle this endpoint's height: ${sheet} is a plan view and nothing read there gives it an elevation. The other end of this member does have one, so this end has been levelled to it \u2014 which assumes the member is flat, and the drawings do not say that. It is unverified until someone confirms it.`;
103352
+ placedAtPlanWhy = (sheet) => `The drawings do not settle this endpoint's height: ${sheet} is a plan view and no height read there was tied to this end. It has been placed at a plan elevation so the member is built and can be seen, but a plan elevation is a cut plane, not a stated top of steel \u2014 it is unverified until someone confirms it.`;
103353
+ levelledToOtherEndWhy = (sheet) => `The drawings do not settle this endpoint's height: ${sheet} is a plan view and no height read there was tied to this end. The other end of this member does have one, so this end has been levelled to it \u2014 which assumes the member is flat, and the drawings do not say that. It is unverified until someone confirms it.`;
103354
+ READER_ACCOUNT_LEAD = " The read's own account: ";
103305
103355
  unplaceableWhy = (sheet) => `The drawings do not settle this endpoint's height, and this model states no plan elevation to place it at either \u2014 ${sheet} is the sheet it was read on. The value submitted with the read has been kept so the member is built, but nothing on the drawings supports it and it is unverified until someone confirms it.`;
103306
103356
  }
103307
103357
  });
@@ -116472,9 +116522,10 @@ function drawnAtNote(value, basis2, sheet) {
116472
116522
  }
116473
116523
  }
116474
116524
  function placementBasis(why, sheet) {
116475
- if (why === placedAtPlanWhy(sheet)) return "plan";
116476
- if (why === levelledToOtherEndWhy(sheet)) return "level-with-other-end";
116477
- if (why === unplaceableWhy(sheet)) return "submitted";
116525
+ const is = (sentence2) => typeof why === "string" && (why === sentence2 || why.startsWith(`${sentence2}${READER_ACCOUNT_LEAD}`));
116526
+ if (is(placedAtPlanWhy(sheet))) return "plan";
116527
+ if (is(levelledToOtherEndWhy(sheet))) return "level-with-other-end";
116528
+ if (is(unplaceableWhy(sheet))) return "submitted";
116478
116529
  return "unstated";
116479
116530
  }
116480
116531
  function uncheckedBeyondFirst(candidate2) {
@@ -117867,7 +117918,7 @@ function deleteRequest(id2) {
117867
117918
  }
117868
117919
  }
117869
117920
  }
117870
- clearRequestScratch(id2);
117921
+ clearRequestScratch(id2, "its request is being deleted");
117871
117922
  (0, import_node_fs44.rmSync)((0, import_node_path39.join)(REQUESTS_DIR, file2));
117872
117923
  clearRequestSettlement(id2);
117873
117924
  return true;
@@ -117876,10 +117927,15 @@ function requestIdFromFile(file2) {
117876
117927
  const match = /__([^_/\\]+)\.json$/i.exec(file2);
117877
117928
  return match && REQUEST_ID2.test(match[1]) ? match[1] : null;
117878
117929
  }
117879
- function clearRequestScratch(id2) {
117930
+ function clearRequestScratch(id2, reason) {
117880
117931
  if (!REQUEST_ID2.test(id2)) return true;
117881
117932
  try {
117933
+ const existed = (0, import_node_fs44.existsSync)(requestScratchPath(id2));
117882
117934
  const outcome = removeRequestScratch(id2);
117935
+ if (existed && outcome.removed) {
117936
+ console.log(`[request-work] removed the scratch directory of request ${id2}: ${reason}.`);
117937
+ }
117938
+ if (outcome.removed) unmeasurableScratch.delete(id2);
117883
117939
  if (!outcome.removed) {
117884
117940
  console.warn(outcome.retained.length ? `[floless-store] kept ${outcome.retained.length} named diagnostic(s) under ${outcome.path}: ${outcome.retained.join(", ")}` : `[floless-store] could not remove the scratch directory ${outcome.path} for request ${id2}`);
117885
117941
  }
@@ -117906,7 +117962,7 @@ function sweepIdleRequestScratch(options2) {
117906
117962
  if (id2.toLowerCase() === keep) continue;
117907
117963
  try {
117908
117964
  if (!hasRequestFile(id2)) {
117909
- if (clearRequestScratch(id2)) removed.push(id2);
117965
+ if (clearRequestScratch(id2, "it has no request row")) removed.push(id2);
117910
117966
  continue;
117911
117967
  }
117912
117968
  const request = getRequest(id2);
@@ -117918,18 +117974,35 @@ function sweepIdleRequestScratch(options2) {
117918
117974
  continue;
117919
117975
  }
117920
117976
  const state3 = options2.liveness(request);
117921
- if (state3 === "live") continue;
117922
- if (state3 === "unobservable") {
117977
+ let reason;
117978
+ if (state3 === "gone") {
117979
+ reason = "its conversation no longer exists";
117980
+ } else if (state3 === "idle" || state3 === "unobservable") {
117923
117981
  const newest = activity(id2);
117924
- if (newest === null || now2 - newest < idleMs) continue;
117982
+ if (newest !== null) unmeasurableScratch.delete(id2);
117983
+ if (newest === null) {
117984
+ if (!unmeasurableScratch.has(id2)) {
117985
+ unmeasurableScratch.add(id2);
117986
+ console.warn(`[request-work] cannot tell when request ${id2}'s scratch directory was last written; keeping it.`);
117987
+ }
117988
+ continue;
117989
+ }
117990
+ if (now2 - newest < idleMs) continue;
117991
+ reason = `${state3 === "idle" ? "its conversation is settled" : "the server cannot observe its reader"} and nothing in it has been written for ${formatIdle(now2 - newest)}`;
117992
+ } else {
117993
+ continue;
117925
117994
  }
117926
- if (clearRequestScratch(id2)) removed.push(id2);
117995
+ if (clearRequestScratch(id2, reason)) removed.push(id2);
117927
117996
  } catch (error62) {
117928
117997
  console.warn(`[floless-store] cannot decide whether request ${id2}'s scratch is idle; leaving it:`, error62);
117929
117998
  }
117930
117999
  }
117931
118000
  return removed;
117932
118001
  }
118002
+ function formatIdle(ms2) {
118003
+ const minutes = Math.floor(ms2 / 6e4);
118004
+ return minutes >= 120 ? `${Math.floor(minutes / 60)} h ${minutes % 60} min` : `${minutes} min`;
118005
+ }
117933
118006
  function hasRequestFile(id2) {
117934
118007
  if (!(0, import_node_fs44.existsSync)(REQUESTS_DIR)) return false;
117935
118008
  return (0, import_node_fs44.readdirSync)(REQUESTS_DIR).some((f) => f.endsWith(`__${id2}.json`));
@@ -118014,7 +118087,7 @@ function clearCapturedRequests(snapshot2, protectRequest = () => false) {
118014
118087
  continue;
118015
118088
  }
118016
118089
  const orphanScratchId = requestIdFromFile(file2);
118017
- if (orphanScratchId) clearRequestScratch(orphanScratchId);
118090
+ if (orphanScratchId) clearRequestScratch(orphanScratchId, "its unreadable request row is being cleared");
118018
118091
  try {
118019
118092
  (0, import_node_fs44.rmSync)((0, import_node_path39.join)(REQUESTS_DIR, file2));
118020
118093
  removed++;
@@ -118072,7 +118145,7 @@ function decodeSnapshots(inputs) {
118072
118145
  return { buf, ext, role: s.role ?? "locator" };
118073
118146
  });
118074
118147
  }
118075
- var import_node_crypto37, import_node_fs44, import_node_os25, import_node_path39, ROOT4, TEMPLATES_FILE, REQUESTS_DIR, REQUEST_SETTLEMENTS_DIR, REQUEST_SETTLEMENT_HISTORY_DIR, PROMOTION_SETTLEMENT_INDEX, PROMOTION_SETTLEMENT_QUARANTINE_DIR, REQUEST_DISCARDS_DIR, REQUEST_DISCARD_HISTORY_DIR, REQUEST_PUBLICATION_STALE_MS, STEEL_FAVS_FILE, TYPE_SET, requestPublicationHookForTest, REQUEST_ID2, SETTLEMENT_HASH, SETTLEMENT_TEXT, SETTLEMENT_MAX_BYTES, SETTLEMENT_INDEX_MAX_BYTES, SETTLEMENT_DIAGNOSTIC_MAX, PROMOTION_SETTLEMENT_MAX_HISTORY, PROMOTION_SETTLEMENT_MAX_AGE_MS, emptyPromotionIndex, UNOBSERVABLE_SCRATCH_IDLE_MS, unreadableScratchRows, flolessRoot, SnapshotError, MAX_SNAPSHOTS, MAX_BYTES3;
118148
+ var import_node_crypto37, import_node_fs44, import_node_os25, import_node_path39, ROOT4, TEMPLATES_FILE, REQUESTS_DIR, REQUEST_SETTLEMENTS_DIR, REQUEST_SETTLEMENT_HISTORY_DIR, PROMOTION_SETTLEMENT_INDEX, PROMOTION_SETTLEMENT_QUARANTINE_DIR, REQUEST_DISCARDS_DIR, REQUEST_DISCARD_HISTORY_DIR, REQUEST_PUBLICATION_STALE_MS, STEEL_FAVS_FILE, TYPE_SET, requestPublicationHookForTest, REQUEST_ID2, SETTLEMENT_HASH, SETTLEMENT_TEXT, SETTLEMENT_MAX_BYTES, SETTLEMENT_INDEX_MAX_BYTES, SETTLEMENT_DIAGNOSTIC_MAX, PROMOTION_SETTLEMENT_MAX_HISTORY, PROMOTION_SETTLEMENT_MAX_AGE_MS, emptyPromotionIndex, UNOBSERVABLE_SCRATCH_IDLE_MS, unreadableScratchRows, unmeasurableScratch, flolessRoot, SnapshotError, MAX_SNAPSHOTS, MAX_BYTES3;
118076
118149
  var init_floless_store = __esm({
118077
118150
  "floless-store.ts"() {
118078
118151
  "use strict";
@@ -118120,6 +118193,7 @@ var init_floless_store = __esm({
118120
118193
  emptyPromotionIndex = () => ({ v: 1, entries: [] });
118121
118194
  UNOBSERVABLE_SCRATCH_IDLE_MS = 2 * 60 * 6e4;
118122
118195
  unreadableScratchRows = /* @__PURE__ */ new Set();
118196
+ unmeasurableScratch = /* @__PURE__ */ new Set();
118123
118197
  flolessRoot = ROOT4;
118124
118198
  SnapshotError = class extends Error {
118125
118199
  };
@@ -125622,7 +125696,7 @@ async function duplicateProject(id2, name, onCreated, operationId = (0, import_n
125622
125696
  const srcRoot = projectDir(src.id);
125623
125697
  (0, import_node_fs53.cpSync)(srcRoot, copyRoot, {
125624
125698
  recursive: true,
125625
- filter: (p) => !p.endsWith("project.json") && !isReservedProjectInternalPath(p) && !isProjectRootSidecar(srcRoot, p, RFI_FILENAME) && !isProjectRootSidecar(srcRoot, p, RFI_POISON_FILENAME)
125699
+ filter: (p) => !p.endsWith("project.json") && !isReservedProjectInternalPath(p) && !isProjectRootSidecar(srcRoot, p, RFI_FILENAME) && !isProjectRootSidecar(srcRoot, p, RFI_POISON_FILENAME) && !isProjectRootSidecar(srcRoot, p, CHAT_DIRECTORY_NAME)
125626
125700
  });
125627
125701
  try {
125628
125702
  dropSignOffsFor(copy.id);
@@ -127122,7 +127196,7 @@ async function importProjectZip(data, rfiOperationId = (0, import_node_crypto44.
127122
127196
  return { project: meta3, rfiTransfer, ...revitPortable ? { revitPortable: true } : {}, ...revitSource ? { revitSource } : {} };
127123
127197
  }, seams.destination);
127124
127198
  }
127125
- var import_node_fs53, import_node_child_process14, import_promises20, import_node_path47, import_node_os28, import_node_crypto44, import_node_stream2, ProjectError, RESERVED_PROJECT_INTERNAL, NO_INCARNATION_REFUSAL, writeMeta, FRESH_DESTINATION_RETRY, THUMBNAIL_EXTS, MAX_THUMBNAIL_BYTES, THUMBNAIL_MEDIA_TYPES, ZIP_SLICE, yieldToLoop, IMPORT_MAX_FILES, IMPORT_MAX_UNCOMPRESSED, ARCHIVED_PDF_PAGE_GEOMETRY, ArchivedPdfInspectionError, RFI_INVENTORY_LIMITS;
127199
+ var import_node_fs53, import_node_child_process14, import_promises20, import_node_path47, import_node_os28, import_node_crypto44, import_node_stream2, ProjectError, CHAT_DIRECTORY_NAME, RESERVED_PROJECT_INTERNAL, NO_INCARNATION_REFUSAL, writeMeta, FRESH_DESTINATION_RETRY, THUMBNAIL_EXTS, MAX_THUMBNAIL_BYTES, THUMBNAIL_MEDIA_TYPES, ZIP_SLICE, yieldToLoop, IMPORT_MAX_FILES, IMPORT_MAX_UNCOMPRESSED, ARCHIVED_PDF_PAGE_GEOMETRY, ArchivedPdfInspectionError, RFI_INVENTORY_LIMITS;
127126
127200
  var init_projects_store = __esm({
127127
127201
  "projects-store.ts"() {
127128
127202
  "use strict";
@@ -127164,6 +127238,7 @@ var init_projects_store = __esm({
127164
127238
  }
127165
127239
  code;
127166
127240
  };
127241
+ CHAT_DIRECTORY_NAME = "chats";
127167
127242
  RESERVED_PROJECT_INTERNAL = /(?:^|[\\/])(?:\.member-end-resolution(?:[\\/]|$)|\.floless-model-lifecycle\.json$|\.floless-revit-publication\.json$|\.floless-revit-publication-quarantine(?:[\\/]|$)|\.floless-(?:txn|cleanup|tmp|backup|activation|refcache|checkpoints|working-revision|export-handle|approval-operation)-|contract\.json\.publication\.json$)/i;
127168
127243
  NO_INCARNATION_REFUSAL = "This project can\u2019t be approved \u2014 duplicate it from the Workspaces list to sign off";
127169
127244
  writeMeta = (meta3, directory) => {
@@ -132394,7 +132469,13 @@ function preparationInterruptionDiagnosticText(req) {
132394
132469
  const detail = req.steelPreparationTimeout ?? req.run?.steelPreparationTimeout;
132395
132470
  return `Diagnostic ${detail.diagnosticId}; ${detail.phase} phase; ${detail.elapsedMs} ms of ${detail.timeoutMs} ms; ${detail.workload.sourceCount} source(s).`;
132396
132471
  }
132397
- function runEligibilityFor(req) {
132472
+ function chatCanStartRequest(view) {
132473
+ if (view.canRun === true) return true;
132474
+ if (view.type !== "revision-read") return false;
132475
+ if (view.run !== void 0 || runEligibilityFor(view).runnable) return false;
132476
+ return runEligibilityFor(view, { interactive: true }).runnable;
132477
+ }
132478
+ function runEligibilityFor(req, opts = {}) {
132398
132479
  const policy = policyFor(req.type);
132399
132480
  if (!policy.runnable) return policy;
132400
132481
  if (req.type === "guide" && !normalizeInstructorContext(req.instructorContext)) {
@@ -132443,22 +132524,24 @@ function runEligibilityFor(req) {
132443
132524
  why: steelPreparationTimeoutWhy(req)
132444
132525
  };
132445
132526
  }
132446
- if (!req.project || !req.appId || !Number.isInteger(req.baseVersion) || Number(req.baseVersion) <= 0) {
132527
+ const firstRead = !req.project || !req.appId || !Number.isInteger(req.baseVersion) || Number(req.baseVersion) <= 0;
132528
+ if (firstRead && !(opts.interactive && req.project && req.appId)) {
132447
132529
  return { runnable: false, why: "this is the first drawing read for the project \u2014 your terminal AI must create the starting project checkpoint and wait for you to review and save the Drawing Filter" };
132448
132530
  }
132449
132531
  if (req.appTemplateId !== "steel-model") {
132450
132532
  return { runnable: false, why: "headless revision pre-read is available only for an existing steel model" };
132451
132533
  }
132452
- if (req.nativeSteelReady !== true) {
132534
+ if (!firstRead && req.nativeSteelReady !== true) {
132453
132535
  return { runnable: false, why: "headless revision pre-read requires a current native steel model" };
132454
132536
  }
132455
132537
  if (!Array.isArray(req.sourceRefs) || req.sourceRefs.length === 0 || req.sourceRefs.some((ref) => !ref || typeof ref !== "object" || typeof ref.ext !== "string" || ref.ext.toLowerCase() !== "pdf")) {
132456
- return { runnable: false, why: "headless revision pre-read currently requires the queued drawing set to be PDF" };
132538
+ return { runnable: false, why: "the drawing set must be PDF files" };
132457
132539
  }
132458
132540
  if (req.extractorAvailable === false) {
132459
- return { runnable: false, why: "headless revision pre-read needs a local Python runtime with PyMuPDF installed" };
132541
+ return { runnable: false, why: "this computer needs a local Python runtime with PyMuPDF installed to read the drawings" };
132460
132542
  }
132461
- if (Number.isInteger(req.headVersion) && req.baseVersion !== req.headVersion) {
132543
+ const queuedAgainst = firstRead ? req.baseVersion ?? 0 : req.baseVersion;
132544
+ if (firstRead && !Number.isInteger(req.headVersion) || Number.isInteger(req.headVersion) && queuedAgainst !== req.headVersion) {
132462
132545
  return { runnable: false, why: "the project changed after this revision was queued \u2014 attach the drawings again against the current version" };
132463
132546
  }
132464
132547
  return { runnable: true, policy };
@@ -133552,7 +133635,7 @@ For an unbuilt-connection relationship question, a verified connection marker is
133552
133635
  const scratch = `
133553
133636
  Every helper script or throwaway file this read needs belongs in temporary scratch space. ${scratchDestination} Do NOT write a .ps1, .mjs or any other helper into the project folder or beside the drawings: that folder is the user's own document, not a workspace. Nothing you want to survive the request belongs in temporary scratch space.${readIsolationClause(req.id, req.project ?? "", (req.appTemplateId || req.appId) !== "vectorize")}`;
133554
133637
  const vectorPost = `GET the current contract again and keep its ETag, then POST /api/projects/${req.project}/revision-read with { contract, message: "${messageHint}", requestId: "${req.id}" } and If-Match: <that current ETag>. The server derives the base version and source provenance from this queued request. The first completed vector drawing publishes History version 1; later reads stage a review and publish only after confirmation. Do NOT DELETE the request yourself. If you can't read the drawing, POST /api/projects/${req.project}/revision-requests/${req.id}/fail with { error }.`;
133555
- const post = `After Filter Save, GET /api/projects/${req.project}/revision-requests/${req.id}/steel-manifest and GET the current contract with its ETag. Preserve every server-owned id. Account for every manifest page, layer, human-excluded line weight and colour, candidate line, reference/detail/connection marker, and every new or changed joint in a closed steel-read/v6 attestation. Where the drawings genuinely do not tell you what something is, SAY SO rather than guessing or leaving it out: disposition "unresolved" on a layers[] or facetExclusions[] row, and kind "unreviewed" on a pageReviews[] row (still copying its real candidateShardHash), each with a note giving the reason a person needs. Each publishes the model with a question attached instead of refusing the read. "unresolved" never authorises the wholesale dismissal below, so every line failing an unresolved dimension still needs its own row. A candidate line you neither model nor write a row for no longer refuses the read either: it publishes as a question against its sheet. That is a gap RECORDED, not a line accounted for, and it is a worse outcome than saying "unresolved" \u2014 the question states how many lines and names a bounded sample of them per sheet, NEVER all of them, so lines you leave out can reach the user as a number nobody can trace back to a drawing. Account for every line; leave silence as what happens when you fail to, not as a way of working. An endpoint elevation the drawings do not settle is submitted {"unknown":true} with why (one sentence on what the set does say) and checked ([{sourceHash,pageId,sheet}] for the pages you read): that publishes with a question attached, while an unknown carrying neither is refused. The SERVER then places that endpoint at the elevation of the plan it was read from and marks it {known, assumed:true, why, checked}, so the member is BUILT and visible instead of dropping out of the model, and the question still reaches the user. You may NOT write assumed yourself - it is the server saying it could not prove a height, and a reader that stamped its own number with it would be claiming server authority for a guess. Submit unknown and let the server place it. It follows that a plan view any member is read from MUST state its own elevation_mm: without one there is nowhere to place that member, so a plan whose elevation the set does not state outright is a QUESTION: ASK THE USER for it before you read members from that sheet - one question per view, not one per member - and never author elevation_mm from your own guess. But do not ask cold for what the set carries: look at the sheets first - the datums[] you recorded in the design-set knowledge, a level on a building section or frame elevation that this plan's title names, a T.O. STEEL note that governs the whole plan's framing (a general note, "U.N.O."; never one member's callout, which governs only its own end), and the page picture - and where you can read a level, POST /api/projects/${req.project}/revision-requests/${req.id}/plan-elevation-proposal with { plan: { viewId, sourceHash, pageId }, readings: [{ value, asRead, page: { sourceHash, pageId, sheet }, quote, elementIds } or, for a callout drawn rather than written, { value, asRead, page, near }] }, where viewId is that plan's id in the project's plans[] (on a first read, the checkpoint shell's; for a plan a revised set adds, the id you will give it; a sheet that carries several plan views is refused, so ask about each of those with no proposal, naming the view) and value is your conversion of asRead to world millimetres. RELAY its proposal.ask verbatim - it quotes what you read and names the sheet, says when a reading was read off a picture and not checked, and asks whether this plan is at that level - and author elevation_mm only after the user confirms or corrects it. Readings that disagree come back as a choice from lowest to highest with none preferred: never pick one yourself. Propose only what you READ: never another plan's elevation, a cut plane, or arithmetic. Ask with no proposal only when the whole set is silent, and then name the sheets you checked. The manifest response carries derived fields you cannot compute yourself and must copy exactly: pageShards (one candidateShardHash per page \u2014 give every page exactly one { pageId, kind: "whole" or "unreviewed", candidateShardHash, note } pageReview, and never a second one), layerLineCounts (each layers[] row states its own { model, evidence } lineCounts, verified against the server's ledger), dismissibleFacetValues (every { dim, value } the human excluded \u2014 each thickness or color one needs exactly one facetExclusions[] row; layer ones are covered by layers[] instead), facetLineCounts (copy the matching { model, evidence } into that row's lineCounts; a dismissible value with no row there carries zero lines, so state zeros rather than omitting it), and referenceCandidates (every element owing a references[] row \u2014 decided by its text, so detail/connection markers count too, never a candidate-kind filter). The response also carries scaleProposals: one row per plan page, the server's deterministic reading of that sheet's OWN drawing scale, fitted over every printed dimension string between its grid bubbles rather than the two runs you would otherwise pick by eye. It is ADVISORY \u2014 you still author mm_per_px, and the two-control 2 pt proof is unchanged and still required, so if a proposed value fails that proof the PROOF wins. Each row's outcome.action says what to do with it, and you follow that rather than deciding for yourself. "author": the sheet's dimensions settled it in both directions, so use outcome.mmPerPx and SAY SO in the chat, naming the standard and how many dimension strings agreed. Only an IMPERIAL sheet ever reaches this action; a metric one never does, however well its dimensions agree. "ask-and-confirm": SHOW THE USER that number and the sheet, and use it ONLY if they confirm. WHICH fact they are confirming depends on outcome.decidedBy, and describing the wrong one would say something untrue about the drawing. "printed-unverified" means only the printed title-block note claims a scale and the sheet's own dimensions do not corroborate it. "metric-unverified" is the opposite case, and it is metric: the sheet's dimension strings DO agree on a value, inside the band its own printed 1:N ratio opens, and it still needs confirming because nothing automatic can tell a genuine dimension chain apart from a coincidence assembled out of a neighbouring row of dimensions. On that arm quote outcome.standard, outcome.unit (whether the sheet's bare numbers were read as millimetres or centimetres \u2014 a real drawing set uses either), and outcome.plottedAtPct (how far the drawn content sits from that ratio, which is why a fixed table cannot read these sheets). Say whether outcome.chains.x and outcome.chains.y report anchoredByOverall: a printed overall dimension that matches the chain is the best corroboration the sheet offers, and its ABSENCE is the thing to say plainly when it is missing rather than a detail to skip. It is CORROBORATION AND NOT A VERDICT \u2014 it does not decide which reading the proposer chose, so do not present it as the reason the number is right. Name every outcome.runnersUp row too. A competing reading is now RARER than it was: the proposer reads each chain out of a single printed dimension row and refuses one that skips a dimension sitting alongside it, which removes most sub-multiple readings before they are ever reported. So an EMPTY runnersUp is the normal case and is not itself reassurance, while a row that does survive is a reading the drawing genuinely supports twice over \u2014 say so, and never as a footnote. An unconfirmed scale is never registered silently, because a world scale nobody checked must not reach a model with nothing recording that nobody checked it. "ask-and-wait": a real question, so put it in the chat naming the sheet and listing outcome.candidates -- each carries only its standard, its mmPerPx and how many dimension strings supported it, so quote THOSE and do not describe evidence you were not given. A metric sheet whose readings could not be separated carries outcome.metricCandidates INSTEAD, and those rows additionally carry the unit each reading assumes, so name the unit as well: "1:100 read in centimetres, or 1:10 read in millimetres" is the actual question, and dropping the unit makes it unanswerable. Then WAIT \u2014 the user may answer with a hand measurement of their own, and that is a legitimate scale you then author. "fallback-hand-fit": nothing the user could answer would help (the elements arrived carrying no ids, the sheet prints more different drawing ratios than this reader will weigh, or the work budget stopped that sheet), so derive the scale by hand exactly as you always have and do NOT put it to the user as a question \u2014 asking somebody to resolve a server budget is a question with no answer. "report-defect": the proposer itself failed on that sheet; say so rather than working around it. A row may ALSO carry bubbleTokenQuestion, and that one is INDEPENDENT of outcome.action - put it to the user even on "fallback-hand-fit", which silences the SCALE question and not this one. It means every circle on that sheet holding more than one text repeats the same token, so the grid can be read two ways and nothing in the drawing data settles which: the token may be a zone or building code drawn beside each grid reference (ISO 19650), or it may be the sheet a row of detail callouts points at. Ask ONE question naming the sheet, the token(s) and bubbleTokenQuestion.bubbleCount, and offer exactly these answers, which are mutually exclusive: one named candidate token is the CONTEXTUAL one to ignore when reading the remaining grid label; or DO NOT USE THESE CIRCLES AS GRID BUBBLES (they are callouts or something else) - say that rather than "this sheet has no grid", because the sheet may carry a grid elsewhere that this question is not about; or NEITHER, when the two texts together form one grid label or the office uses a convention neither answer describes, in which case ask the user what that convention is and follow it. Offer all three: a forced choice between two readings that are both wrong would put back the wrong grid this question exists to avoid. With two candidates ask which of them is contextual - never as two separate yes/no questions, because stripping one and stripping the other give grids that cannot both be right. Each candidate carries wouldRead: a PREVIEW of the grid that reading would give, labels only and no coordinates. SHOW it, never copy it as the grid - after the user answers, re-read the matching bubbles and their positions from the sheet itself. It is bounded, so say what is missing: whenever a family's labelsTotal exceeds the labels shown, or wouldReadTotal exceeds the families shown, state how many are not listed, and an empty wouldRead with a positive wouldReadTotal means the preview COULD NOT BE SHOWN (its labels are too long to carry), never that the reading yields nothing - a person deciding from four of five families without being told is deciding from evidence they believe is complete. WAIT for the answer before using any candidate label or the bubbles behind it; unrelated work on that sheet may go on only where it does not depend on which reading is right. Confirming a token settles the GRID and not the scale: you still derive mm_per_px yourself and the two-control 2 pt proof is unchanged. When scaleProposals is ABSENT entirely the manifest predates this and every scale is yours to derive by hand as before, while an EMPTY array means it ran and proposed nothing. If the response carries an unaccounted key, those derived fields are NOT all there to copy: this manifest holds pages its saved Drawing Filter cannot account for, so no line count folded from it would describe the drawing set, and unaccounted.withheld names EXACTLY which fields are absent. Do not invent them and do not attest a count you did not receive \u2014 the audit recomputes through the same fold and would block. Nothing else in the response has been narrowed: the manifest, pageShards, sourceSetDigest and referenceCandidates are all sound and still worth working from. Read unaccounted.questions instead: each row names a pageId, the sheets involved and a plain question. TELL THE USER IN THE CHAT about every row whose answerable is true \u2014 which page of the current set a sheet really is, which of two sheets claiming one page owns it, whether a drawing that has changed since the Filter was saved is the one to read \u2014 and act on the answer, which is normally to fix the Drawing Filter and Save it again, or to POST this request's /steel-manifest to regenerate the manifest. A row whose answerable is false is one no answer of the user's would settle, and its OWN why says what would \u2014 follow that, never one blanket remedy. Two shapes reach it: a page this drawing scan did not classify as a model page is fixed by RECLASSIFYING it in the Drawing Filter, and regenerating the manifest would reproduce the same classification and loop; a fault in the stored manifest (a candidate whose page is missing, whose element is unreadable, or whose kind disagrees with it) is fixed by POSTing this request's /steel-manifest to regenerate. A page-side mismatch or a stored-manifest fault may need one regeneration even after this request has published its Filter checkpoint and the saved Filter still matches its copy in the manifest: POST this request's /steel-manifest ONCE with no bindings so FloLess rebuilds the server-held drawing scan. If that POST returns 409 revision-filter-prepared, the server did not authorise recovery; STOP and tell the user what the questions say \u2014 do not retry. Tell the user which of the two they are looking at, in that row's own terms. pageCount and candidateCount are the WHOLE population even when truncated is true and the list you were shown is shorter, so quote those numbers rather than counting the rows. For each resolved references[] row keep targetPageId. When the drawing identifies a specific destination detail, also state targetDetail: { tag, region } with the human-readable tag and the full detail-cell extent in manifest page coordinates; when the marker itself lies inside a detail, state that containing cell as sourceDetail: { tag, region }. A plan callout normally has no sourceDetail. A missing row may carry sourceDetail but never a target. These are reader observations: never substitute the small tag-text box for the detail cell, infer a cell from server geometry, or invent one on a raster/ambiguous sheet. Omit the locator and preserve the honest page-only reference instead. The server checks page ownership, raw bounds, whole-marker containment and repeated-locator consistency; it does not certify the semantic tag. Nonzero qualification or traversal capacity means transitive navigation is incomplete: say exact detail highlighting is unavailable for affected branches and never claim a fixed point. The response also carries exclusionBasis: when it is not "saved-filter" the human has not saved the Drawing Filter yet, dismissibleFacetValues and proofBudget are absent entirely, and there is nothing to build a proof against \u2014 wait for the Save. If the response's proofBudget says strained, one explicit row per line would not fit: this set only works if observations, the wholesale shorthand and grouping between them save enough bytes, so model what is genuinely a member, dismiss wholesale what the Filter authorises, group the rest by shared reason, and warn the human up front if none of that will be enough; impossible is a sound refusal but not a complete detector, so a set can pass it and still admit no proof that fits. If the response's proofBudget says impossible, stop: no proof over this Drawing Filter can fit the 8 MB cap however it is written, and the human has to switch more line weights off. Where many lines share one disposition and one reason, put them in a single lineDispositionGroups[] entry \u2014 { disposition, reason, elementIds: [...] }, plus one shared duplicateOf when the disposition is duplicate \u2014 instead of repeating the same sentence once per line. A line that needs a written disposition must appear EXACTLY ONCE, named literally, in either lineDispositions[] or one group, never in both (a line an observation accounts for, or one the rules below dismiss wholesale, belongs in neither): elementIds holds real ids and nothing else, there is no range, wildcard or "everything else", and a group's reason must be true of every line it names rather than of a typical one. Use a lineDispositions[] row when a reason is genuinely specific to one line, and keep THOSE concise because they are paid per line; a grouped reason is written once, so make it a full sentence worth reading. Prefer a modeling observation over any written disposition wherever a line is genuinely a member. A line the Filter does not select needs NO per-line disposition only when EVERY dimension it fails independently authorises that: the value is in dismissibleFacetValues AND you attested it annotation, existing or other (in layers[] for a layer, in facetExclusions[] for a line weight or colour; "unresolved" does NOT count). If even one failing dimension does not, that line needs its own row whatever the others say. When a valid-scale elevation or section observation traces a member but its view has no sourceRegistration, keep that member out of contract.members, keep its direct active observation and two endpoint-lineage rows in the contract, and add a viewFrameCandidates row with its id, profile, provenance, optional material / role / memberType, viewId, observationId, and exactly two { observationEnd, memberEnd, lineageId } endpoint identities. Send an empty viewFrameCandidates array when there are no such members. POST /api/projects/${req.project}/revision-read/audit with { requestId: "${req.id}", contract, viewFrameCandidates, attestation }; if that call itself is refused with code steel-attestation-invalid, act on THAT before anything else: its recovery names who must act and the one step they take, and its diagnosis names the exact version or keys. A blocked report is NOT a checklist to repeat until it goes green. Every blocking check carries recovery: an ordered list whose FIRST entry is the next step, each with an owner and an action. Take the heads of every blocking check and act on exactly one of them, in this order. Any head with owner "none" ends the request: relay its action and POST /fail - nobody can clear it and repeating cannot. Otherwise, if ANY head has owner "user", finish the run with outcome "needs-you" and ONE question carrying EVERY user-owned action together, and stop - do not re-submit, and do not do the reader or server work first, because a change the user makes to the drawing selection invalidates the scan built from it and the proof built from that. Otherwise act on the single highest-precedence remaining head, "server" before "reader": a "server" action is an API call this instruction names, and if it is refused - 409 revision-filter-prepared - nothing you send will change that answer, so relay it and POST /fail; a "reader" action is a repair to the contract or the attestation you submitted. After ANY of those, POST the audit again and re-read the heads: they are computed from the evidence you sent, so acting on a stale one repeats work that has already been undone. NEVER re-submit the same contract and attestation against an unchanged report - that is a loop, not a repair. source-accounting-floor shows why the owner matters rather than the check id: on a populated ledger it is a reader repair, and where the selection carries no linework at all it is not - no re-read can account for a line that is not there, and its route says whether a re-scan or a different drawing set is what is needed. The audit response carries audit.rfis: the questions this read could not settle, derived by the server -- you cannot author, merge or drop one. TELL THE USER ABOUT THEM IN THE CHAT before you move on, whether or not the read went through: the response also carries questionBriefing, a response-only sibling the server derives for exactly this: it groups the questions, ranks the groups, and gives each one a plain category, what not answering it costs, how many are affected, how many are already filed, and a few exact locations. RELAY IT - do not re-derive the grouping and do not re-order it, because the ranking is the server's. Its affected count is QUESTIONS, not members - two unknown endpoints on one member are two, and a layer question is about no member at all. Its alreadyFiled can be null, which means the RFI file could not be read and NOT that nothing is filed. Read each group's ways out off its routes rather than reciting all three. file-rfi is withheld in exactly two cases and you do not have to work out which: a group whose questions EVERY ONE have an open, sent or answered record, because offering another for one of those is forbidden; and every group when the RFI file could not be read at all, because nothing may be filed until current RFI state can be checked. A CLOSED record withholds nothing - its question returning is filed as a linked successor - so a group can be filed end to end and still carry file-rfi. Your FIRST turn about questions says, in this order and before the user asks for any of it: the totals by priority; then groups[0] in full - it is already the most urgent because the server ordered them - what it is, what it costs, how many questions, and its named locations ("S-203, page 7", or the member to select); then ONE answerable question about that group and nothing else. Whatever groups[0] is, that is what you lead with; an EMPTY groups list means the read raised no questions, so say so rather than manufacturing one. Then work group by group: take the answer, re-audit, say what moved, go to the next. A BARE COUNT IS NEVER THE ANSWER - an earlier version of this instruction let a read reply "140 review questions" and stop, and the user had to ask repeatedly before one sheet was named. Never open with "Should I publish all N as RFIs?" either; that is the same non-answer wearing a question mark, and it asks somebody to dispose of work nobody has described to them. exactEvidenceUnavailable is marked on a LOCATION and never on a group, and it means there is no exact area to highlight rather than no idea where to look. When that location still carries a sheet - which every whole-sheet question does, including every unreviewed-page one - name the sheet as somewhere to look and say the read cannot point at a spot on it; never name a whole sheet as if it were the exact spot. Only where a location has no sheet, no member, no joint and no Filter row say the set does not show where it is. Each question carries at: WHERE it is, and you must SAY IT so the user can go and look -- {"where":"drawing"} names a page of audit.rfiPages by its pageIx, so quote that page's sheet and page number ("S-502, page 9"); role "detail" names a reader-identified destination cell, so quote its tag, sheet and page and say that bounded area is highlighted; role "supporting-reference" names a detail reached by following references from the direct detail, so call it supporting rather than direct; role "referenced-sheet" is the sheet a callout points AT rather than the callout itself, so say so ("referenced sheet S-502, from the callout on S-202") and never call it the detail -- nothing in the read proves which detail on that sheet it is; role "page" is a WHOLE SHEET with no rectangle on it, and which sheet depends on the question: on an unreviewed-page question it is the sheet NOBODY reviewed ("S-201 was never reviewed"), and on a question about a member it is a sheet you told the audit you CHECKED and could not settle it from ("checked S-201; nothing on it settles the size") -- never say the thing is drawn there, and never call an unreviewed sheet checked; {"where":"model"} names a member or connection the user can select in the editor; {"where":"filter"} is a Drawing Filter row for a question about a setting no line carries. A question about something the drawings never showed has only a model or filter target, and that is the honest answer -- say the set does not draw it rather than pointing at a page it is not on. Then offer to work through them: the user can give you the value, ask you to carry it as an RFI, or tell you to proceed on a stated assumption -- and every one of those ends with the member built. audit.rfisOmitted, when present, is how many questions did not fit the report; say that number rather than implying the list is complete. Publishing a model and saying nothing about its open questions is the one outcome this whole flow exists to prevent. Then, ONLY IF the audit came back with status "read-complete", POST the exact same contract and attestation to /api/projects/${req.project}/revision-read with { contract, viewFrameCandidates, attestation, message: "${messageHint}", requestId: "${req.id}" } and If-Match: <that exact ETag>. A blocked report never reaches this step: you have already taken its one next action above, or parked, or failed the request. A later read returns 202 for human review; when replacing an existing staged generation, also send If-Match-Stage with its exact stageId. Do NOT DELETE the request yourself. If you can't read the set, POST /api/projects/${req.project}/revision-requests/${req.id}/fail with { error }.`;
133638
+ const post = `After Filter Save, GET /api/projects/${req.project}/revision-requests/${req.id}/steel-manifest and GET the current contract with its ETag. Preserve every server-owned id. Account for every manifest page, layer, human-excluded line weight and colour, candidate line, reference/detail/connection marker, and every new or changed joint in a closed steel-read/v6 attestation. Where the drawings genuinely do not tell you what something is, SAY SO rather than guessing or leaving it out: disposition "unresolved" on a layers[] or facetExclusions[] row, and kind "unreviewed" on a pageReviews[] row (still copying its real candidateShardHash), each with a note giving the reason a person needs. Each publishes the model with a question attached instead of refusing the read. "unresolved" never authorises the wholesale dismissal below, so every line failing an unresolved dimension still needs its own row. A candidate line you neither model nor write a row for no longer refuses the read either: it publishes as a question against its sheet. That is a gap RECORDED, not a line accounted for, and it is a worse outcome than saying "unresolved" \u2014 the question states how many lines and names a bounded sample of them per sheet, NEVER all of them, so lines you leave out can reach the user as a number nobody can trace back to a drawing. Account for every line; leave silence as what happens when you fail to, not as a way of working. An endpoint elevation the drawings do not settle is submitted {"unknown":true} with why (one sentence on what the set does say) and checked ([{sourceHash,pageId,sheet}] for the pages you read): that publishes with a question attached, while an unknown carrying neither is refused. The SERVER then places that endpoint at the elevation of the plan it was read from and marks it {known, assumed:true, why, checked}, so the member is BUILT and visible instead of dropping out of the model, and the question still reaches the user. You may NOT write assumed yourself - it is the server saying it could not prove a height, and a reader that stamped its own number with it would be claiming server authority for a guess. Before you submit any unknown, read that sheet's drawn heights: fetch ALL NINE enlarged tiles of the sheet (GET /api/projects/${req.project}/revision-requests/${req.id}/steel-manifest/pages/<pageId>/picture?part=1 through part=9), transcribe every top-of-steel callout drawn on it, and for each one that lies at this end's grid intersection or along this member's line but that you cannot tie to this end, add it to that unknown's candidates [{ value, asRead, near, page: { sourceHash, pageId, sheet } }] (at most five, nearest first; never as known) - one blanket unknown over a sheet that shows callouts is the failure, not the answer. Submit unknown and let the server place it. It follows that a plan view any member is read from MUST state its own elevation_mm: without one there is nowhere to place that member, so a plan whose elevation the set does not state outright is a QUESTION: ASK THE USER for it before you read members from that sheet - one question per view, not one per member - and never author elevation_mm from your own guess. But do not ask cold for what the set carries: look at the sheets first - the datums[] you recorded in the design-set knowledge, a level on a building section or frame elevation that this plan's title names, a T.O. STEEL note that governs the whole plan's framing (a general note, "U.N.O."; never one member's callout, which governs only its own end), and the page picture - and where you can read a level, POST /api/projects/${req.project}/revision-requests/${req.id}/plan-elevation-proposal with { plan: { viewId, sourceHash, pageId }, readings: [{ value, asRead, page: { sourceHash, pageId, sheet }, quote, elementIds } or, for a callout drawn rather than written, { value, asRead, page, near }] }, where viewId is that plan's id in the project's plans[] (on a first read, the checkpoint shell's; for a plan a revised set adds, the id you will give it; a sheet that carries several plan views is refused, so ask about each of those with no proposal, naming the view) and value is your conversion of asRead to world millimetres. RELAY its proposal.ask verbatim - it quotes what you read and names the sheet, says when a reading was read off a picture and not checked, and asks whether this plan is at that level - and author elevation_mm only after the user confirms or corrects it. Readings that disagree come back as a choice from lowest to highest with none preferred: never pick one yourself. Propose only what you READ: never another plan's elevation, a cut plane, or arithmetic. Ask with no proposal only when the whole set is silent, and then name the sheets you checked. The manifest response carries derived fields you cannot compute yourself and must copy exactly: pageShards (one candidateShardHash per page \u2014 give every page exactly one { pageId, kind: "whole" or "unreviewed", candidateShardHash, note } pageReview, and never a second one), layerLineCounts (each layers[] row states its own { model, evidence } lineCounts, verified against the server's ledger), dismissibleFacetValues (every { dim, value } the human excluded \u2014 each thickness or color one needs exactly one facetExclusions[] row; layer ones are covered by layers[] instead), facetLineCounts (copy the matching { model, evidence } into that row's lineCounts; a dismissible value with no row there carries zero lines, so state zeros rather than omitting it), and referenceCandidates (every element owing a references[] row \u2014 decided by its text, so detail/connection markers count too, never a candidate-kind filter). The response also carries scaleProposals: one row per plan page, the server's deterministic reading of that sheet's OWN drawing scale, fitted over every printed dimension string between its grid bubbles rather than the two runs you would otherwise pick by eye. It is ADVISORY \u2014 you still author mm_per_px, and the two-control 2 pt proof is unchanged and still required, so if a proposed value fails that proof the PROOF wins. Each row's outcome.action says what to do with it, and you follow that rather than deciding for yourself. "author": the sheet's dimensions settled it in both directions, so use outcome.mmPerPx and SAY SO in the chat, naming the standard and how many dimension strings agreed. Only an IMPERIAL sheet ever reaches this action; a metric one never does, however well its dimensions agree. "ask-and-confirm": SHOW THE USER that number and the sheet, and use it ONLY if they confirm. WHICH fact they are confirming depends on outcome.decidedBy, and describing the wrong one would say something untrue about the drawing. "printed-unverified" means only the printed title-block note claims a scale and the sheet's own dimensions do not corroborate it. "metric-unverified" is the opposite case, and it is metric: the sheet's dimension strings DO agree on a value, inside the band its own printed 1:N ratio opens, and it still needs confirming because nothing automatic can tell a genuine dimension chain apart from a coincidence assembled out of a neighbouring row of dimensions. On that arm quote outcome.standard, outcome.unit (whether the sheet's bare numbers were read as millimetres or centimetres \u2014 a real drawing set uses either), and outcome.plottedAtPct (how far the drawn content sits from that ratio, which is why a fixed table cannot read these sheets). Say whether outcome.chains.x and outcome.chains.y report anchoredByOverall: a printed overall dimension that matches the chain is the best corroboration the sheet offers, and its ABSENCE is the thing to say plainly when it is missing rather than a detail to skip. It is CORROBORATION AND NOT A VERDICT \u2014 it does not decide which reading the proposer chose, so do not present it as the reason the number is right. Name every outcome.runnersUp row too. A competing reading is now RARER than it was: the proposer reads each chain out of a single printed dimension row and refuses one that skips a dimension sitting alongside it, which removes most sub-multiple readings before they are ever reported. So an EMPTY runnersUp is the normal case and is not itself reassurance, while a row that does survive is a reading the drawing genuinely supports twice over \u2014 say so, and never as a footnote. An unconfirmed scale is never registered silently, because a world scale nobody checked must not reach a model with nothing recording that nobody checked it. "ask-and-wait": a real question, so put it in the chat naming the sheet and listing outcome.candidates -- each carries only its standard, its mmPerPx and how many dimension strings supported it, so quote THOSE and do not describe evidence you were not given. A metric sheet whose readings could not be separated carries outcome.metricCandidates INSTEAD, and those rows additionally carry the unit each reading assumes, so name the unit as well: "1:100 read in centimetres, or 1:10 read in millimetres" is the actual question, and dropping the unit makes it unanswerable. Then WAIT \u2014 the user may answer with a hand measurement of their own, and that is a legitimate scale you then author. "fallback-hand-fit": nothing the user could answer would help (the elements arrived carrying no ids, the sheet prints more different drawing ratios than this reader will weigh, or the work budget stopped that sheet), so derive the scale by hand exactly as you always have and do NOT put it to the user as a question \u2014 asking somebody to resolve a server budget is a question with no answer. "report-defect": the proposer itself failed on that sheet; say so rather than working around it. A row may ALSO carry bubbleTokenQuestion, and that one is INDEPENDENT of outcome.action - put it to the user even on "fallback-hand-fit", which silences the SCALE question and not this one. It means every circle on that sheet holding more than one text repeats the same token, so the grid can be read two ways and nothing in the drawing data settles which: the token may be a zone or building code drawn beside each grid reference (ISO 19650), or it may be the sheet a row of detail callouts points at. Ask ONE question naming the sheet, the token(s) and bubbleTokenQuestion.bubbleCount, and offer exactly these answers, which are mutually exclusive: one named candidate token is the CONTEXTUAL one to ignore when reading the remaining grid label; or DO NOT USE THESE CIRCLES AS GRID BUBBLES (they are callouts or something else) - say that rather than "this sheet has no grid", because the sheet may carry a grid elsewhere that this question is not about; or NEITHER, when the two texts together form one grid label or the office uses a convention neither answer describes, in which case ask the user what that convention is and follow it. Offer all three: a forced choice between two readings that are both wrong would put back the wrong grid this question exists to avoid. With two candidates ask which of them is contextual - never as two separate yes/no questions, because stripping one and stripping the other give grids that cannot both be right. Each candidate carries wouldRead: a PREVIEW of the grid that reading would give, labels only and no coordinates. SHOW it, never copy it as the grid - after the user answers, re-read the matching bubbles and their positions from the sheet itself. It is bounded, so say what is missing: whenever a family's labelsTotal exceeds the labels shown, or wouldReadTotal exceeds the families shown, state how many are not listed, and an empty wouldRead with a positive wouldReadTotal means the preview COULD NOT BE SHOWN (its labels are too long to carry), never that the reading yields nothing - a person deciding from four of five families without being told is deciding from evidence they believe is complete. WAIT for the answer before using any candidate label or the bubbles behind it; unrelated work on that sheet may go on only where it does not depend on which reading is right. Confirming a token settles the GRID and not the scale: you still derive mm_per_px yourself and the two-control 2 pt proof is unchanged. When scaleProposals is ABSENT entirely the manifest predates this and every scale is yours to derive by hand as before, while an EMPTY array means it ran and proposed nothing. If the response carries an unaccounted key, those derived fields are NOT all there to copy: this manifest holds pages its saved Drawing Filter cannot account for, so no line count folded from it would describe the drawing set, and unaccounted.withheld names EXACTLY which fields are absent. Do not invent them and do not attest a count you did not receive \u2014 the audit recomputes through the same fold and would block. Nothing else in the response has been narrowed: the manifest, pageShards, sourceSetDigest and referenceCandidates are all sound and still worth working from. Read unaccounted.questions instead: each row names a pageId, the sheets involved and a plain question. TELL THE USER IN THE CHAT about every row whose answerable is true \u2014 which page of the current set a sheet really is, which of two sheets claiming one page owns it, whether a drawing that has changed since the Filter was saved is the one to read \u2014 and act on the answer, which is normally to fix the Drawing Filter and Save it again, or to POST this request's /steel-manifest to regenerate the manifest. A row whose answerable is false is one no answer of the user's would settle, and its OWN why says what would \u2014 follow that, never one blanket remedy. Two shapes reach it: a page this drawing scan did not classify as a model page is fixed by RECLASSIFYING it in the Drawing Filter, and regenerating the manifest would reproduce the same classification and loop; a fault in the stored manifest (a candidate whose page is missing, whose element is unreadable, or whose kind disagrees with it) is fixed by POSTing this request's /steel-manifest to regenerate. A page-side mismatch or a stored-manifest fault may need one regeneration even after this request has published its Filter checkpoint and the saved Filter still matches its copy in the manifest: POST this request's /steel-manifest ONCE with no bindings so FloLess rebuilds the server-held drawing scan. If that POST returns 409 revision-filter-prepared, the server did not authorise recovery; STOP and tell the user what the questions say \u2014 do not retry. Tell the user which of the two they are looking at, in that row's own terms. pageCount and candidateCount are the WHOLE population even when truncated is true and the list you were shown is shorter, so quote those numbers rather than counting the rows. For each resolved references[] row keep targetPageId. When the drawing identifies a specific destination detail, also state targetDetail: { tag, region } with the human-readable tag and the full detail-cell extent in manifest page coordinates; when the marker itself lies inside a detail, state that containing cell as sourceDetail: { tag, region }. A plan callout normally has no sourceDetail. A missing row may carry sourceDetail but never a target. These are reader observations: never substitute the small tag-text box for the detail cell, infer a cell from server geometry, or invent one on a raster/ambiguous sheet. Omit the locator and preserve the honest page-only reference instead. The server checks page ownership, raw bounds, whole-marker containment and repeated-locator consistency; it does not certify the semantic tag. Nonzero qualification or traversal capacity means transitive navigation is incomplete: say exact detail highlighting is unavailable for affected branches and never claim a fixed point. The response also carries exclusionBasis: when it is not "saved-filter" the human has not saved the Drawing Filter yet, dismissibleFacetValues and proofBudget are absent entirely, and there is nothing to build a proof against \u2014 wait for the Save. If the response's proofBudget says strained, one explicit row per line would not fit: this set only works if observations, the wholesale shorthand and grouping between them save enough bytes, so model what is genuinely a member, dismiss wholesale what the Filter authorises, group the rest by shared reason, and warn the human up front if none of that will be enough; impossible is a sound refusal but not a complete detector, so a set can pass it and still admit no proof that fits. If the response's proofBudget says impossible, stop: no proof over this Drawing Filter can fit the 8 MB cap however it is written, and the human has to switch more line weights off. Where many lines share one disposition and one reason, put them in a single lineDispositionGroups[] entry \u2014 { disposition, reason, elementIds: [...] }, plus one shared duplicateOf when the disposition is duplicate \u2014 instead of repeating the same sentence once per line. A line that needs a written disposition must appear EXACTLY ONCE, named literally, in either lineDispositions[] or one group, never in both (a line an observation accounts for, or one the rules below dismiss wholesale, belongs in neither): elementIds holds real ids and nothing else, there is no range, wildcard or "everything else", and a group's reason must be true of every line it names rather than of a typical one. Use a lineDispositions[] row when a reason is genuinely specific to one line, and keep THOSE concise because they are paid per line; a grouped reason is written once, so make it a full sentence worth reading. Prefer a modeling observation over any written disposition wherever a line is genuinely a member. A line the Filter does not select needs NO per-line disposition only when EVERY dimension it fails independently authorises that: the value is in dismissibleFacetValues AND you attested it annotation, existing or other (in layers[] for a layer, in facetExclusions[] for a line weight or colour; "unresolved" does NOT count). If even one failing dimension does not, that line needs its own row whatever the others say. When a valid-scale elevation or section observation traces a member but its view has no sourceRegistration, keep that member out of contract.members, keep its direct active observation and two endpoint-lineage rows in the contract, and add a viewFrameCandidates row with its id, profile, provenance, optional material / role / memberType, viewId, observationId, and exactly two { observationEnd, memberEnd, lineageId } endpoint identities. Send an empty viewFrameCandidates array when there are no such members. POST /api/projects/${req.project}/revision-read/audit with { requestId: "${req.id}", contract, viewFrameCandidates, attestation }; if that call itself is refused with code steel-attestation-invalid, act on THAT before anything else: its recovery names who must act and the one step they take, and its diagnosis names the exact version or keys. A blocked report is NOT a checklist to repeat until it goes green. Every blocking check carries recovery: an ordered list whose FIRST entry is the next step, each with an owner and an action. Take the heads of every blocking check and act on exactly one of them, in this order. Any head with owner "none" ends the request: relay its action and POST /fail - nobody can clear it and repeating cannot. Otherwise, if ANY head has owner "user", finish the run with outcome "needs-you" and ONE question carrying EVERY user-owned action together, and stop - do not re-submit, and do not do the reader or server work first, because a change the user makes to the drawing selection invalidates the scan built from it and the proof built from that. Otherwise act on the single highest-precedence remaining head, "server" before "reader": a "server" action is an API call this instruction names, and if it is refused - 409 revision-filter-prepared - nothing you send will change that answer, so relay it and POST /fail; a "reader" action is a repair to the contract or the attestation you submitted. After ANY of those, POST the audit again and re-read the heads: they are computed from the evidence you sent, so acting on a stale one repeats work that has already been undone. NEVER re-submit the same contract and attestation against an unchanged report - that is a loop, not a repair. source-accounting-floor shows why the owner matters rather than the check id: on a populated ledger it is a reader repair, and where the selection carries no linework at all it is not - no re-read can account for a line that is not there, and its route says whether a re-scan or a different drawing set is what is needed. The audit response carries audit.rfis: the questions this read could not settle, derived by the server -- you cannot author, merge or drop one. TELL THE USER ABOUT THEM IN THE CHAT before you move on, whether or not the read went through: the response also carries questionBriefing, a response-only sibling the server derives for exactly this: it groups the questions, ranks the groups, and gives each one a plain category, what not answering it costs, how many are affected, how many are already filed, and a few exact locations. RELAY IT - do not re-derive the grouping and do not re-order it, because the ranking is the server's. Its affected count is QUESTIONS, not members - two unknown endpoints on one member are two, and a layer question is about no member at all. Its alreadyFiled can be null, which means the RFI file could not be read and NOT that nothing is filed. Read each group's ways out off its routes rather than reciting all three. file-rfi is withheld in exactly two cases and you do not have to work out which: a group whose questions EVERY ONE have an open, sent or answered record, because offering another for one of those is forbidden; and every group when the RFI file could not be read at all, because nothing may be filed until current RFI state can be checked. A CLOSED record withholds nothing - its question returning is filed as a linked successor - so a group can be filed end to end and still carry file-rfi. Your FIRST turn about questions says, in this order and before the user asks for any of it: the totals by priority; then groups[0] in full - it is already the most urgent because the server ordered them - what it is, what it costs, how many questions, and its named locations ("S-203, page 7", or the member to select); then ONE answerable question about that group and nothing else. Whatever groups[0] is, that is what you lead with; an EMPTY groups list means the read raised no questions, so say so rather than manufacturing one. Then work group by group: take the answer, re-audit, say what moved, go to the next. A BARE COUNT IS NEVER THE ANSWER - an earlier version of this instruction let a read reply "140 review questions" and stop, and the user had to ask repeatedly before one sheet was named. Never open with "Should I publish all N as RFIs?" either; that is the same non-answer wearing a question mark, and it asks somebody to dispose of work nobody has described to them. exactEvidenceUnavailable is marked on a LOCATION and never on a group, and it means there is no exact area to highlight rather than no idea where to look. When that location still carries a sheet - which every whole-sheet question does, including every unreviewed-page one - name the sheet as somewhere to look and say the read cannot point at a spot on it; never name a whole sheet as if it were the exact spot. Only where a location has no sheet, no member, no joint and no Filter row say the set does not show where it is. Each question carries at: WHERE it is, and you must SAY IT so the user can go and look -- {"where":"drawing"} names a page of audit.rfiPages by its pageIx, so quote that page's sheet and page number ("S-502, page 9"); role "detail" names a reader-identified destination cell, so quote its tag, sheet and page and say that bounded area is highlighted; role "supporting-reference" names a detail reached by following references from the direct detail, so call it supporting rather than direct; role "referenced-sheet" is the sheet a callout points AT rather than the callout itself, so say so ("referenced sheet S-502, from the callout on S-202") and never call it the detail -- nothing in the read proves which detail on that sheet it is; role "page" is a WHOLE SHEET with no rectangle on it, and which sheet depends on the question: on an unreviewed-page question it is the sheet NOBODY reviewed ("S-201 was never reviewed"), and on a question about a member it is a sheet you told the audit you CHECKED and could not settle it from ("checked S-201; nothing on it settles the size") -- never say the thing is drawn there, and never call an unreviewed sheet checked; {"where":"model"} names a member or connection the user can select in the editor; {"where":"filter"} is a Drawing Filter row for a question about a setting no line carries. A question about something the drawings never showed has only a model or filter target, and that is the honest answer -- say the set does not draw it rather than pointing at a page it is not on. Then offer to work through them: the user can give you the value, ask you to carry it as an RFI, or tell you to proceed on a stated assumption -- and every one of those ends with the member built. audit.rfisOmitted, when present, is how many questions did not fit the report; say that number rather than implying the list is complete. Publishing a model and saying nothing about its open questions is the one outcome this whole flow exists to prevent. Then, ONLY IF the audit came back with status "read-complete", POST the exact same contract and attestation to /api/projects/${req.project}/revision-read with { contract, viewFrameCandidates, attestation, message: "${messageHint}", requestId: "${req.id}" } and If-Match: <that exact ETag>. A blocked report never reaches this step: you have already taken its one next action above, or parked, or failed the request. A later read returns 202 for human review; when replacing an existing staged generation, also send If-Match-Stage with its exact stageId. Do NOT DELETE the request yourself. If you can't read the set, POST /api/projects/${req.project}/revision-requests/${req.id}/fail with { error }.`;
133556
133639
  const scaleQuestionBriefing = `When the response carries scaleQuestionBriefing, require version: 2 and use that response-only object as the server's authoritative presentation of every ask-and-confirm scale question: RELAY questions in its exact order and copy each question, confirmLabel, technicalDetails, all counts, and every evidence label and summary exactly; do not re-derive, merge, omit, or reorder them from scaleProposals. In that case, do not relay any competing ask-and-confirm narrative from the lower-level scaleProposals fields described later in this instruction. Open evidence only through the exact server-issued locations[].openPath, using that location's actionLabel exactly as the Markdown link text. Never expose a raw source path, make a file:// link, or construct an evidence route yourself. A page location is an honest whole-sheet fallback, not an exact highlight. A Winning X dimension chain or Winning Y dimension chain is the fitter's complete, ordered chain membership; the manifest separately rechecks each listed element's page ownership, text kind, and normalized magnitude. Relay that producer-owned claim exactly, but never call it independent proof or confirmation. General dimension references are the broader proposal inputs and are not identified as members of a complete winning chain. A truncated producer chain gets no winning-chain row. Winning-chain locations are budgeted before general dimensions across the whole response; response truncation and producer truncation are different facts. None of these locations makes the scale confirmed. `;
133557
133640
  const manifestPhase = `FIRST POST /api/projects/${req.project}/revision-requests/${req.id}/steel-manifest with {}; only it inventories pages and mints Filter ids. On sheet-identification-required, inspect listed pages, identify each, then retry with { bindings: [{ pageId, sheet, title?, evidenceKind }] }. evidenceKind is exactly one of "plan", "elevation", "section", "detail", "schedule", "notes", "foundation", or "other"; never guess another value from a drawing title. Never guess from other pages or build Filter geometry. On steel-manifest-preparation-busy, steel-manifest-inspection-interrupted, or steel-manifest-extraction-interrupted, wait at least retryAfterMs and retry this step for the SAME request; the request, completed page identification, and drawing set remain attached. On steel-manifest-preparation-blocked, STOP and relay recovery; do not retry until an operator clears it. For an interruption, relay error and recovery, then phase, elapsed/limit, counts and diagnostic id; null page counts are unknown. Never relay commands, stderr, source, filenames, or paths. On steel-manifest-over-budget, STOP and relay recovery. Page scope: remove or split that dense sheet. Total scope: smaller revisions. Bytes scope is drawing-data weight, not element count: move or split the heaviest sheets first; one sheet over the limit cannot be isolated to help. Null scope means extraction overflowed before measurement: no breakdown; the set must be far smaller. Only complete true covers the whole set; with false or null the figures are lower bounds and the recovery may not suffice. On steel-manifest-extraction-failed, STOP and relay the diagnostic; an identical retry fails. Never rename Filter geometry or mint element ids.`;
133558
133641
  const notReadLayers = `A Filter layer row with notRead: true was withheld by FloLess's extraction, not switched off by the user: every line it draws (typically grid lines and bubbles, dimension lines, section and callout marks) is left out of the elements, and the Drawing Filter shows it dimmed with a disabled tick box. Nobody can tick it, and saving the Filter again changes nothing, so NEVER ask the user to include, tick or re-save for a notRead layer, and never treat one being off as a gap in the saved selection. Live text is not withheld: grid labels, dimension strings and callout text that the PDF holds as text arrive as kind "text" elements (usually under layer "TEXT", never under the notRead layer itself) with positions in the page's point frame, so look there first. Lettering DRAWN as linework on a notRead layer was withheld with the rest of it, so a label you cannot find among the text elements is not proof the sheet lacks it: once the Filter is saved, read it and the withheld linework off the page picture (GET /api/projects/${req.project}/revision-requests/${req.id}/steel-manifest/pages/<pageId>/picture, part=0 for the whole sheet, 1-9 for enlarged tiles; if it answers 404, follow what its error says). The picture is context for grids, dimensions and annotation only: members still come from elements the saved selection keeps. A scaleProposals refusal saying no grid family was found is usually that same withholding, and in every case it is computed from the extracted elements, not from what the Filter selects, so no Filter change can alter it: follow its outcome.action as described below, never answer it with a Filter change. Where a notRead layer genuinely limits what you can read, say so as a statement in your report, naming the layer and what it stopped you reading, and carry on with the rest; ask only a question whose answer the user can actually give.`;
@@ -133772,6 +133855,7 @@ function withPrompt(r, base2 = selfOrigin()) {
133772
133855
  const prompt = instructionFor(r);
133773
133856
  const marker = markerFor(r, base2, prompt);
133774
133857
  const eligibility = runEligibilityFor(r);
133858
+ const interactive = eligibility.runnable ? eligibility : runEligibilityFor(r, { interactive: true });
133775
133859
  const preparationEntry = r.type === "revision-read" ? steelPreparationEntryFor(r) : null;
133776
133860
  const retryablePreparationRefusal = r.type === "revision-read" && hasRetryablePreparationRefusal(r);
133777
133861
  const preparationRetryable = r.type === "revision-read" && preparationEntry?.allowed === true && (retryablePreparationRefusal || r.status === "pending" && hasPreparationInterruptionDiagnostic(r));
@@ -133782,17 +133866,22 @@ function withPrompt(r, base2 = selfOrigin()) {
133782
133866
  const clearPolicy = requestClearPolicyFor(r);
133783
133867
  const activeRun2 = projectedRun?.state === "queued" || projectedRun?.state === "running";
133784
133868
  const canCopy = marker !== "" && !activeRun2 && !isFilterAiChangeRequest(r) && !isFilterAiQuestionRequest(r) && (r.type !== "revision-read" || r.status === "pending" && r.prepassReady !== true && preparationEntry?.allowed === true);
133869
+ const status = retryablePreparationRefusal && r.status === "failed" ? "pending" : r.status;
133870
+ const canRun = eligibility.runnable && !hasAttempt;
133785
133871
  return {
133786
133872
  ...r,
133787
- status: retryablePreparationRefusal && r.status === "failed" ? "pending" : r.status,
133873
+ status,
133788
133874
  run: projectedRun,
133789
133875
  prompt,
133790
133876
  marker: terminalPreparationRefusal ? "" : marker,
133791
133877
  preparationState: preparationEntry?.state ?? null,
133792
133878
  preparationRetryable,
133793
133879
  preparationDiagnostic: hasPreparationInterruptionDiagnostic(r) ? preparationInterruptionDiagnosticText(r) : null,
133794
- canRun: eligibility.runnable && !hasAttempt,
133795
- runWhy: eligibility.runnable ? null : eligibility.why,
133880
+ canRun,
133881
+ runWhy: eligibility.runnable ? null : interactive.runnable ? eligibility.why : interactive.why,
133882
+ // The chat start route's own verdict (chat-routes `acceptRequestChat` + index.ts `canStart`), so
133883
+ // the upload modal never offers a Start in AI Chat that route answers with a 409.
133884
+ chatCanStart: r.type === "guide" || Boolean(r.intakeSubmissionId) || chatCanStartRequest({ ...r, status, run: projectedRun, canRun }),
133796
133885
  canCopy,
133797
133886
  ...clearPolicy,
133798
133887
  resumeCommand: terminalPreparationRefusal ? null : resumeCommandForRequest(r),
@@ -133822,6 +133911,7 @@ function withPrompt(r, base2 = selfOrigin()) {
133822
133911
  canCopy: false,
133823
133912
  canRun: false,
133824
133913
  runWhy: null,
133914
+ chatCanStart: false,
133825
133915
  ...clearPolicy,
133826
133916
  resumeCommand: resumeCommandForRequest(r),
133827
133917
  desktopHandoffs: null
@@ -138731,7 +138821,7 @@ function normalizeTeklaReadOperations(value) {
138731
138821
  if (!Array.isArray(value) || !value.length || value.length > TEKLA_CHAT_READ_OPERATIONS.length || new Set(value).size !== value.length || value.some((item) => !TEKLA_CHAT_READ_OPERATIONS.includes(item))) return null;
138732
138822
  return TEKLA_CHAT_READ_OPERATIONS.filter((operation) => value.includes(operation));
138733
138823
  }
138734
- var TEKLA_MODEL_READ_OPERATION, TEKLA_SELECTION_READ_OPERATION, TEKLA_CHAT_READ_OPERATIONS, TEKLA_MODEL_LIBRARY_PATTERN, TEKLA_READ_TOOL_NAME, TEKLA_SELECTION_TOOL_NAME, TEKLA_TOOL_OPERATIONS, TEKLA_SELECTION_ROW_LIMIT, TEKLA_ALLOWANCE_HISTORY_LIMIT;
138824
+ var TEKLA_MODEL_READ_OPERATION, TEKLA_SELECTION_READ_OPERATION, TEKLA_CHAT_READ_OPERATIONS, TEKLA_MODEL_LIBRARY_PATTERN, TEKLA_READ_TOOL_NAME, TEKLA_SELECTION_TOOL_NAME, TEKLA_TOOL_OPERATIONS, TEKLA_SELECTION_ROW_LIMIT, TEKLA_LINKED_PART_CHECK_LIMIT, TEKLA_ALLOWANCE_SCOPE, TEKLA_ALLOWANCE_HISTORY_LIMIT, TEKLA_LINKED_PARTS_CHECKS;
138735
138825
  var init_chat_types = __esm({
138736
138826
  "chat-types.ts"() {
138737
138827
  "use strict";
@@ -138749,7 +138839,127 @@ var init_chat_types = __esm({
138749
138839
  [TEKLA_SELECTION_TOOL_NAME]: TEKLA_SELECTION_READ_OPERATION
138750
138840
  });
138751
138841
  TEKLA_SELECTION_ROW_LIMIT = 200;
138842
+ TEKLA_LINKED_PART_CHECK_LIMIT = 1e3;
138843
+ TEKLA_ALLOWANCE_SCOPE = 2;
138752
138844
  TEKLA_ALLOWANCE_HISTORY_LIMIT = 20;
138845
+ TEKLA_LINKED_PARTS_CHECKS = ["unavailable", "partial"];
138846
+ }
138847
+ });
138848
+
138849
+ // chat-subjects.ts
138850
+ function subjectKinds(source) {
138851
+ return KINDS2[source];
138852
+ }
138853
+ function codePoints(text9, max2, ellipsis = false) {
138854
+ const points = [...text9];
138855
+ if (points.length <= max2) return text9;
138856
+ return ellipsis ? `${points.slice(0, max2 - 1).join("").trimEnd()}\u2026` : points.slice(0, max2).join("").trimEnd();
138857
+ }
138858
+ function tidy(text9) {
138859
+ return text9.replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim();
138860
+ }
138861
+ function subjectItem(value, source, kinds) {
138862
+ const row2 = value && typeof value === "object" && !Array.isArray(value) ? value : null;
138863
+ if (!row2) throw new ChatSubjectsError("a selected object is not an object");
138864
+ if (typeof row2.kind !== "string" || !kinds.has(row2.kind)) throw new ChatSubjectsError("a selected object has an unknown kind");
138865
+ const id2 = row2.id;
138866
+ if (typeof id2 !== "string" || !id2.trim() || id2.length > MAX_SUBJECT_ID || CONTROL.test(id2) || id2 === "__proto__") {
138867
+ throw new ChatSubjectsError("a selected object has an invalid id");
138868
+ }
138869
+ if (isSnapshotSource(source) && ENTITY_ID2.exec(id2)?.[1] !== row2.kind) throw new ChatSubjectsError("a selected object has an invalid id");
138870
+ if (isLiveSource(source) && !TEKLA_GUID.test(id2)) throw new ChatSubjectsError("a selected object has an invalid id");
138871
+ const label2 = typeof row2.label === "string" ? codePoints(tidy(row2.label), MAX_SUBJECT_LABEL) : "";
138872
+ return { kind: row2.kind, id: id2, label: label2 || codePoints(id2, MAX_SUBJECT_LABEL) };
138873
+ }
138874
+ function subjectList(value, source, kinds, max2) {
138875
+ if (!Array.isArray(value) || value.length > max2 * 4) throw new ChatSubjectsError("the selected objects are not a list");
138876
+ const seen = /* @__PURE__ */ new Set();
138877
+ const items = [];
138878
+ for (const raw of value) {
138879
+ const item = subjectItem(raw, source, kinds);
138880
+ const key5 = `${item.kind}\0${item.id}`;
138881
+ if (seen.has(key5)) continue;
138882
+ seen.add(key5);
138883
+ items.push(item);
138884
+ }
138885
+ if (items.length > max2) throw new ChatSubjectsError(`more than ${max2} selected objects`);
138886
+ return items;
138887
+ }
138888
+ function normalizeChatSubjects(value) {
138889
+ if (value === void 0 || value === null) return null;
138890
+ const row2 = typeof value === "object" && !Array.isArray(value) ? value : null;
138891
+ if (!row2) throw new ChatSubjectsError("the selection is not an object");
138892
+ const kinds = typeof row2.source === "string" && Object.hasOwn(KINDS2, row2.source) ? KINDS2[row2.source] : null;
138893
+ if (!kinds) throw new ChatSubjectsError("the selection comes from an unsupported model");
138894
+ const source = row2.source;
138895
+ const revision = row2.revision === void 0 || row2.revision === null ? null : row2.revision;
138896
+ const revisionOk = isLiveSource(source) ? false : isSnapshotSource(source) ? typeof revision === "string" && HEX645.test(revision) : typeof revision === "number" && Number.isSafeInteger(revision) && revision >= 0;
138897
+ if (revision !== null && !revisionOk) throw new ChatSubjectsError("the selection has an invalid model revision");
138898
+ if (!isSnapshotSource(source) && row2.sourceDigest !== void 0) throw new ChatSubjectsError("only a snapshot model names its source file");
138899
+ const digest7 = row2.sourceDigest === void 0 || row2.sourceDigest === null ? null : row2.sourceDigest;
138900
+ if (digest7 !== null && (typeof digest7 !== "string" || !HEX645.test(digest7))) throw new ChatSubjectsError("the selection has an invalid source file");
138901
+ const identity4 = isSnapshotSource(source) ? { sourceDigest: digest7 } : {};
138902
+ if (row2.items !== void 0 && row2.group !== void 0) throw new ChatSubjectsError("the selection is both a list and a group");
138903
+ if (row2.items !== void 0) {
138904
+ const items = subjectList(row2.items, source, kinds, MAX_LISTED_SUBJECTS);
138905
+ if (!items.length) throw new ChatSubjectsError("the selection is empty");
138906
+ return { source, revision, ...identity4, items };
138907
+ }
138908
+ const group = row2.group && typeof row2.group === "object" && !Array.isArray(row2.group) ? row2.group : null;
138909
+ if (!group) throw new ChatSubjectsError("the selection has no objects");
138910
+ const count4 = group.count;
138911
+ if (typeof count4 !== "number" || !Number.isSafeInteger(count4) || count4 <= MAX_LISTED_SUBJECTS || count4 > MAX_GROUP_COUNT) {
138912
+ throw new ChatSubjectsError("the selection group has an invalid size");
138913
+ }
138914
+ const sample = subjectList(group.sample, source, kinds, MAX_GROUP_SAMPLE);
138915
+ if (sample.length > count4) throw new ChatSubjectsError("the selection sample is larger than the group");
138916
+ return { source, revision, ...identity4, group: { count: count4, sample } };
138917
+ }
138918
+ function subjectNote(text9) {
138919
+ const line = String(text9 || "").split(/\r?\n/).map(tidy).find(Boolean);
138920
+ return line ? codePoints(line, MAX_SUBJECT_NOTE, true) : "A message with attachments";
138921
+ }
138922
+ function subjectLinkNote(text9) {
138923
+ if (typeof text9 !== "string") return "";
138924
+ const line = text9.split(/\r?\n|\r/).map(tidy).find(Boolean);
138925
+ return line ? codePoints(line, MAX_LINK_NOTE, true) : "";
138926
+ }
138927
+ var MAX_LISTED_SUBJECTS, MAX_GROUP_SAMPLE, MAX_GROUP_COUNT, MAX_SUBJECT_ID, MAX_SUBJECT_LABEL, MAX_SUBJECT_NOTE, KINDS2, CHAT_SUBJECT_SOURCES, isLiveSource, isSnapshotSource, SUBJECT_SOURCE_NOUNS, ChatSubjectsError, CONTROL, HEX645, ENTITY_ID2, TEKLA_GUID, MAX_LINK_NOTE;
138928
+ var init_chat_subjects = __esm({
138929
+ "chat-subjects.ts"() {
138930
+ "use strict";
138931
+ MAX_LISTED_SUBJECTS = 200;
138932
+ MAX_GROUP_SAMPLE = 50;
138933
+ MAX_GROUP_COUNT = 1e6;
138934
+ MAX_SUBJECT_ID = 200;
138935
+ MAX_SUBJECT_LABEL = 120;
138936
+ MAX_SUBJECT_NOTE = 120;
138937
+ KINDS2 = {
138938
+ steel: /* @__PURE__ */ new Set(["member", "joint", "detail"]),
138939
+ revit: /* @__PURE__ */ new Set(["element"]),
138940
+ "tekla-parser": /* @__PURE__ */ new Set(["element"]),
138941
+ tekla: /* @__PURE__ */ new Set(["part"])
138942
+ };
138943
+ CHAT_SUBJECT_SOURCES = Object.freeze(["steel", "revit", "tekla-parser", "tekla"]);
138944
+ isLiveSource = (source) => source === "tekla";
138945
+ isSnapshotSource = (source) => source === "revit" || source === "tekla-parser";
138946
+ SUBJECT_SOURCE_NOUNS = Object.freeze({
138947
+ steel: ["Steel Model object", "Steel Model objects"],
138948
+ revit: ["Revit element", "Revit elements"],
138949
+ "tekla-parser": ["Tekla object", "Tekla objects"],
138950
+ tekla: ["Tekla part", "Tekla parts"]
138951
+ });
138952
+ ChatSubjectsError = class extends Error {
138953
+ constructor(message2) {
138954
+ super(message2);
138955
+ this.name = "ChatSubjectsError";
138956
+ }
138957
+ };
138958
+ CONTROL = /[\u0000-\u001f\u007f]/;
138959
+ HEX645 = /^[0-9a-f]{64}$/;
138960
+ ENTITY_ID2 = /^([a-z][a-z0-9-]*):(\S+)$/;
138961
+ TEKLA_GUID = /^(?!0{8}-0{4}-0{4}-0{4}-0{12}$)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
138962
+ MAX_LINK_NOTE = 160;
138753
138963
  }
138754
138964
  });
138755
138965
 
@@ -138772,7 +138982,7 @@ function boundedText2(value) {
138772
138982
  const chars = Array.from(value.replace(/[\u0000-\u001f\u007f]/gu, " ").trim());
138773
138983
  return chars.length <= FIELD_LIMIT ? chars.join("") : `${chars.slice(0, FIELD_LIMIT - 1).join("")}\u2026`;
138774
138984
  }
138775
- function parseSelection(result2) {
138985
+ function parseSelection(result2, linkedParts) {
138776
138986
  const invalid8 = refusal("invalid-result", "FloLess could not read the Tekla selection result. Check that Tekla and its bridge are available, then try again.");
138777
138987
  if (typeof result2.selectionTooLarge !== "boolean" || typeof result2.selectionChanged !== "boolean") return invalid8;
138778
138988
  if (result2.selectionTooLarge) {
@@ -138784,6 +138994,7 @@ function parseSelection(result2) {
138784
138994
  const { parts, partCount, totalWeightKg, complete, weightMissing, otherObjectCount } = result2;
138785
138995
  if (!Array.isArray(parts) || parts.length > TEKLA_SELECTION_ROW_LIMIT || !isCount3(partCount) || partCount < parts.length || !isWeight(totalWeightKg) || typeof complete !== "boolean" || !isCount3(weightMissing) || weightMissing > partCount || !isCount3(otherObjectCount)) return invalid8;
138786
138996
  const rows2 = [];
138997
+ const guids = /* @__PURE__ */ new Set();
138787
138998
  for (const row2 of parts) {
138788
138999
  if (!row2 || typeof row2 !== "object" || Array.isArray(row2)) return invalid8;
138789
139000
  const item = row2;
@@ -138793,7 +139004,9 @@ function parseSelection(result2) {
138793
139004
  const material = boundedText2(item.material);
138794
139005
  if (mark === null || name === null || profile === null || material === null) return invalid8;
138795
139006
  if (item.weightKg !== null && !isWeight(item.weightKg)) return invalid8;
138796
- rows2.push({ mark, name, profile, material, weightKg: item.weightKg === null ? null : item.weightKg });
139007
+ if (typeof item.guid !== "string" || !TEKLA_GUID.test(item.guid) || guids.has(item.guid)) return invalid8;
139008
+ guids.add(item.guid);
139009
+ rows2.push({ mark, name, profile, material, weightKg: item.weightKg === null ? null : item.weightKg, guid: item.guid });
138797
139010
  }
138798
139011
  const weightless = rows2.filter((row2) => row2.weightKg === null).length;
138799
139012
  if (weightless > weightMissing) return invalid8;
@@ -138801,7 +139014,23 @@ function parseSelection(result2) {
138801
139014
  const listed = rows2.reduce((sum2, row2) => sum2 + (row2.weightKg ?? 0), 0);
138802
139015
  if (weightless !== weightMissing || Math.abs(listed - totalWeightKg) > 0.01 + 1e-9 * totalWeightKg) return invalid8;
138803
139016
  }
138804
- return { parts: rows2, partCount, totalWeightKg, truncated: partCount > rows2.length, complete, weightMissing, otherObjectCount };
139017
+ const selection = {
139018
+ parts: rows2,
139019
+ partCount,
139020
+ totalWeightKg,
139021
+ truncated: partCount > rows2.length,
139022
+ complete,
139023
+ weightMissing,
139024
+ otherObjectCount
139025
+ };
139026
+ if (!linkedParts) return selection;
139027
+ const { missingLinkedParts: missing, linkedPartsChecked: checked2 } = result2;
139028
+ const asked = new Set(linkedParts);
139029
+ if (!Array.isArray(missing) || checked2 !== linkedParts.length || new Set(missing).size !== missing.length || missing.some((guid3) => typeof guid3 !== "string" || !asked.has(guid3) || guids.has(guid3))) return { ...selection, linkedPartsCheck: "unavailable" };
139030
+ return { ...selection, linkedPartsChecked: checked2, missingLinkedParts: missing };
139031
+ }
139032
+ function validLinkedParts(value) {
139033
+ return Array.isArray(value) && value.length <= TEKLA_LINKED_PART_CHECK_LIMIT && new Set(value).size === value.length && value.every((guid3) => typeof guid3 === "string" && TEKLA_GUID.test(guid3));
138805
139034
  }
138806
139035
  function validateTeklaLibraryBinding(input2, canonical3 = canonicalLocalTeklaFile) {
138807
139036
  const invalid8 = { ok: false, message: "FloLess could not use this Tekla model library for Chat. Verify the model read in Graft again, then continue in AI Chat." };
@@ -138823,12 +139052,20 @@ function validateTeklaLibraryBinding(input2, canonical3 = canonicalLocalTeklaFil
138823
139052
  }
138824
139053
  return { ok: true, sourcePath: source, hostVersion, operations };
138825
139054
  }
138826
- async function verifyTeklaLibraryRead(sourcePath2, deps = DEFAULT_DEPS2, signal, operation = TEKLA_MODEL_READ_OPERATION) {
139055
+ async function verifyTeklaLibraryRead(sourcePath2, deps = DEFAULT_DEPS2, signal, operation = TEKLA_MODEL_READ_OPERATION, opts = {}) {
138827
139056
  const code = Object.hasOwn(OPERATION_CODE, operation) ? OPERATION_CODE[operation] : void 0;
138828
139057
  if (!code) {
138829
139058
  console.warn("[tekla-library-read] refused an unknown read", { operation });
138830
139059
  return refusal("invalid-result", "FloLess does not know this Tekla read, so it read nothing. Update FloLess, then try again.");
138831
139060
  }
139061
+ const linkedParts = opts.linkedParts;
139062
+ if (linkedParts !== void 0 && (operation !== TEKLA_SELECTION_READ_OPERATION || !validLinkedParts(linkedParts))) {
139063
+ console.warn("[tekla-library-read] refused an unsound list of linked parts", {
139064
+ operation,
139065
+ count: Array.isArray(linkedParts) ? linkedParts.length : null
139066
+ });
139067
+ return refusal("invalid-request", "FloLess could not prepare the check of parts linked to earlier questions, so it read nothing. Try again; if it keeps happening, report the issue.");
139068
+ }
138832
139069
  if (typeof sourcePath2 !== "string" || sourcePath2.length > 2048) {
138833
139070
  return refusal("invalid-source", "Choose the Tekla model library again, then inspect it.");
138834
139071
  }
@@ -138844,7 +139081,7 @@ async function verifyTeklaLibraryRead(sourcePath2, deps = DEFAULT_DEPS2, signal,
138844
139081
  if (signal?.aborted) return stoppedRefusal();
138845
139082
  let receipt;
138846
139083
  try {
138847
- receipt = await deps.probe(code, selectedVersion, signal);
139084
+ receipt = await deps.probe(code, selectedVersion, signal, linkedParts ? { linkedParts: [...linkedParts] } : void 0);
138848
139085
  } catch (error62) {
138849
139086
  if (signal?.aborted) return stoppedRefusal();
138850
139087
  console.warn("[tekla-library-read] the bridge call failed", { error: error62 instanceof Error ? error62.message : String(error62) });
@@ -138901,7 +139138,7 @@ async function verifyTeklaLibraryRead(sourcePath2, deps = DEFAULT_DEPS2, signal,
138901
139138
  verifiedAt: deps.now()
138902
139139
  };
138903
139140
  if (operation === TEKLA_SELECTION_READ_OPERATION) {
138904
- const selection = parseSelection(result2);
139141
+ const selection = parseSelection(result2, linkedParts);
138905
139142
  if ("ok" in selection) return selection;
138906
139143
  verification.selection = selection;
138907
139144
  }
@@ -138911,7 +139148,13 @@ async function runTeklaLibraryRead(sourcePath2, opts = {}) {
138911
139148
  if (inFlight) return refusal("busy", "A Tekla read is already in progress. Wait for it to finish, then try again.");
138912
139149
  inFlight = true;
138913
139150
  try {
138914
- return await verifyTeklaLibraryRead(sourcePath2, opts.deps ?? DEFAULT_DEPS2, opts.signal, opts.operation);
139151
+ return await verifyTeklaLibraryRead(
139152
+ sourcePath2,
139153
+ opts.deps ?? DEFAULT_DEPS2,
139154
+ opts.signal,
139155
+ opts.operation,
139156
+ opts.linkedParts ? { linkedParts: opts.linkedParts } : {}
139157
+ );
138915
139158
  } finally {
138916
139159
  inFlight = false;
138917
139160
  }
@@ -138931,6 +139174,7 @@ var init_tekla_library_read = __esm({
138931
139174
  import_node_path76 = require("node:path");
138932
139175
  init_aware_adapter();
138933
139176
  init_chat_types();
139177
+ init_chat_subjects();
138934
139178
  SOURCE_PATTERN = TEKLA_MODEL_LIBRARY_PATTERN;
138935
139179
  MODEL_NAME_CODE = `using Tekla.Structures.Model;
138936
139180
  var teklaModel = new Model();
@@ -138946,7 +139190,8 @@ var teklaModel = new Model();
138946
139190
  var connected = teklaModel.GetConnectionStatus();
138947
139191
  var modelName = string.Empty;
138948
139192
  var parts = new System.Collections.Generic.List<object>();
138949
- int partCount = 0, weightMissing = 0, otherObjectCount = 0, visited = 0;
139193
+ var missingLinkedParts = new System.Collections.Generic.List<string>();
139194
+ int partCount = 0, weightMissing = 0, otherObjectCount = 0, visited = 0, linkedPartsChecked = 0;
138950
139195
  double totalWeightKg = 0;
138951
139196
  bool complete = true, selectionChanged = false, selectionTooLarge = false;
138952
139197
  if (connected) {
@@ -139003,7 +139248,15 @@ if (connected) {
139003
139248
  double weight = 0;
139004
139249
  bool hasWeight = part.GetReportProperty("WEIGHT", ref weight) && !double.IsNaN(weight) && !double.IsInfinity(weight) && weight >= 0;
139005
139250
  if (hasWeight) totalWeightKg += weight; else weightMissing++;
139006
- if (parts.Count < ${TEKLA_SELECTION_ROW_LIMIT}) parts.Add(new { mark, name, profile, material, weightKg = hasWeight ? (double?)weight : null });
139251
+ if (parts.Count < ${TEKLA_SELECTION_ROW_LIMIT}) parts.Add(new { mark, name, profile, material, weightKg = hasWeight ? (double?)weight : null,
139252
+ guid = part.Identifier.GUID.ToString() });
139253
+ }
139254
+ var linkedList = args != null && args.ContainsKey("linkedParts") ? args["linkedParts"] as System.Collections.Generic.List<object> : null;
139255
+ if (linkedList != null) foreach (var entry in linkedList) {
139256
+ var text = entry as string; System.Guid linkedGuid;
139257
+ if (text == null || !System.Guid.TryParse(text, out linkedGuid)) continue;
139258
+ linkedPartsChecked++;
139259
+ if (!(teklaModel.SelectModelObject(new Tekla.Structures.Identifier(linkedGuid)) is Tekla.Structures.Model.Part)) missingLinkedParts.Add(text);
139007
139260
  }
139008
139261
  var secondIds = new System.Collections.Generic.List<int>();
139009
139262
  var again = new Tekla.Structures.Model.UI.ModelObjectSelector().GetSelectedObjects();
@@ -139019,14 +139272,14 @@ if (connected) {
139019
139272
  }
139020
139273
  }
139021
139274
  return new { connected, modelName, assemblyPath = typeof(Model).Assembly.Location, parts, partCount,
139022
- totalWeightKg, complete, weightMissing, otherObjectCount, selectionChanged, selectionTooLarge };`;
139275
+ totalWeightKg, complete, weightMissing, otherObjectCount, selectionChanged, selectionTooLarge, missingLinkedParts, linkedPartsChecked };`;
139023
139276
  OPERATION_CODE = Object.freeze({
139024
139277
  [TEKLA_MODEL_READ_OPERATION]: MODEL_NAME_CODE,
139025
139278
  [TEKLA_SELECTION_READ_OPERATION]: SELECTION_CODE
139026
139279
  });
139027
139280
  DEFAULT_DEPS2 = {
139028
139281
  canonical: canonicalLocalTeklaFile,
139029
- probe: (code, version2, signal) => aware.execTekla(code, { version: version2, signal }),
139282
+ probe: (code, version2, signal, args) => aware.execTekla(code, { version: version2, signal, ...args ? { args } : {} }),
139030
139283
  now: () => (/* @__PURE__ */ new Date()).toISOString()
139031
139284
  };
139032
139285
  isCount3 = (value) => Number.isSafeInteger(value) && value >= 0;
@@ -139900,115 +140153,79 @@ var init_workflow_publication = __esm({
139900
140153
  }
139901
140154
  });
139902
140155
 
139903
- // chat-subjects.ts
139904
- function subjectKinds(source) {
139905
- return KINDS2[source];
139906
- }
139907
- function codePoints(text9, max2, ellipsis = false) {
139908
- const points = [...text9];
139909
- if (points.length <= max2) return text9;
139910
- return ellipsis ? `${points.slice(0, max2 - 1).join("").trimEnd()}\u2026` : points.slice(0, max2).join("").trimEnd();
140156
+ // ../web/model-property-display.js
140157
+ function teklaPropertyGroups(rows2) {
140158
+ const properties = [], udas = [], nativeGroups = /* @__PURE__ */ new Map();
140159
+ for (const row2 of Array.isArray(rows2) ? rows2 : []) {
140160
+ const isUda = row2.isUda === true || row2.groupName === "User-defined attributes" || row2.groupName === "User-defined attributes (UDA)" || row2.groupName === "UDA";
140161
+ if (isUda) {
140162
+ udas.push(row2);
140163
+ continue;
140164
+ }
140165
+ if (row2.semantic && Number.isSafeInteger(row2.groupOrdinal)) {
140166
+ const key5 = `${row2.groupOrdinal}\0${row2.groupName}`;
140167
+ const group = nativeGroups.get(key5) || { key: key5, name: row2.groupName, ordinal: row2.groupOrdinal, rows: [], expanded: true };
140168
+ group.rows.push(row2);
140169
+ nativeGroups.set(key5, group);
140170
+ continue;
140171
+ }
140172
+ if (/^(?:Raw\b|provenance|Reader coverage|Technical details|System)/i.test(row2.groupName || "")) continue;
140173
+ if (row2.groupName === "Overview" && ["Object kind", "Subtype"].includes(row2.name)) continue;
140174
+ if (row2.groupName === "Source identity" && row2.name === "Native type") continue;
140175
+ const item = row2.name === "Object ID" ? { ...row2, name: "ID" } : row2;
140176
+ properties.push(item);
140177
+ }
140178
+ const ordered = (values2) => values2.slice().sort((a, b) => (a.propertyOrdinal ?? 0) - (b.propertyOrdinal ?? 0));
140179
+ return [
140180
+ ...[...nativeGroups.values()].sort((a, b) => a.ordinal - b.ordinal).map((group) => ({ ...group, rows: ordered(group.rows) })),
140181
+ ...properties.length ? [{ key: "tekla-properties", name: "Properties", rows: properties, expanded: true }] : [],
140182
+ ...udas.length ? [{ key: "tekla-udas", name: "User-defined attributes (UDA)", rows: ordered(udas), expanded: false }] : []
140183
+ ];
139911
140184
  }
139912
- function tidy(text9) {
139913
- return text9.replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim();
140185
+ function teklaObjectFields(entity, rows2 = []) {
140186
+ const source = teklaPropertyGroups(rows2).filter((group) => group.key !== "tekla-udas").flatMap((group) => group.rows);
140187
+ const value = (name) => source.find((row2) => row2.name === name)?.value;
140188
+ return {
140189
+ name: value("Name") ?? null,
140190
+ profile: value("Profile") ?? null,
140191
+ id: value("ID") ?? entity.objectId ?? (/^element:([0-9]+)$/.exec(entity.id || "")?.[1] ?? null)
140192
+ };
139914
140193
  }
139915
- function subjectItem(value, source, kinds) {
139916
- const row2 = value && typeof value === "object" && !Array.isArray(value) ? value : null;
139917
- if (!row2) throw new ChatSubjectsError("a selected object is not an object");
139918
- if (typeof row2.kind !== "string" || !kinds.has(row2.kind)) throw new ChatSubjectsError("a selected object has an unknown kind");
139919
- const id2 = row2.id;
139920
- if (typeof id2 !== "string" || !id2.trim() || id2.length > MAX_SUBJECT_ID || CONTROL.test(id2) || id2 === "__proto__") {
139921
- throw new ChatSubjectsError("a selected object has an invalid id");
139922
- }
139923
- if (isSnapshotSource(source) && ENTITY_ID2.exec(id2)?.[1] !== row2.kind) throw new ChatSubjectsError("a selected object has an invalid id");
139924
- const label2 = typeof row2.label === "string" ? codePoints(tidy(row2.label), MAX_SUBJECT_LABEL) : "";
139925
- return { kind: row2.kind, id: id2, label: label2 || codePoints(id2, MAX_SUBJECT_LABEL) };
140194
+ function teklaObjectLabel(entity, rows2 = []) {
140195
+ const fields = teklaObjectFields(entity, rows2);
140196
+ return [
140197
+ fields.name != null ? `Name: ${fields.name}` : null,
140198
+ fields.profile != null ? `Profile: ${fields.profile}` : null,
140199
+ fields.id != null ? `ID: ${fields.id}` : null
140200
+ ].filter(Boolean).join(" \xB7 ") || entity.typeName || "Tekla object";
139926
140201
  }
139927
- function subjectList(value, source, kinds, max2) {
139928
- if (!Array.isArray(value) || value.length > max2 * 4) throw new ChatSubjectsError("the selected objects are not a list");
139929
- const seen = /* @__PURE__ */ new Set();
139930
- const items = [];
139931
- for (const raw of value) {
139932
- const item = subjectItem(raw, source, kinds);
139933
- const key5 = `${item.kind}\0${item.id}`;
139934
- if (seen.has(key5)) continue;
139935
- seen.add(key5);
139936
- items.push(item);
140202
+ var init_model_property_display = __esm({
140203
+ "../web/model-property-display.js"() {
140204
+ init_display_units();
139937
140205
  }
139938
- if (items.length > max2) throw new ChatSubjectsError(`more than ${max2} selected objects`);
139939
- return items;
140206
+ });
140207
+
140208
+ // ../web/model-chat-questions.js
140209
+ function subjectLabelText(text9) {
140210
+ return [...String(text9 || "").replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim()].slice(0, 120).join("").trimEnd();
139940
140211
  }
139941
- function normalizeChatSubjects(value) {
139942
- if (value === void 0 || value === null) return null;
139943
- const row2 = typeof value === "object" && !Array.isArray(value) ? value : null;
139944
- if (!row2) throw new ChatSubjectsError("the selection is not an object");
139945
- const kinds = typeof row2.source === "string" && Object.hasOwn(KINDS2, row2.source) ? KINDS2[row2.source] : null;
139946
- if (!kinds) throw new ChatSubjectsError("the selection comes from an unsupported model");
139947
- const source = row2.source;
139948
- const revision = row2.revision === void 0 || row2.revision === null ? null : row2.revision;
139949
- const revisionOk = isSnapshotSource(source) ? typeof revision === "string" && HEX645.test(revision) : typeof revision === "number" && Number.isSafeInteger(revision) && revision >= 0;
139950
- if (revision !== null && !revisionOk) throw new ChatSubjectsError("the selection has an invalid model revision");
139951
- if (!isSnapshotSource(source) && row2.sourceDigest !== void 0) throw new ChatSubjectsError("only a snapshot model names its source file");
139952
- const digest7 = row2.sourceDigest === void 0 || row2.sourceDigest === null ? null : row2.sourceDigest;
139953
- if (digest7 !== null && (typeof digest7 !== "string" || !HEX645.test(digest7))) throw new ChatSubjectsError("the selection has an invalid source file");
139954
- const identity4 = isSnapshotSource(source) ? { sourceDigest: digest7 } : {};
139955
- if (row2.items !== void 0 && row2.group !== void 0) throw new ChatSubjectsError("the selection is both a list and a group");
139956
- if (row2.items !== void 0) {
139957
- const items = subjectList(row2.items, source, kinds, MAX_LISTED_SUBJECTS);
139958
- if (!items.length) throw new ChatSubjectsError("the selection is empty");
139959
- return { source, revision, ...identity4, items };
140212
+ function modelSubjectLabel(source, entity, rows2 = []) {
140213
+ if (source === "tekla") {
140214
+ const what2 = entity?.mark || entity?.name || "Tekla part";
140215
+ return entity?.profile ? `${what2} \xB7 ${entity.profile}` : what2;
139960
140216
  }
139961
- const group = row2.group && typeof row2.group === "object" && !Array.isArray(row2.group) ? row2.group : null;
139962
- if (!group) throw new ChatSubjectsError("the selection has no objects");
139963
- const count4 = group.count;
139964
- if (typeof count4 !== "number" || !Number.isSafeInteger(count4) || count4 <= MAX_LISTED_SUBJECTS || count4 > MAX_GROUP_COUNT) {
139965
- throw new ChatSubjectsError("the selection group has an invalid size");
140217
+ const id2 = String(entity?.id ?? "");
140218
+ if (source === "tekla-parser") {
140219
+ const fields = teklaObjectFields(entity || {}, rows2);
140220
+ const label2 = teklaObjectLabel(entity || {}, rows2);
140221
+ return fields.id == null ? `${label2} \xB7 ${id2}` : label2;
139966
140222
  }
139967
- const sample = subjectList(group.sample, source, kinds, MAX_GROUP_SAMPLE);
139968
- if (sample.length > count4) throw new ChatSubjectsError("the selection sample is larger than the group");
139969
- return { source, revision, ...identity4, group: { count: count4, sample } };
139970
- }
139971
- function subjectNote(text9) {
139972
- const line = String(text9 || "").split(/\r?\n/).map(tidy).find(Boolean);
139973
- return line ? codePoints(line, MAX_SUBJECT_NOTE, true) : "A message with attachments";
139974
- }
139975
- function subjectLinkNote(text9) {
139976
- if (typeof text9 !== "string") return "";
139977
- const line = text9.split(/\r?\n|\r/).map(tidy).find(Boolean);
139978
- return line ? codePoints(line, MAX_LINK_NOTE, true) : "";
140223
+ const what = entity?.name || entity?.typeName || entity?.categoryName || entity?.category || "Revit element";
140224
+ return `${what} \xB7 ${id2}`;
139979
140225
  }
139980
- var MAX_LISTED_SUBJECTS, MAX_GROUP_SAMPLE, MAX_GROUP_COUNT, MAX_SUBJECT_ID, MAX_SUBJECT_LABEL, MAX_SUBJECT_NOTE, KINDS2, CHAT_SUBJECT_SOURCES, isSnapshotSource, SUBJECT_SOURCE_NOUNS, ChatSubjectsError, CONTROL, HEX645, ENTITY_ID2, MAX_LINK_NOTE;
139981
- var init_chat_subjects = __esm({
139982
- "chat-subjects.ts"() {
139983
- "use strict";
139984
- MAX_LISTED_SUBJECTS = 200;
139985
- MAX_GROUP_SAMPLE = 50;
139986
- MAX_GROUP_COUNT = 1e6;
139987
- MAX_SUBJECT_ID = 200;
139988
- MAX_SUBJECT_LABEL = 120;
139989
- MAX_SUBJECT_NOTE = 120;
139990
- KINDS2 = {
139991
- steel: /* @__PURE__ */ new Set(["member", "joint", "detail"]),
139992
- revit: /* @__PURE__ */ new Set(["element"]),
139993
- "tekla-parser": /* @__PURE__ */ new Set(["element"])
139994
- };
139995
- CHAT_SUBJECT_SOURCES = Object.freeze(["steel", "revit", "tekla-parser"]);
139996
- isSnapshotSource = (source) => source !== "steel";
139997
- SUBJECT_SOURCE_NOUNS = Object.freeze({
139998
- steel: ["Steel Model object", "Steel Model objects"],
139999
- revit: ["Revit element", "Revit elements"],
140000
- "tekla-parser": ["Tekla object", "Tekla objects"]
140001
- });
140002
- ChatSubjectsError = class extends Error {
140003
- constructor(message2) {
140004
- super(message2);
140005
- this.name = "ChatSubjectsError";
140006
- }
140007
- };
140008
- CONTROL = /[\u0000-\u001f\u007f]/;
140009
- HEX645 = /^[0-9a-f]{64}$/;
140010
- ENTITY_ID2 = /^([a-z][a-z0-9-]*):(\S+)$/;
140011
- MAX_LINK_NOTE = 160;
140226
+ var init_model_chat_questions = __esm({
140227
+ "../web/model-chat-questions.js"() {
140228
+ init_model_property_display();
140012
140229
  }
140013
140230
  });
140014
140231
 
@@ -140018,7 +140235,7 @@ function emptySubjectIndex() {
140018
140235
  }
140019
140236
  function parseLink(value) {
140020
140237
  const row2 = value && typeof value === "object" && !Array.isArray(value) ? value : null;
140021
- if (!row2 || !str6(row2.messageEventId, 64) || !str6(row2.chatId, 64) || !str6(row2.source, 32) || !str6(row2.kind, 32) || !str6(row2.id, 200) || typeof row2.label !== "string" || typeof row2.note !== "string" || !Number.isSafeInteger(row2.sequence) || !str6(row2.createdAt, 64) || !(row2.revision === null || isRevision(row2.revision)) || !(row2.sourceDigest === void 0 || row2.sourceDigest === null || digestOf(row2.sourceDigest) !== null) || typeof row2.origin !== "string" || !ORIGINS.has(row2.origin) || !str6(row2.linkEventId, 64) || !Number.isSafeInteger(row2.linkSequence) || typeof row2.aiNote !== "string" || !str6(row2.askedAt, 64)) return null;
140238
+ if (!row2 || !str6(row2.messageEventId, 64) || !str6(row2.chatId, 64) || !str6(row2.source, 32) || !str6(row2.kind, 32) || !str6(row2.id, 200) || typeof row2.label !== "string" || typeof row2.note !== "string" || !Number.isSafeInteger(row2.sequence) || !str6(row2.createdAt, 64) || !(row2.revision === null || isRevision(row2.revision)) || !(row2.sourceDigest === void 0 || row2.sourceDigest === null || digestOf(row2.sourceDigest) !== null) || typeof row2.origin !== "string" || !ORIGINS.has(row2.origin) || !str6(row2.linkEventId, 64) || !Number.isSafeInteger(row2.linkSequence) || typeof row2.aiNote !== "string" || !str6(row2.askedAt, 64) || row2.source === "tekla" && !TEKLA_GUID.test(row2.id)) return null;
140022
140239
  return {
140023
140240
  messageEventId: row2.messageEventId,
140024
140241
  chatId: row2.chatId,
@@ -140093,8 +140310,45 @@ function aiLinksOfEvent(event) {
140093
140310
  }
140094
140311
  return links;
140095
140312
  }
140313
+ function teklaReadLinkRows(event) {
140314
+ const payload = event.payload;
140315
+ const question = asRow(payload.linkedQuestion);
140316
+ const parts = payload.parts;
140317
+ if (!question || !event.turnId || payload.status !== "verified-for-selection-read" || payload.operation !== TEKLA_SELECTION_READ_OPERATION || payload.complete !== true || payload.truncated !== false || !Array.isArray(parts) || !parts.length || parts.length > MAX_LISTED_SUBJECTS || !str6(question.messageEventId, 64) || !Number.isSafeInteger(question.messageSequence) || question.messageSequence >= event.sequence || typeof question.question !== "string" || !isIso(question.askedAt)) return [];
140318
+ const seen = /* @__PURE__ */ new Set();
140319
+ const links = [];
140320
+ for (const item of parts) {
140321
+ const part = asRow(item);
140322
+ const guid3 = part?.guid;
140323
+ if (!part || typeof guid3 !== "string" || !TEKLA_GUID.test(guid3) || seen.has(guid3)) return [];
140324
+ seen.add(guid3);
140325
+ links.push({
140326
+ messageEventId: question.messageEventId,
140327
+ chatId: event.chatId,
140328
+ sequence: question.messageSequence,
140329
+ source: "tekla",
140330
+ kind: "part",
140331
+ id: guid3,
140332
+ label: subjectLabelText(modelSubjectLabel("tekla", part)),
140333
+ note: question.question,
140334
+ revision: null,
140335
+ sourceDigest: null,
140336
+ createdAt: event.createdAt,
140337
+ origin: "read",
140338
+ linkEventId: event.eventId,
140339
+ linkSequence: event.sequence,
140340
+ aiNote: "",
140341
+ askedAt: question.askedAt
140342
+ });
140343
+ }
140344
+ return links;
140345
+ }
140096
140346
  function subjectLinksOfEvent(event) {
140347
+ return linksOfEvent(event).filter((link2) => link2.source !== "tekla" || TEKLA_GUID.test(link2.id));
140348
+ }
140349
+ function linksOfEvent(event) {
140097
140350
  if (event.type === "chat-subjects") return aiLinksOfEvent(event);
140351
+ if (event.type === "tekla-read") return teklaReadLinkRows(event);
140098
140352
  if (event.type !== "user-message") return [];
140099
140353
  const payload = event.payload;
140100
140354
  const subjects = payload.subjects && typeof payload.subjects === "object" && !Array.isArray(payload.subjects) ? payload.subjects : null;
@@ -140145,8 +140399,8 @@ function foldSubjectEvent(index, event) {
140145
140399
  const links = subjectLinksOfEvent(event);
140146
140400
  if (!links.length) return false;
140147
140401
  const first = links[0];
140148
- if (first.origin === "selection") return addSubjectLinks(index, links);
140149
- const same6 = (link2) => link2.chatId === first.chatId && link2.messageEventId === first.messageEventId && link2.origin === first.origin;
140402
+ if (ADD_ONLY.has(first.origin)) return addSubjectLinks(index, links);
140403
+ const same6 = (link2) => link2.chatId === first.chatId && link2.messageEventId === first.messageEventId && link2.origin === first.origin && link2.source === first.source;
140150
140404
  if (index.links.some((link2) => same6(link2) && link2.linkSequence > first.linkSequence)) return false;
140151
140405
  const before = index.links.length;
140152
140406
  index.links = index.links.filter((link2) => !(same6(link2) && link2.linkSequence < first.linkSequence));
@@ -140158,20 +140412,24 @@ function forgetSubjectChats(index, keep) {
140158
140412
  for (const chatId of Object.keys(index.chats)) if (!keep(chatId)) delete index.chats[chatId];
140159
140413
  return index.links.length + Object.keys(index.chats).length !== before;
140160
140414
  }
140161
- var SUBJECT_INDEX_VERSION, SUBJECT_INDEX_FILE, ORIGINS, str6, isRevision, revisionOf, digestOf, asRow, linkKey;
140415
+ var SUBJECT_INDEX_VERSION, SUBJECT_INDEX_FILE, ORIGINS, ADD_ONLY, str6, isRevision, revisionOf, digestOf, asRow, isIso, linkKey;
140162
140416
  var init_chat_subject_index = __esm({
140163
140417
  "chat-subject-index.ts"() {
140164
140418
  "use strict";
140419
+ init_chat_types();
140165
140420
  init_chat_subjects();
140166
- SUBJECT_INDEX_VERSION = 2;
140421
+ init_model_chat_questions();
140422
+ SUBJECT_INDEX_VERSION = 3;
140167
140423
  SUBJECT_INDEX_FILE = "subject-index.json";
140168
- ORIGINS = /* @__PURE__ */ new Set(["selection", "ai-note", "ai-answer"]);
140424
+ ORIGINS = /* @__PURE__ */ new Set(["selection", "read", "ai-note", "ai-answer"]);
140425
+ ADD_ONLY = /* @__PURE__ */ new Set(["selection", "read"]);
140169
140426
  str6 = (value, max2 = 4096) => typeof value === "string" && value.length > 0 && value.length <= max2;
140170
140427
  isRevision = (value) => Number.isSafeInteger(value) || typeof value === "string" && HEX645.test(value);
140171
140428
  revisionOf = (value) => isRevision(value) ? value : null;
140172
140429
  digestOf = (value) => typeof value === "string" && HEX645.test(value) ? value : null;
140173
140430
  asRow = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : null;
140174
- linkKey = (link2) => `${link2.linkEventId}\0${link2.kind}\0${link2.id}`;
140431
+ isIso = (value) => str6(value, 64) && Number.isFinite(Date.parse(value));
140432
+ linkKey = (link2) => ADD_ONLY.has(link2.origin) ? `${link2.origin}\0${link2.messageEventId}\0${link2.kind}\0${link2.id}` : `${link2.linkEventId}\0${link2.kind}\0${link2.id}`;
140175
140433
  }
140176
140434
  });
140177
140435
 
@@ -141331,7 +141589,9 @@ function parseTeklaAllowance(row2) {
141331
141589
  if (row2.allowedForChat !== void 0) {
141332
141590
  const allowed = row2.allowedForChat;
141333
141591
  if (!allowed || typeof allowed !== "object" || Array.isArray(allowed) || !isIsoDate(allowed.grantedAt) || typeof allowed.approvalId !== "string" || !UUID20.test(allowed.approvalId)) throw invalid8();
141334
- result2.allowedForChat = { grantedAt: allowed.grantedAt, approvalId: allowed.approvalId.toLowerCase() };
141592
+ if (allowed.scope === TEKLA_ALLOWANCE_SCOPE) {
141593
+ result2.allowedForChat = { grantedAt: allowed.grantedAt, approvalId: allowed.approvalId.toLowerCase(), scope: TEKLA_ALLOWANCE_SCOPE };
141594
+ }
141335
141595
  }
141336
141596
  if (row2.allowanceRevision !== void 0) {
141337
141597
  if (!isRevision2(row2.allowanceRevision)) throw invalid8();
@@ -141365,7 +141625,7 @@ function grantTeklaAllowance(binding, approvalId, at = (/* @__PURE__ */ new Date
141365
141625
  const id2 = approvalId.toLowerCase();
141366
141626
  return {
141367
141627
  ...withAllowanceDecision(binding, { action: "grant", at, revision, approvalId: id2 }),
141368
- allowedForChat: { grantedAt: at, approvalId: id2 }
141628
+ allowedForChat: { grantedAt: at, approvalId: id2, scope: TEKLA_ALLOWANCE_SCOPE }
141369
141629
  };
141370
141630
  }
141371
141631
  async function revokeChatTeklaAllowance(owner3, chatId) {
@@ -142127,12 +142387,42 @@ function parseTeklaSelectedPart(value) {
142127
142387
  const texts = [row2.mark, row2.name, row2.profile, row2.material];
142128
142388
  if (texts.some((text9) => typeof text9 !== "string" || Array.from(text9).length > TEKLA_PART_TEXT_LIMIT || /[\u0000-\u001f\u007f]/u.test(text9))) return null;
142129
142389
  if (row2.weightKg !== null && !isWeight2(row2.weightKg)) return null;
142390
+ if (row2.guid !== void 0 && (typeof row2.guid !== "string" || !TEKLA_GUID.test(row2.guid))) return null;
142130
142391
  return {
142131
142392
  mark: row2.mark,
142132
142393
  name: row2.name,
142133
142394
  profile: row2.profile,
142134
142395
  material: row2.material,
142135
- weightKg: row2.weightKg
142396
+ weightKg: row2.weightKg,
142397
+ ...row2.guid !== void 0 ? { guid: row2.guid } : {}
142398
+ };
142399
+ }
142400
+ function parseLinkedPartCheck(row2, listed, invalid8) {
142401
+ const { linkedPartsChecked: checked2, missingLinkedParts: missing, linkedPartsUnchecked: unchecked, linkedPartsCheck: shortfall } = row2;
142402
+ if (shortfall !== void 0 && !TEKLA_LINKED_PARTS_CHECKS.includes(shortfall)) throw invalid8();
142403
+ const marker = shortfall !== void 0 ? { linkedPartsCheck: shortfall } : {};
142404
+ if (checked2 === void 0 && missing === void 0 && unchecked === void 0) return marker;
142405
+ if (shortfall === "unavailable" || !isCount4(checked2) || checked2 > TEKLA_LINKED_PART_CHECK_LIMIT || !Array.isArray(missing) || missing.length > checked2 || new Set(missing).size !== missing.length || missing.some((guid3) => typeof guid3 !== "string" || !TEKLA_GUID.test(guid3) || listed.has(guid3)) || unchecked !== void 0 && !isCount4(unchecked)) throw invalid8();
142406
+ return { linkedPartsChecked: checked2, missingLinkedParts: [...missing], ...unchecked !== void 0 ? { linkedPartsUnchecked: unchecked } : {}, ...marker };
142407
+ }
142408
+ function teklaReadLinkedQuestion(resolved, events, turnId, payload) {
142409
+ const parts = payload.parts ?? [];
142410
+ if (resolved.owner.kind !== "project" || payload.status !== "verified-for-selection-read" || payload.complete !== true || payload.truncated !== false || !parts.length || parts.some((part) => !part.guid)) return void 0;
142411
+ const question = events.find((event) => event.type === "user-message" && event.turnId === turnId);
142412
+ if (!question) return void 0;
142413
+ const linked = new Set(parts.map((part) => part.guid));
142414
+ for (const event of events) {
142415
+ if (event.type !== "tekla-read" || event.turnId !== turnId || !event.payload.linkedQuestion) continue;
142416
+ for (const part of Array.isArray(event.payload.parts) ? event.payload.parts : []) {
142417
+ if (typeof part?.guid === "string") linked.add(part.guid);
142418
+ }
142419
+ }
142420
+ if (linked.size > MAX_LISTED_SUBJECTS) return void 0;
142421
+ return {
142422
+ messageEventId: question.eventId,
142423
+ messageSequence: question.sequence,
142424
+ question: subjectNote(typeof question.payload.text === "string" ? question.payload.text : ""),
142425
+ askedAt: question.createdAt
142136
142426
  };
142137
142427
  }
142138
142428
  function parseChatTeklaReadPayload(value) {
@@ -142158,7 +142448,9 @@ function parseChatTeklaReadPayload(value) {
142158
142448
  if (!selection) return verified;
142159
142449
  const parts = Array.isArray(row2.parts) && row2.parts.length <= TEKLA_SELECTION_ROW_LIMIT ? row2.parts.map(parseTeklaSelectedPart) : null;
142160
142450
  if (!parts || parts.some((part) => part === null) || !isCount4(row2.partCount) || row2.partCount < parts.length || !isWeight2(row2.totalWeightKg) || row2.truncated !== row2.partCount > parts.length || typeof row2.complete !== "boolean" || !isCount4(row2.weightMissing) || row2.weightMissing > row2.partCount || !isCount4(row2.otherObjectCount)) throw invalid8();
142161
- return {
142451
+ const guids = parts.map((part) => part.guid).filter((guid3) => guid3 !== void 0);
142452
+ if (new Set(guids).size !== guids.length) throw invalid8();
142453
+ const listed = {
142162
142454
  ...verified,
142163
142455
  parts,
142164
142456
  partCount: row2.partCount,
@@ -142168,6 +142460,7 @@ function parseChatTeklaReadPayload(value) {
142168
142460
  weightMissing: row2.weightMissing,
142169
142461
  otherObjectCount: row2.otherObjectCount
142170
142462
  };
142463
+ return { ...listed, ...parseLinkedPartCheck(row2, new Set(guids), invalid8) };
142171
142464
  }
142172
142465
  if (typeof row2.code !== "string" || !/^[a-z][a-z-]{0,63}$/u.test(row2.code) || typeof row2.message !== "string" || !row2.message.trim() || row2.message.length > 2048 || row2.modelName !== void 0 || row2.hostPid !== void 0) throw invalid8();
142173
142466
  return { ...base2, code: row2.code, message: row2.message };
@@ -142185,21 +142478,24 @@ async function appendChatTeklaReadIfTurnCurrent(owner3, chatId, expected2, paylo
142185
142478
  const parsed = parseChatTeklaReadPayload(payload);
142186
142479
  const resolved = resolveOwner2(owner3);
142187
142480
  const id2 = assertUuid2(chatId, "chat identity");
142188
- return withChatMutation(resolved, id2, "recording Tekla read", () => {
142481
+ return withChatMutation(resolved, id2, "recording Tekla read", async () => {
142189
142482
  const chat = readChatAt(resolved, id2);
142190
- const recorded = readEventJournal(resolved, chat).find((event2) => event2.eventId === parsed.approvalId);
142483
+ const events = readEventJournal(resolved, chat);
142484
+ const recorded = events.find((event2) => event2.eventId === parsed.approvalId);
142191
142485
  if (recorded) return { appended: true, event: recorded };
142192
142486
  const active2 = chat.activeTurn;
142193
142487
  if (!active2 || active2.turnId !== expected2.turnId.toLowerCase() || active2.ownershipGeneration !== expected2.ownershipGeneration.toLowerCase() || active2.connectionRevision !== expected2.connectionRevision.toLowerCase() || chat.connectionRevision !== expected2.connectionRevision.toLowerCase() || active2.dispatchState !== "acknowledged" || chat.state !== "running" && chat.state !== "awaiting-approval" || !stillWanted()) {
142194
142488
  return { appended: false };
142195
142489
  }
142490
+ const linkedQuestion = teklaReadLinkedQuestion(resolved, events, active2.turnId, parsed);
142196
142491
  const event = appendChatEventLocked(resolved, id2, {
142197
142492
  eventId: parsed.approvalId,
142198
142493
  turnId: expected2.turnId,
142199
142494
  clientSubmissionId: expected2.clientSubmissionId,
142200
142495
  type: "tekla-read",
142201
- payload: parsed
142496
+ payload: { ...parsed, ...linkedQuestion ? { linkedQuestion } : {} }
142202
142497
  });
142498
+ await indexSubjectLinks(resolved, event);
142203
142499
  return { appended: true, event };
142204
142500
  });
142205
142501
  }
@@ -143359,9 +143655,13 @@ var init_chat_store = __esm({
143359
143655
  "truncated",
143360
143656
  "complete",
143361
143657
  "weightMissing",
143362
- "otherObjectCount"
143658
+ "otherObjectCount",
143659
+ "linkedPartsChecked",
143660
+ "missingLinkedParts",
143661
+ "linkedPartsUnchecked",
143662
+ "linkedPartsCheck"
143363
143663
  ];
143364
- TEKLA_PART_KEYS = ["mark", "name", "profile", "material", "weightKg"];
143664
+ TEKLA_PART_KEYS = ["mark", "name", "profile", "material", "weightKg", "guid"];
143365
143665
  TEKLA_PART_TEXT_LIMIT = 64;
143366
143666
  TEKLA_READ_PAYLOAD_BUDGET = MAX_EVENT_BYTES - 16 * 1024;
143367
143667
  isCount4 = (value) => Number.isSafeInteger(value) && value >= 0;
@@ -163739,76 +164039,26 @@ var init_zod = __esm({
163739
164039
  }
163740
164040
  });
163741
164041
 
163742
- // ../web/model-property-display.js
163743
- function teklaPropertyGroups(rows2) {
163744
- const properties = [], udas = [], nativeGroups = /* @__PURE__ */ new Map();
163745
- for (const row2 of Array.isArray(rows2) ? rows2 : []) {
163746
- const isUda = row2.isUda === true || row2.groupName === "User-defined attributes" || row2.groupName === "User-defined attributes (UDA)" || row2.groupName === "UDA";
163747
- if (isUda) {
163748
- udas.push(row2);
163749
- continue;
163750
- }
163751
- if (row2.semantic && Number.isSafeInteger(row2.groupOrdinal)) {
163752
- const key5 = `${row2.groupOrdinal}\0${row2.groupName}`;
163753
- const group = nativeGroups.get(key5) || { key: key5, name: row2.groupName, ordinal: row2.groupOrdinal, rows: [], expanded: true };
163754
- group.rows.push(row2);
163755
- nativeGroups.set(key5, group);
163756
- continue;
164042
+ // chat-subject-link.ts
164043
+ function teklaReadParts(events, turnId) {
164044
+ const question = /* @__PURE__ */ new Map();
164045
+ const read3 = /* @__PURE__ */ new Map();
164046
+ const readThisTurn = /* @__PURE__ */ new Set();
164047
+ for (const event of events) {
164048
+ const payload = event.type === "tekla-read" ? event.payload : null;
164049
+ if (!payload || payload.status !== "verified-for-selection-read" || payload.operation !== TEKLA_SELECTION_READ_OPERATION || !Array.isArray(payload.parts)) continue;
164050
+ const linked = event.turnId === turnId && Boolean(asRow2(payload.linkedQuestion));
164051
+ for (const item of payload.parts) {
164052
+ const part = asRow2(item);
164053
+ if (!part || typeof part.guid !== "string" || !TEKLA_GUID.test(part.guid)) continue;
164054
+ const label2 = modelSubjectLabel("tekla", part);
164055
+ read3.set(part.guid, label2);
164056
+ if (event.turnId === turnId) readThisTurn.add(part.guid);
164057
+ if (linked) question.set(part.guid, label2);
163757
164058
  }
163758
- if (/^(?:Raw\b|provenance|Reader coverage|Technical details|System)/i.test(row2.groupName || "")) continue;
163759
- if (row2.groupName === "Overview" && ["Object kind", "Subtype"].includes(row2.name)) continue;
163760
- if (row2.groupName === "Source identity" && row2.name === "Native type") continue;
163761
- const item = row2.name === "Object ID" ? { ...row2, name: "ID" } : row2;
163762
- properties.push(item);
163763
- }
163764
- const ordered = (values2) => values2.slice().sort((a, b) => (a.propertyOrdinal ?? 0) - (b.propertyOrdinal ?? 0));
163765
- return [
163766
- ...[...nativeGroups.values()].sort((a, b) => a.ordinal - b.ordinal).map((group) => ({ ...group, rows: ordered(group.rows) })),
163767
- ...properties.length ? [{ key: "tekla-properties", name: "Properties", rows: properties, expanded: true }] : [],
163768
- ...udas.length ? [{ key: "tekla-udas", name: "User-defined attributes (UDA)", rows: ordered(udas), expanded: false }] : []
163769
- ];
163770
- }
163771
- function teklaObjectFields(entity, rows2 = []) {
163772
- const source = teklaPropertyGroups(rows2).filter((group) => group.key !== "tekla-udas").flatMap((group) => group.rows);
163773
- const value = (name) => source.find((row2) => row2.name === name)?.value;
163774
- return {
163775
- name: value("Name") ?? null,
163776
- profile: value("Profile") ?? null,
163777
- id: value("ID") ?? entity.objectId ?? (/^element:([0-9]+)$/.exec(entity.id || "")?.[1] ?? null)
163778
- };
163779
- }
163780
- function teklaObjectLabel(entity, rows2 = []) {
163781
- const fields = teklaObjectFields(entity, rows2);
163782
- return [
163783
- fields.name != null ? `Name: ${fields.name}` : null,
163784
- fields.profile != null ? `Profile: ${fields.profile}` : null,
163785
- fields.id != null ? `ID: ${fields.id}` : null
163786
- ].filter(Boolean).join(" \xB7 ") || entity.typeName || "Tekla object";
163787
- }
163788
- var init_model_property_display = __esm({
163789
- "../web/model-property-display.js"() {
163790
- init_display_units();
163791
164059
  }
163792
- });
163793
-
163794
- // ../web/model-chat-questions.js
163795
- function modelSubjectLabel(source, entity, rows2 = []) {
163796
- const id2 = String(entity?.id ?? "");
163797
- if (source === "tekla-parser") {
163798
- const fields = teklaObjectFields(entity || {}, rows2);
163799
- const label2 = teklaObjectLabel(entity || {}, rows2);
163800
- return fields.id == null ? `${label2} \xB7 ${id2}` : label2;
163801
- }
163802
- const what = entity?.name || entity?.typeName || entity?.categoryName || entity?.category || "Revit element";
163803
- return `${what} \xB7 ${id2}`;
164060
+ return { question, read: read3, readThisTurn };
163804
164061
  }
163805
- var init_model_chat_questions = __esm({
163806
- "../web/model-chat-questions.js"() {
163807
- init_model_property_display();
163808
- }
163809
- });
163810
-
163811
- // chat-subject-link.ts
163812
164062
  function steelSubjectLabels(doc) {
163813
164063
  const labels = /* @__PURE__ */ new Map();
163814
164064
  const root9 = doc && typeof doc === "object" && !Array.isArray(doc) ? doc : {};
@@ -163873,7 +164123,7 @@ function rawInput(value) {
163873
164123
  if (row2.note !== void 0 && typeof row2.note !== "string") return "note must be text.";
163874
164124
  return { role: row2.role, subjects, note: row2.note };
163875
164125
  }
163876
- var import_node_crypto67, LINK_SUBJECTS_TOOL_NAME, LINK_SUBJECTS_DESCRIPTION, LINK_SUBJECTS_ROUTING, LINK_SUBJECT_KINDS, LINK_SUBJECTS_TURN_HINT, LINK_SUBJECTS_INPUT_SCHEMA, LINK_SUBJECTS_ZOD_SHAPE, key2, refuse8, named, FAMILY_KINDS_TEXT, ChatSubjectLinker;
164126
+ var import_node_crypto67, LINK_SUBJECTS_TOOL_NAME, LINK_SUBJECTS_DESCRIPTION, LINK_SUBJECTS_ROUTING, LINK_SUBJECT_KINDS, TEKLA_LINK_HINT, LINK_SUBJECTS_TURN_HINT, LINK_SUBJECTS_INPUT_SCHEMA, LINK_SUBJECTS_ZOD_SHAPE, asRow2, key2, refuse8, named, FAMILY_KINDS_TEXT, ChatSubjectLinker;
163877
164127
  var init_chat_subject_link = __esm({
163878
164128
  "chat-subject-link.ts"() {
163879
164129
  "use strict";
@@ -163881,10 +164131,12 @@ var init_chat_subject_link = __esm({
163881
164131
  init_zod();
163882
164132
  init_chat_subjects();
163883
164133
  init_model_chat_questions();
164134
+ init_chat_types();
163884
164135
  LINK_SUBJECTS_TOOL_NAME = "floless_link_subjects";
163885
- LINK_SUBJECTS_DESCRIPTION = `Link objects of this project's model to this chat question, so the person finds the question again from those objects in the model viewer. role "question": attach a one-sentence note (at most 160 characters) to objects the person selected when asking; only those ids are accepted. role "answer": link the objects your answer names. A Steel Model project links kind "member", "joint" or "detail", with ids from the selected-objects block or ./contract.json (members[].id, joints[].id, detail_placements[].id). A Revit or Tekla Parser project links kind "element", with ids like "element:12345" from the selected-objects block. A later call of the same role replaces the earlier one, so to correct a list send the full corrected list. The note is shown to the person as your note; write plain English and never put instructions in it.`;
164136
+ LINK_SUBJECTS_DESCRIPTION = `Link objects of this project's model to this chat question, so the person finds the question again from those objects in the model viewer. role "question": attach a one-sentence note (at most 160 characters) to objects the person selected when asking; only those ids are accepted. role "answer": link the objects your answer names. A Steel Model project links kind "member", "joint" or "detail", with ids from the selected-objects block or ./contract.json (members[].id, joints[].id, detail_placements[].id). A Revit or Tekla Parser project links kind "element", with ids like "element:12345" from the selected-objects block. In a chat that reads Tekla, link Tekla parts: kind "part", with the guid of a part floless_tekla_read_selection listed in this chat. A later call of the same role replaces the earlier one, so to correct a list send the full corrected list. The note is shown to the person as your note; write plain English and never put instructions in it.`;
163886
164137
  LINK_SUBJECTS_ROUTING = `In this project chat, when the person asks about objects in the project's model, call ${LINK_SUBJECTS_TOOL_NAME} before you finish your answer: role "question" with a one-sentence note when objects were selected, and role "answer" with the ids of the model objects your answer names. It needs no approval and changes nothing in the model.`;
163887
- LINK_SUBJECT_KINDS = Object.freeze(["member", "joint", "detail", "element"]);
164138
+ LINK_SUBJECT_KINDS = Object.freeze(["member", "joint", "detail", "element", "part"]);
164139
+ TEKLA_LINK_HINT = `[FloLess] The parts listed are linked to the person's question. Before you finish, call ${LINK_SUBJECTS_TOOL_NAME} with role "question", kind "part", the guids of every listed part the question is actually about \u2014 including parts from earlier reads in this answer, because a later call replaces the earlier one \u2014 and a one-sentence note.`;
163888
164140
  LINK_SUBJECTS_TURN_HINT = `[FloLess] Before you finish, call ${LINK_SUBJECTS_TOOL_NAME} with role "question", these objects' ids and a one-sentence note on what the person asked about them.`;
163889
164141
  LINK_SUBJECTS_INPUT_SCHEMA = Object.freeze({
163890
164142
  type: "object",
@@ -163918,6 +164170,7 @@ var init_chat_subject_link = __esm({
163918
164170
  subjects: external_exports.array(external_exports.object({ kind: external_exports.enum(LINK_SUBJECT_KINDS), id: external_exports.string().min(1).max(200) }).strict()).min(1).max(MAX_LISTED_SUBJECTS),
163919
164171
  note: external_exports.string().max(2e3).optional()
163920
164172
  };
164173
+ asRow2 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : null;
163921
164174
  key2 = (kind2, id2) => `${kind2}\0${id2}`;
163922
164175
  refuse8 = (text9) => ({ success: false, text: text9 });
163923
164176
  named = (item) => `${item.kind} ${JSON.stringify(item.id)}`;
@@ -163937,12 +164190,17 @@ var init_chat_subject_link = __esm({
163937
164190
  if (chat.owner.kind !== "project" || !chat.owner.projectId) {
163938
164191
  return refuse8("This chat is not a project chat, so it has no model objects to link.");
163939
164192
  }
164193
+ const raw = rawInput(input2.arguments);
164194
+ if (typeof raw === "string") return refuse8(`FloLess did not link anything. ${raw}`);
164195
+ const parts = raw.subjects.filter((item) => item.kind === "part").length;
164196
+ if (parts === raw.subjects.length) return this.linkTeklaParts(chat, turn, raw, input2.callId);
164197
+ if (parts) {
164198
+ return refuse8("FloLess did not link anything: link one model\u2019s objects per call \u2014 Tekla parts separately from this project\u2019s model objects.");
164199
+ }
163940
164200
  const family = this.deps.modelFamily(chat.owner.projectId);
163941
164201
  if (family === "unsupported") {
163942
164202
  return refuse8("Object links are not available for this project\u2019s model yet, so FloLess did not link anything.");
163943
164203
  }
163944
- const raw = rawInput(input2.arguments);
163945
- if (typeof raw === "string") return refuse8(`FloLess did not link anything. ${raw}`);
163946
164204
  const kinds = subjectKinds(family);
163947
164205
  const foreign = raw.subjects.find((item) => !kinds.has(item.kind));
163948
164206
  if (foreign) return refuse8(`FloLess did not link anything: unknown kind ${JSON.stringify(foreign.kind)}. ${FAMILY_KINDS_TEXT[family]}`);
@@ -163991,21 +164249,81 @@ var init_chat_subject_link = __esm({
163991
164249
  return refuse8(`FloLess did not link anything: a "question" note may name only the selected objects, and ${outside.slice(0, 5).map(named).join(", ")}${outside.length > 5 ? ` and ${outside.length - 5} more` : ""} ${outside.length === 1 ? "was" : "were"} not selected.`);
163992
164250
  }
163993
164251
  }
164252
+ const notFound = model ? items.filter((item) => !model.labels.has(key2(item.kind, item.id))) : [];
164253
+ return this.record(chat, turn, raw.role, input2.callId, {
164254
+ role: raw.role,
164255
+ source: family,
164256
+ revision,
164257
+ ...sourceDigest2 !== void 0 ? { sourceDigest: sourceDigest2 } : {},
164258
+ items,
164259
+ aiNote,
164260
+ toolCallId: input2.callId
164261
+ }, { checked: Boolean(model), notFound });
164262
+ }
164263
+ /**
164264
+ * A call naming live Tekla parts (#1653 stage 4). Each GUID must be one FloLess itself read from Tekla in this chat:
164265
+ * for a note, a part this question's own reads linked; for an answer, any part a verified read listed here. An id
164266
+ * that cannot be verified is refused, never stored unchecked — a live model has no snapshot to check it against later.
164267
+ */
164268
+ async linkTeklaParts(chat, turn, raw, callId) {
164269
+ if (!chat.teklaModelRead?.operations.includes(TEKLA_SELECTION_READ_OPERATION) || !this.deps.teklaParts) {
164270
+ return refuse8("This chat does not read Tekla, so it has no Tekla parts to link. FloLess did not link anything.");
164271
+ }
164272
+ const aiNote = subjectLinkNote(raw.note);
164273
+ if (raw.role === "question" && !aiNote) return refuse8('FloLess did not link anything. A "question" link needs a one-sentence note.');
164274
+ let known3;
164275
+ try {
164276
+ known3 = this.deps.teklaParts({ kind: "project", projectId: chat.owner.projectId }, chat.chatId, turn.turnId);
164277
+ } catch (error62) {
164278
+ console.warn("[chat] object links: the Tekla reads of this chat could not be read", JSON.stringify({
164279
+ chatId: chat.chatId,
164280
+ error: error62 instanceof Error ? error62.message : String(error62)
164281
+ }));
164282
+ return refuse8("FloLess could not check which Tekla parts this chat read, so it did not link anything. You may try once more.");
164283
+ }
164284
+ const allowed = raw.role === "question" ? known3.question : known3.read;
164285
+ const readNotLinked = 'FloLess did not link anything: the parts read in this answer were not linked to this question, because that read was cut short, stopped at its limit, or listed more parts than one question can link. Name them with role "answer" instead; do not read the selection again for this.';
164286
+ if (raw.role === "question" && !allowed.size) {
164287
+ if (raw.subjects.some((item) => known3.readThisTurn.has(item.id))) return refuse8(readNotLinked);
164288
+ return refuse8("No Tekla parts are linked to this question yet: read the selection with floless_tekla_read_selection first. FloLess did not link anything.");
164289
+ }
164290
+ const outside = raw.subjects.filter((item) => !allowed.has(item.id));
164291
+ if (raw.role === "question" && outside.some((item) => known3.readThisTurn.has(item.id))) return refuse8(readNotLinked);
164292
+ if (outside.length) {
164293
+ const list3 = `${outside.slice(0, 5).map(named).join(", ")}${outside.length > 5 ? ` and ${outside.length - 5} more` : ""}`;
164294
+ const verb = outside.length === 1 ? "was" : "were";
164295
+ return refuse8(raw.role === "question" ? `FloLess did not link anything: a "question" note may name only the parts linked to this question by its reads, and ${list3} ${verb} not linked to this question.` : `FloLess did not link anything: ${list3} ${verb} not read from Tekla in this chat. Read them with floless_tekla_read_selection, then link them.`);
164296
+ }
164297
+ let items;
164298
+ try {
164299
+ items = normalizeChatSubjects({
164300
+ source: "tekla",
164301
+ revision: null,
164302
+ items: raw.subjects.map((item) => ({ ...item, label: allowed.get(item.id) ?? item.id }))
164303
+ }).items;
164304
+ } catch (error62) {
164305
+ if (error62 instanceof ChatSubjectsError) return refuse8(`FloLess did not link anything: ${error62.message}.`);
164306
+ throw error62;
164307
+ }
164308
+ return this.record(
164309
+ chat,
164310
+ turn,
164311
+ raw.role,
164312
+ callId,
164313
+ { role: raw.role, source: "tekla", revision: null, items, aiNote, toolCallId: callId },
164314
+ { checked: true, notFound: [] }
164315
+ );
164316
+ }
164317
+ /** Appends one call's links conditionally on its turn, announces them, and tells the chat model what was kept. */
164318
+ async record(chat, turn, role, callId, link2, report) {
164319
+ const items = link2.items;
163994
164320
  let appended;
163995
164321
  try {
163996
164322
  appended = await this.deps.append({ kind: "project", projectId: chat.owner.projectId }, chat.chatId, {
163997
164323
  turnId: turn.turnId,
163998
164324
  ownershipGeneration: turn.ownershipGeneration,
163999
164325
  connectionRevision: turn.connectionRevision
164000
- }, subjectLinkEventId(chat.chatId, turn.turnId, input2.callId), {
164001
- role: raw.role,
164002
- source: family,
164003
- revision,
164004
- ...sourceDigest2 !== void 0 ? { sourceDigest: sourceDigest2 } : {},
164005
- items,
164006
- aiNote,
164007
- toolCallId: input2.callId
164008
- });
164326
+ }, subjectLinkEventId(chat.chatId, turn.turnId, callId), link2);
164009
164327
  } catch (error62) {
164010
164328
  console.warn("[chat] object links could not be saved", JSON.stringify({
164011
164329
  chatId: chat.chatId,
@@ -164020,7 +164338,7 @@ var init_chat_subject_link = __esm({
164020
164338
  return refuse8("The question has already finished, so FloLess did not link anything.");
164021
164339
  }
164022
164340
  const recorded = appended.event.payload;
164023
- const sameCall = recorded.role === raw.role && Array.isArray(recorded.items) && recorded.items.length === items.length && recorded.items.every((item, index) => item.kind === items[index].kind && item.id === items[index].id);
164341
+ const sameCall = recorded.role === role && Array.isArray(recorded.items) && recorded.items.length === items.length && recorded.items.every((item, index) => item.kind === items[index].kind && item.id === items[index].id);
164024
164342
  if (!sameCall) {
164025
164343
  return refuse8("FloLess already recorded this call with different objects, so it did not change them. Call again to link a new list.");
164026
164344
  }
@@ -164029,12 +164347,12 @@ var init_chat_subject_link = __esm({
164029
164347
  } catch (error62) {
164030
164348
  console.warn("[chat] object links were saved but not announced live", error62 instanceof Error ? error62.message : String(error62));
164031
164349
  }
164032
- const notFound = model ? items.filter((item) => !model.labels.has(key2(item.kind, item.id))) : [];
164350
+ const { checked: checked2, notFound } = report;
164033
164351
  return { success: true, text: JSON.stringify({
164034
164352
  linked: items.length,
164035
- role: raw.role,
164036
- ...model ? { notFound: notFound.map(named) } : { checked: false },
164037
- message: (raw.role === "question" ? `Noted ${items.length} selected object${items.length === 1 ? "" : "s"}.` : `Linked ${items.length} object${items.length === 1 ? "" : "s"} to your answer.`) + (!model ? " FloLess could not read the project\u2019s model, so the ids were not checked." : "") + (notFound.length ? ` ${notFound.length} ${notFound.length === 1 ? "is" : "are"} not in the current model and will show under objects not in the model; to correct them, call again with the full corrected list.` : "")
164353
+ role,
164354
+ ...checked2 ? { notFound: notFound.map(named) } : { checked: false },
164355
+ message: (role === "question" ? `Noted ${items.length} selected object${items.length === 1 ? "" : "s"}.` : `Linked ${items.length} object${items.length === 1 ? "" : "s"} to your answer.`) + (!checked2 ? " FloLess could not read the project\u2019s model, so the ids were not checked." : "") + (notFound.length ? ` ${notFound.length} ${notFound.length === 1 ? "is" : "are"} not in the current model and will show under objects not in the model; to correct them, call again with the full corrected list.` : "")
164038
164356
  }) };
164039
164357
  }
164040
164358
  };
@@ -164050,13 +164368,13 @@ function teklaChatAllowable(chat, approval) {
164050
164368
  const binding = chat.teklaModelRead;
164051
164369
  if (approval.explicitOnly !== true || !approval.tool || !Object.hasOwn(TEKLA_TOOL_OPERATIONS, approval.tool) || !binding) return false;
164052
164370
  const operation = TEKLA_TOOL_OPERATIONS[approval.tool];
164053
- return binding.operations.includes(operation) && teklaReadApprovalSummary(binding, operation) === approval.summary;
164371
+ return binding.operations.includes(operation) && teklaReadApprovalSummary(binding, operation, chat.owner.kind === "project") === approval.summary;
164054
164372
  }
164055
164373
  function teklaChatAllowanceCovers(chat, approval) {
164056
164374
  return Boolean(chat.teklaModelRead?.allowedForChat) && teklaChatAllowable(chat, approval);
164057
164375
  }
164058
- function teklaReadApprovalSummary(binding, operation = TEKLA_MODEL_READ_OPERATION) {
164059
- const what = operation === TEKLA_SELECTION_READ_OPERATION ? "the parts selected in the open Tekla model" : "the open Tekla model name";
164376
+ function teklaReadApprovalSummary(binding, operation = TEKLA_MODEL_READ_OPERATION, checksLinkedParts = true) {
164377
+ const what = operation !== TEKLA_SELECTION_READ_OPERATION ? "the open Tekla model name" : checksLinkedParts ? "the parts selected in the open Tekla model, and whether parts linked to earlier questions are still in it," : "the parts selected in the open Tekla model";
164060
164378
  return `Read ${what} through ${binding.sourcePath} (Tekla ${binding.hostVersion}). Nothing in the model changes.`;
164061
164379
  }
164062
164380
  function ownerInput(chat) {
@@ -164147,7 +164465,7 @@ var init_chat_integration_tools = __esm({
164147
164465
  kind: "tekla-read",
164148
164466
  integration: "tekla-model-library",
164149
164467
  label: "Tekla model library",
164150
- description: "Read the parts currently selected in the model open in Tekla Structures, through the model library bound to this FloLess chat: for each part the assembly mark, name, profile, material and weight (kg), plus the part count and total weight. Selected assemblies are read as their parts; at most 200 parts are listed. It is read-only; FloLess handles approval for every call and checks it live. It returns a verified result or a refusal; report a refusal as it is and do not try another route to the selection.",
164468
+ description: "Read the parts currently selected in the model open in Tekla Structures, through the model library bound to this FloLess chat: for each part the assembly mark, name, profile, material, weight (kg) and guid, plus the part count and total weight. Selected assemblies are read as their parts; at most 200 parts are listed. It is read-only; FloLess handles approval for every call and checks it live. It returns a verified result or a refusal; report a refusal as it is and do not try another route to the selection.",
164151
164469
  inputSchema: Object.freeze({ type: "object", properties: Object.freeze({}), additionalProperties: false })
164152
164470
  }),
164153
164471
  Object.freeze({
@@ -164203,7 +164521,7 @@ var init_chat_integration_tools = __esm({
164203
164521
  const spec = this.spec(toolName);
164204
164522
  if (!spec) return { summary: "FloLess refused an unknown integration tool." };
164205
164523
  if (spec.kind === "tekla-read") {
164206
- const summary2 = chat.teklaModelRead && isBound(chat, spec) ? teklaReadApprovalSummary(chat.teklaModelRead, TEKLA_TOOL_OPERATIONS[spec.name]) : this.unboundText(toolName);
164524
+ const summary2 = chat.teklaModelRead && isBound(chat, spec) ? teklaReadApprovalSummary(chat.teklaModelRead, TEKLA_TOOL_OPERATIONS[spec.name], chat.owner.kind === "project") : this.unboundText(toolName);
164207
164525
  return { summary: summary2, explicitOnly: true, tool: spec.name };
164208
164526
  }
164209
164527
  const binding = chat.integrationBindings.find((candidate2) => candidate2.integration === spec.integration);
@@ -171207,7 +171525,7 @@ function requestScratchLiveness(request) {
171207
171525
  failure2 = error62;
171208
171526
  }
171209
171527
  if (state3 === "unreadable") {
171210
- if (chatIsGone(failure2)) return "idle";
171528
+ if (chatIsGone(failure2)) return "gone";
171211
171529
  if (!reportedUnreadableScratch.has(request.id)) {
171212
171530
  reportedUnreadableScratch.add(request.id);
171213
171531
  console.warn(`[request-work] cannot read the conversation of request ${request.id}; keeping its scratch until it can be read:`, failure2);
@@ -230473,6 +230791,22 @@ var init_chat_integration_relay = __esm({
230473
230791
  });
230474
230792
 
230475
230793
  // chat-tekla-read-relay.ts
230794
+ function newestLinkedParts(links, limit = TEKLA_LINKED_PART_CHECK_LIMIT) {
230795
+ const ids2 = [];
230796
+ const seen = /* @__PURE__ */ new Set();
230797
+ for (const link2 of [...links].sort((a, b) => b.createdAt.localeCompare(a.createdAt))) {
230798
+ if (seen.has(link2.id)) continue;
230799
+ seen.add(link2.id);
230800
+ ids2.push(link2.id);
230801
+ }
230802
+ return { ids: ids2.slice(0, limit), unchecked: Math.max(0, ids2.length - limit) };
230803
+ }
230804
+ async function teklaLinkedPartsToCheck(owner3) {
230805
+ if (owner3.kind !== "project") return null;
230806
+ const listed = await listChatSubjectLinks(owner3, "tekla");
230807
+ const found = newestLinkedParts(listed.links);
230808
+ return listed.partial ? { ...found, partial: true } : found;
230809
+ }
230476
230810
  function ownerInput6(chat) {
230477
230811
  return chat.owner.kind === "project" ? { kind: "project", projectId: chat.owner.projectId } : { kind: "workflow", workflowId: chat.owner.workflowId };
230478
230812
  }
@@ -230491,24 +230825,27 @@ function canonicalJson2(value) {
230491
230825
  }
230492
230826
  function differingCardFields(recorded, own5) {
230493
230827
  const mine = own5;
230494
- const keys = [.../* @__PURE__ */ new Set([...Object.keys(recorded), ...Object.keys(mine)])].filter((key5) => key5 !== "approvalId");
230828
+ const skip = /* @__PURE__ */ new Set(["approvalId", "linkedQuestion", ...LINKED_PART_CHECK_FIELDS]);
230829
+ const keys = [.../* @__PURE__ */ new Set([...Object.keys(recorded), ...Object.keys(mine)])].filter((key5) => !skip.has(key5));
230495
230830
  return keys.filter((key5) => canonicalJson2(recorded[key5]) !== canonicalJson2(mine[key5])).sort();
230496
230831
  }
230497
230832
  function refusalMessage(result2) {
230498
230833
  return result2.code === "busy" ? "Another Tekla read was already running, so FloLess used this approval without reading the model. Ask again when the other read finishes." : result2.message;
230499
230834
  }
230500
- var NOT_VERIFIED, LEDGER_LIMIT, DEFAULT_DEPS8, READ_FAILED_MESSAGE, RECORD_FAILED_MESSAGE, STOPPED_MESSAGE, UNREAD_RECORD_CODES, ChatTeklaReadRelay;
230835
+ var NOT_VERIFIED, LEDGER_LIMIT, DEFAULT_DEPS8, READ_FAILED_MESSAGE, RECORD_FAILED_MESSAGE, STOPPED_MESSAGE, UNREAD_RECORD_CODES, LINKED_PART_CHECK_FIELDS, ChatTeklaReadRelay;
230501
230836
  var init_chat_tekla_read_relay = __esm({
230502
230837
  "chat-tekla-read-relay.ts"() {
230503
230838
  "use strict";
230504
230839
  init_chat_store();
230505
230840
  init_chat_integration_tools();
230841
+ init_chat_subject_link();
230506
230842
  init_tekla_library_read();
230507
230843
  init_chat_types();
230508
230844
  NOT_VERIFIED = "The generated Graft agent and its other commands were not run or verified.";
230509
230845
  LEDGER_LIMIT = 256;
230510
230846
  DEFAULT_DEPS8 = {
230511
- read: (sourcePath2, operation, signal) => runTeklaLibraryRead(sourcePath2, { signal, operation }),
230847
+ read: (sourcePath2, operation, signal, linkedParts) => runTeklaLibraryRead(sourcePath2, { signal, operation, ...linkedParts ? { linkedParts } : {} }),
230848
+ linkedParts: teklaLinkedPartsToCheck,
230512
230849
  append: appendChatTeklaReadIfTurnCurrent,
230513
230850
  publish: () => {
230514
230851
  },
@@ -230519,6 +230856,7 @@ var init_chat_tekla_read_relay = __esm({
230519
230856
  RECORD_FAILED_MESSAGE = "FloLess could not record the check, so this result is not verified. Ask again.";
230520
230857
  STOPPED_MESSAGE = "The Tekla read was stopped before it finished. Ask again if you still need it.";
230521
230858
  UNREAD_RECORD_CODES = ["chat-record-unreadable", "chat-record-unsafe"];
230859
+ LINKED_PART_CHECK_FIELDS = ["linkedPartsChecked", "missingLinkedParts", "linkedPartsUnchecked", "linkedPartsCheck"];
230522
230860
  ChatTeklaReadRelay = class {
230523
230861
  deps;
230524
230862
  /** approvalId -> the one outcome of that approval. At most one host read per approval in this process. */
@@ -230578,7 +230916,7 @@ var init_chat_tekla_read_relay = __esm({
230578
230916
  }
230579
230917
  const operation = TEKLA_TOOL_OPERATIONS[approval.tool];
230580
230918
  const binding = chat.teklaModelRead;
230581
- if (!binding || !binding.operations.includes(operation) || teklaReadApprovalSummary(binding, operation) !== approval.summary) {
230919
+ if (!binding || !binding.operations.includes(operation) || teklaReadApprovalSummary(binding, operation, chat.owner.kind === "project") !== approval.summary) {
230582
230920
  this.deps.log("the bound Tekla library did not match the approval, so the read was refused", {
230583
230921
  approvalId,
230584
230922
  chatId: chat.chatId,
@@ -230587,20 +230925,39 @@ var init_chat_tekla_read_relay = __esm({
230587
230925
  return unverified("library-not-bound", "The Tekla model library for this chat changed or was removed, so FloLess did not read the model. Verify the model read again in Graft into agent, then choose Continue in AI Chat.");
230588
230926
  }
230589
230927
  const signal = input2.signal;
230590
- const result2 = await this.deps.read(binding.sourcePath, operation, signal);
230928
+ let linked = null;
230929
+ let listing;
230930
+ if (operation === TEKLA_SELECTION_READ_OPERATION) {
230931
+ try {
230932
+ linked = await this.deps.linkedParts(owner3);
230933
+ if (linked?.partial) listing = "partial";
230934
+ } catch (error62) {
230935
+ listing = "unavailable";
230936
+ this.deps.log("the parts linked to earlier questions could not be listed, so this read checks none", {
230937
+ approvalId,
230938
+ chatId: chat.chatId,
230939
+ error: error62 instanceof Error ? error62.message : String(error62)
230940
+ });
230941
+ }
230942
+ }
230943
+ const result2 = await this.deps.read(binding.sourcePath, operation, signal, linked?.ids);
230591
230944
  if (signal?.aborted) return unverified("stopped", STOPPED_MESSAGE);
230592
230945
  const base2 = { approvalId, operation, library: binding.sourcePath, hostVersion: binding.hostVersion };
230593
230946
  let payload;
230594
230947
  if (!result2.ok) {
230595
230948
  payload = { ...base2, status: "unverified", checkedAt: this.deps.now(), code: result2.code, message: refusalMessage(result2) };
230596
230949
  } else if (operation === TEKLA_SELECTION_READ_OPERATION && result2.verification.operation === operation && result2.verification.selection) {
230950
+ const selection = result2.verification.selection;
230951
+ const check3 = selection.linkedPartsCheck ?? listing;
230597
230952
  payload = {
230598
230953
  ...base2,
230599
230954
  status: "verified-for-selection-read",
230600
230955
  checkedAt: result2.verification.verifiedAt,
230601
230956
  modelName: result2.verification.modelName,
230602
230957
  hostPid: result2.verification.hostPid,
230603
- ...result2.verification.selection
230958
+ ...selection,
230959
+ ...linked?.unchecked && selection.missingLinkedParts ? { linkedPartsUnchecked: linked.unchecked } : {},
230960
+ ...check3 ? { linkedPartsCheck: check3 } : {}
230604
230961
  };
230605
230962
  } else if (operation !== TEKLA_SELECTION_READ_OPERATION && result2.verification.operation === operation) {
230606
230963
  payload = {
@@ -230658,8 +231015,15 @@ var init_chat_tekla_read_relay = __esm({
230658
231015
  } catch {
230659
231016
  }
230660
231017
  if (!result2.ok) return unverified(result2.code, refusalMessage(result2));
230661
- const { approvalId: _approvalId, ...card } = payload;
230662
- return { success: true, text: JSON.stringify({ ...card, notVerified: NOT_VERIFIED }) };
231018
+ const recordedCard = appended.event.payload;
231019
+ const { approvalId: _approvalId, ...own5 } = payload;
231020
+ const card = { ...own5 };
231021
+ for (const key5 of LINKED_PART_CHECK_FIELDS) {
231022
+ if (recordedCard[key5] === void 0) delete card[key5];
231023
+ else card[key5] = recordedCard[key5];
231024
+ }
231025
+ const linkedToQuestion = Boolean(recordedCard.linkedQuestion);
231026
+ return { success: true, text: JSON.stringify({ ...card, notVerified: NOT_VERIFIED, ...linkedToQuestion ? { linkHint: TEKLA_LINK_HINT } : {} }) };
230663
231027
  }
230664
231028
  };
230665
231029
  }
@@ -238458,7 +238822,9 @@ ${view.prompt}` : "";
238458
238822
  const snapshot2 = await readContractSnapshot({ appId: getProject(projectId2)?.app ?? "steel-model", projectId: projectId2 });
238459
238823
  return snapshot2 ? { revision: snapshot2.storeRevision, labels: steelSubjectLabels(snapshot2.contract) } : null;
238460
238824
  },
238461
- publish: (event) => chatCoordinator.publishEvent(event)
238825
+ publish: (event) => chatCoordinator.publishEvent(event),
238826
+ // Live Tekla parts (#1653 stage 4) are verified against this chat's own selection receipts, never the project model.
238827
+ teklaParts: (owner3, chatId, turnId) => teklaReadParts(listChatEvents(owner3, chatId), turnId)
238462
238828
  });
238463
238829
  const chatIntegrationTools = new ChatIntegrationToolHost(new ChatIntegrationRelay(chatProviders, aware), chatTeklaReadRelay, chatSubjectLinker);
238464
238830
  claudeChatProvider.setIntegrationTools(chatIntegrationTools);
@@ -238504,7 +238870,13 @@ ${view.prompt}` : "";
238504
238870
  // A new project’s first drawing request is intentionally staged before any prepass exists.
238505
238871
  // Chat is the first action that should process it, so do not apply the normal headless-run
238506
238872
  // readiness gate to this durable intake request.
238507
- canStart: (request) => request.intakeSubmissionId ? true : requestView2(request)?.canRun === true
238873
+ // An imported or existing project's first read has no intake id, and AI Chat is still the
238874
+ // interactive terminal AI its first-read refusal asks for (#1779) — so the same exception applies.
238875
+ canStart: (request) => {
238876
+ if (request.intakeSubmissionId) return true;
238877
+ const view = requestView2(request);
238878
+ return view ? chatCanStartRequest(view) : false;
238879
+ }
238508
238880
  },
238509
238881
  projectIntakes: {
238510
238882
  accepted: readAcceptedProjectChatIntake,