@floless/app 0.164.0 → 0.165.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.
@@ -3947,13 +3947,13 @@ function appVersion() {
3947
3947
  return resolveVersion({
3948
3948
  isSea: isSea2(),
3949
3949
  sqVersionXml: readSqVersionXml(),
3950
- define: true ? "0.164.0" : void 0,
3950
+ define: true ? "0.165.0" : void 0,
3951
3951
  pkgVersion: readPkgVersion()
3952
3952
  });
3953
3953
  }
3954
3954
  function buildVersion(sources2) {
3955
3955
  if (sources2) return resolveBuildVersion(sources2.define, sources2.pkgVersion);
3956
- return resolveBuildVersion(true ? "0.164.0" : void 0, readPkgVersion());
3956
+ return resolveBuildVersion(true ? "0.165.0" : void 0, readPkgVersion());
3957
3957
  }
3958
3958
  function resolveBuildVersion(define, pkgVersion) {
3959
3959
  if (typeof define === "string" && define) return define;
@@ -3971,7 +3971,7 @@ function resolveChannel(s) {
3971
3971
  function appChannel() {
3972
3972
  return resolveChannel({
3973
3973
  isSea: isSea2(),
3974
- define: true ? "0.164.0" : void 0,
3974
+ define: true ? "0.165.0" : void 0,
3975
3975
  // argv[1] is the entry the runtime actually loaded (…/dist/floless-server.cjs), which is what
3976
3976
  // carries the npx cache prefix. Absent under the SEA exe, which never reaches the npx branch.
3977
3977
  modulePath: process.argv[1]
@@ -45380,6 +45380,9 @@ var init_lifecycle_lock = __esm({
45380
45380
  });
45381
45381
 
45382
45382
  // project-types.ts
45383
+ function keepsCorrespondenceRfis(templateId2) {
45384
+ return typeof templateId2 === "string" && CORRESPONDENCE_RFI_PROJECT_TYPES.has(templateId2);
45385
+ }
45383
45386
  function isSourcelessProjectType(id2) {
45384
45387
  return typeof id2 === "string" && SOURCELESS_PROJECT_TYPES.has(id2);
45385
45388
  }
@@ -45394,12 +45397,13 @@ function projectTypeIdConflict(id2) {
45394
45397
  suggestedId
45395
45398
  };
45396
45399
  }
45397
- var GENERAL_PROJECT_APP_ID, SOURCELESS_PROJECT_TYPES;
45400
+ var GENERAL_PROJECT_APP_ID, SOURCELESS_PROJECT_TYPES, CORRESPONDENCE_RFI_PROJECT_TYPES;
45398
45401
  var init_project_types = __esm({
45399
45402
  "project-types.ts"() {
45400
45403
  "use strict";
45401
45404
  GENERAL_PROJECT_APP_ID = "floless-general";
45402
45405
  SOURCELESS_PROJECT_TYPES = /* @__PURE__ */ new Set([GENERAL_PROJECT_APP_ID]);
45406
+ CORRESPONDENCE_RFI_PROJECT_TYPES = /* @__PURE__ */ new Set([GENERAL_PROJECT_APP_ID, "vectorize", "revit-model", "tekla-parser", "drawing-check"]);
45403
45407
  }
45404
45408
  });
45405
45409
 
@@ -45978,6 +45982,10 @@ function resolveTemplateId(id2) {
45978
45982
  if (isSourcelessProjectType(id2)) return id2;
45979
45983
  return readOrigin(id2)?.derivedFrom ?? id2;
45980
45984
  }
45985
+ function resolveTemplateIdStrict(id2) {
45986
+ if (isSourcelessProjectType(id2) || !safeSegment(id2)) return id2;
45987
+ return loadAllStrict()[id2]?.derivedFrom ?? id2;
45988
+ }
45981
45989
  function sameAppLineage(a, b) {
45982
45990
  return a === b || resolveTemplateId(a) === resolveTemplateId(b);
45983
45991
  }
@@ -183593,9 +183601,14 @@ __export(rfi_correspondence_exports, {
183593
183601
  clipUtf8: () => clipUtf8,
183594
183602
  correspondenceCycle: () => correspondenceCycle,
183595
183603
  correspondenceEmailText: () => correspondenceEmailText,
183604
+ correspondenceOpenFact: () => correspondenceOpenFact,
183605
+ correspondenceOpenSummary: () => correspondenceOpenSummary,
183596
183606
  correspondencePayloadHash: () => correspondencePayloadHash,
183607
+ correspondenceProjectAdmission: () => correspondenceProjectAdmission,
183608
+ correspondenceProjectRefusal: () => correspondenceProjectRefusal,
183597
183609
  correspondenceRecoveryKey: () => correspondenceRecoveryKey,
183598
183610
  correspondenceRfiId: () => correspondenceRfiId,
183611
+ correspondenceRfiKind: () => correspondenceRfiKind,
183599
183612
  correspondenceStoreText: () => correspondenceStoreText,
183600
183613
  emptyCorrespondenceFile: () => emptyCorrespondenceFile,
183601
183614
  fileInputProblem: () => fileInputProblem,
@@ -183615,6 +183628,32 @@ __export(rfi_correspondence_exports, {
183615
183628
  storeKeysOf: () => storeKeysOf,
183616
183629
  writeCorrespondenceStore: () => writeCorrespondenceStore
183617
183630
  });
183631
+ function correspondenceProjectRefusal(project3, templateOf) {
183632
+ const admission = correspondenceProjectAdmission(project3, templateOf);
183633
+ return admission.ok ? null : admission.refusal;
183634
+ }
183635
+ function correspondenceProjectAdmission(project3, templateOf) {
183636
+ let template;
183637
+ try {
183638
+ template = typeof project3.app === "string" ? templateOf(project3.app) : void 0;
183639
+ } catch (error62) {
183640
+ console.warn("[rfi-correspondence] project lineage unreadable", { app: project3.app }, error62);
183641
+ return { ok: false, refusal: { status: 503, code: "project-kind-unreadable", error: "FloLess couldn\u2019t read which workflow this project comes from just now. Try again in a moment." } };
183642
+ }
183643
+ if (template === "steel-model") return { ok: false, refusal: { status: 409, code: "not-general", error: "This project\u2019s RFIs are in its steel editor. Open them there." } };
183644
+ if (template === void 0 || !keepsCorrespondenceRfis(template)) return { ok: false, refusal: { status: 409, code: "rfis-not-here", error: "This kind of project doesn\u2019t keep RFIs. Raise them on a General project, or on the project they\u2019re about." } };
183645
+ if (!project3.uuid) return { ok: false, refusal: { status: 409, code: "project-unsigned", error: "This project has no identity yet, so it can\u2019t keep RFIs. Duplicate it from the Workspaces page to give it one." } };
183646
+ return { ok: true, template };
183647
+ }
183648
+ function correspondenceRfiKind(project3, templateOf = resolveTemplateIdStrict) {
183649
+ if (typeof project3.app !== "string") return "not";
183650
+ try {
183651
+ return keepsCorrespondenceRfis(templateOf(project3.app)) ? "keeps" : "not";
183652
+ } catch (error62) {
183653
+ console.warn("[rfi-correspondence] project lineage unreadable", { app: project3.app }, error62);
183654
+ return "unknown";
183655
+ }
183656
+ }
183618
183657
  function statusOf(record9) {
183619
183658
  return statusOfCycle(cycleSince(record9.events, { includeReopened: false }));
183620
183659
  }
@@ -183721,7 +183760,7 @@ function parseEvent2(v10) {
183721
183760
  return onlyKeys6(v10, ["t", "at", "by", "to", "via", "deliveryAttemptId"]) && isPlainAddress(v10.to) && typeof v10.deliveryAttemptId === "string" && v10.deliveryAttemptId.length > 0 && v10.deliveryAttemptId.length <= 200 ? { ...base3, t: "sent", to: v10.to, via: "gmail", deliveryAttemptId: v10.deliveryAttemptId } : null;
183722
183761
  }
183723
183762
  if (v10.settlesAttemptId !== void 0) {
183724
- if (!onlyKeys6(v10, ["t", "at", "by", "to", "via", "how", "settlesAttemptId"]) || !isPlainAddress(v10.to) || typeof v10.settlesAttemptId !== "string" || v10.settlesAttemptId.length === 0 || v10.settlesAttemptId.length > 200) return null;
183763
+ if (!onlyKeys6(v10, ["t", "at", "by", "to", "via", "settlesAttemptId"], ["how"]) || !isPlainAddress(v10.to) || typeof v10.settlesAttemptId !== "string" || v10.settlesAttemptId.length === 0 || v10.settlesAttemptId.length > 200) return null;
183725
183764
  if (v10.via === "email" && v10.how === void 0) return { ...base3, t: "sent", to: v10.to, via: "email", settlesAttemptId: v10.settlesAttemptId };
183726
183765
  return v10.via === "other" && isRfiDeliveryHow(v10.how) ? { ...base3, t: "sent", to: v10.to, via: "other", how: v10.how, settlesAttemptId: v10.settlesAttemptId } : null;
183727
183766
  }
@@ -183914,6 +183953,24 @@ function readCorrespondenceStore(projectId14) {
183914
183953
  return { state: "quarantined", message: QUARANTINED };
183915
183954
  }
183916
183955
  }
183956
+ function correspondenceOpenSummary(projectId14) {
183957
+ const read5 = readCorrespondenceStore(projectId14);
183958
+ if (read5.state !== "ok") throw new Error(read5.message);
183959
+ const open8 = read5.file.records.filter((record9) => {
183960
+ const status = statusOf(record9);
183961
+ return status === "open" || status === "sent";
183962
+ }).map((record9) => ({ id: record9.id, seq: record9.seq, raisedAt: record9.events[0].at }));
183963
+ const oldest = open8.filter((row3) => Number.isFinite(Date.parse(row3.raisedAt))).sort((a, b) => Date.parse(a.raisedAt) - Date.parse(b.raisedAt)).slice(0, 5);
183964
+ return { open: open8.length, oldest };
183965
+ }
183966
+ function correspondenceOpenFact(projectId14, rfiId4) {
183967
+ const read5 = readCorrespondenceStore(projectId14);
183968
+ if (read5.state !== "ok") throw new Error(read5.message);
183969
+ const record9 = read5.file.records.find((candidate2) => candidate2.id === rfiId4);
183970
+ if (!record9) return null;
183971
+ const status = statusOf(record9);
183972
+ return { open: status === "open" || status === "sent", openedAt: Date.parse(record9.events[0].at) };
183973
+ }
183917
183974
  function repairCorrespondenceStore(projectId14) {
183918
183975
  const marker = presence(poisonPath(projectId14));
183919
183976
  if (marker === "absent") return { outcome: "not-quarantined" };
@@ -184100,6 +184157,8 @@ var init_rfi_correspondence = __esm({
184100
184157
  init_rfi_lifecycle_core();
184101
184158
  init_rfi_store_names();
184102
184159
  init_projects_store();
184160
+ init_project_types();
184161
+ init_app_origin_store();
184103
184162
  init_rfi_delivery_journal();
184104
184163
  CORRESPONDENCE_IDENTITY_MESSAGES = {
184105
184164
  changed: "This project changed or another Workspace is open. Look at it again.",
@@ -185780,7 +185839,8 @@ __export(rfi_correspondence_citations_exports, {
185780
185839
  publishWithPins: () => publishWithPins,
185781
185840
  reconcileRfiCitationRetention: () => reconcileRfiCitationRetention,
185782
185841
  rfiCitationOwnerId: () => rfiCitationOwnerId,
185783
- rfiCitationPinId: () => rfiCitationPinId
185842
+ rfiCitationPinId: () => rfiCitationPinId,
185843
+ sweepRfiCitationRetention: () => sweepRfiCitationRetention
185784
185844
  });
185785
185845
  function currentKnowledgePages(projectId14, q10 = "", limit = 200) {
185786
185846
  const generation = readCurrentGeneration(projectId14);
@@ -185907,6 +185967,15 @@ async function reconcileRfiCitationRetention(projects) {
185907
185967
  }
185908
185968
  return result2;
185909
185969
  }
185970
+ async function sweepRfiCitationRetention(projects, kindOf2 = correspondenceRfiKind) {
185971
+ const kinds = projects.map((project3) => ({ project: project3, kind: kindOf2(project3) }));
185972
+ const result2 = await reconcileRfiCitationRetention(kinds.filter((row3) => row3.kind === "keeps").map((row3) => row3.project));
185973
+ for (const { project: project3 } of kinds.filter((row3) => row3.kind === "unknown")) {
185974
+ if (project3.uuid) result2.blockedProjectUuids.add(project3.uuid);
185975
+ else result2.blockedUnsignedProjectIds.add(project3.id);
185976
+ }
185977
+ return result2;
185978
+ }
185910
185979
  function dropCarriedRfiCitationPins(projectId14) {
185911
185980
  let dropped2 = 0;
185912
185981
  for (const pin of readGenerationRetentionPins(projectId14)) {
@@ -195616,6 +195685,17 @@ var init_floless_owned_workflows = __esm({
195616
195685
  });
195617
195686
 
195618
195687
  // oauth-presets.ts
195688
+ function microsoftPreset(env2 = process.env) {
195689
+ const clientId = (env2.FLOLESS_M365_CLIENT_ID ?? FLOLESS_M365_CLIENT_ID).trim();
195690
+ if (!clientId) return null;
195691
+ return {
195692
+ id: "microsoft-365",
195693
+ displayName: "Microsoft 365",
195694
+ clientId,
195695
+ scopes: FLOLESS_M365_SCOPES,
195696
+ ownAppEnv: "AWARE_OAUTH_M365_CLIENT_ID"
195697
+ };
195698
+ }
195619
195699
  function friendlyIntegrationName(id2) {
195620
195700
  const preset = OAUTH_PRESETS[id2];
195621
195701
  if (preset) return preset.displayName;
@@ -195629,8 +195709,9 @@ function managedProfileYaml(preset) {
195629
195709
  return [
195630
195710
  MANAGED_HEADER,
195631
195711
  `client_id: ${preset.clientId}`,
195632
- `redirect_uri: ${preset.redirectUri}`,
195633
- `callback_port: ${preset.callbackPort}`,
195712
+ ...preset.redirectUri ? [`redirect_uri: ${preset.redirectUri}`] : [],
195713
+ ...preset.callbackPort != null ? [`callback_port: ${preset.callbackPort}`] : [],
195714
+ ...preset.scopes?.length ? ["scopes:", ...preset.scopes.map((scope3) => ` - ${scope3}`)] : [],
195634
195715
  ""
195635
195716
  ].join("\n");
195636
195717
  }
@@ -195645,8 +195726,7 @@ function isUpgradableLegacyProfile(existing2, preset) {
195645
195726
  const m = /^client_id\s*:\s*(.+?)\s*$/.exec(only4);
195646
195727
  return m !== null && m[1] === preset.clientId;
195647
195728
  }
195648
- function ensureManagedProfile(id2) {
195649
- const preset = OAUTH_PRESETS[id2];
195729
+ function ensureManagedProfile(id2, preset = OAUTH_PRESETS[id2], env2 = process.env) {
195650
195730
  if (!preset) return "not-managed";
195651
195731
  const dir2 = oauthDir();
195652
195732
  const file3 = (0, import_node_path90.join)(dir2, `${id2}.yaml`);
@@ -195654,10 +195734,11 @@ function ensureManagedProfile(id2) {
195654
195734
  if (existing2 !== null && !existing2.startsWith(MANAGED_HEADER) && !isUpgradableLegacyProfile(existing2, preset)) {
195655
195735
  return "skipped";
195656
195736
  }
195737
+ if (existing2 === null && preset.ownAppEnv && env2[preset.ownAppEnv]?.trim()) return "skipped";
195657
195738
  const desired = managedProfileYaml(preset);
195658
195739
  if (existing2 === desired) return "unchanged";
195659
195740
  (0, import_node_fs98.mkdirSync)(dir2, { recursive: true });
195660
- (0, import_node_fs98.writeFileSync)(file3, desired, "utf8");
195741
+ writeAtomic(file3, desired);
195661
195742
  return "written";
195662
195743
  }
195663
195744
  function isPortBindable(port, host2 = "127.0.0.1") {
@@ -195667,7 +195748,7 @@ function isPortBindable(port, host2 = "127.0.0.1") {
195667
195748
  srv.listen(port, host2, () => srv.close(() => resolve76(true)));
195668
195749
  });
195669
195750
  }
195670
- var import_node_os46, import_node_path90, import_node_net2, import_node_fs98, MANAGED_HEADER, OAUTH_PRESETS;
195751
+ var import_node_os46, import_node_path90, import_node_net2, import_node_fs98, MANAGED_HEADER, FLOLESS_M365_CLIENT_ID, FLOLESS_M365_SCOPES, microsoft, OAUTH_PRESETS;
195671
195752
  var init_oauth_presets = __esm({
195672
195753
  "oauth-presets.ts"() {
195673
195754
  "use strict";
@@ -195675,7 +195756,11 @@ var init_oauth_presets = __esm({
195675
195756
  import_node_path90 = require("node:path");
195676
195757
  import_node_net2 = __toESM(require("node:net"), 1);
195677
195758
  import_node_fs98 = require("node:fs");
195759
+ init_write_json_atomic();
195678
195760
  MANAGED_HEADER = "# managed by floless.app - do not edit";
195761
+ FLOLESS_M365_CLIENT_ID = "d4453cc5-e534-483a-a2b3-2dbcaf82cde3";
195762
+ FLOLESS_M365_SCOPES = Object.freeze(["offline_access", "User.Read"]);
195763
+ microsoft = microsoftPreset();
195679
195764
  OAUTH_PRESETS = {
195680
195765
  "trimble-connect": {
195681
195766
  id: "trimble-connect",
@@ -195683,7 +195768,8 @@ var init_oauth_presets = __esm({
195683
195768
  clientId: process.env.FLOLESS_TRIMBLE_CLIENT_ID ?? "0a2444e4-f531-4a67-ab43-edc93ccff680",
195684
195769
  redirectUri: "http://localhost",
195685
195770
  callbackPort: 80
195686
- }
195771
+ },
195772
+ ...microsoft ? { "microsoft-365": microsoft } : {}
195687
195773
  };
195688
195774
  }
195689
195775
  });
@@ -195799,7 +195885,7 @@ var init_google_client = __esm({
195799
195885
  GOOGLE_INTEGRATION = "google-workspace";
195800
195886
  DRIVE_READONLY_SCOPE = "https://www.googleapis.com/auth/drive.readonly";
195801
195887
  AWARE_GOOGLE_CLIENT_ID_ENV = "AWARE_OAUTH_GOOGLE_CLIENT_ID";
195802
- FLOLESS_GOOGLE_CLIENT_ID = "";
195888
+ FLOLESS_GOOGLE_CLIENT_ID = "674694202162-bu79or33kfaqn5hvthr14c2k8ftn7936.apps.googleusercontent.com";
195803
195889
  ACCOUNT_ALIAS = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
195804
195890
  GOOGLE_SETUP_FAILED = "FloLess couldn\u2019t prepare its Google sign-in on this computer. Click Connect to try again, and if it keeps happening, report the problem from the menu.";
195805
195891
  GOOGLE_SWITCHED_UNFINISHED = "Google sign-in didn\u2019t finish. FloLess now uses its own Google sign-in, so click Connect again to send RFIs through Gmail.";
@@ -218344,7 +218430,7 @@ function onlyThisRequestList(body3, requestId3) {
218344
218430
  }
218345
218431
  function isRfiWrite(method, url2) {
218346
218432
  if (!url2 || method === "GET" || method === "HEAD") return false;
218347
- return url2 === "/api/projects/:id/rfis" || url2.startsWith("/api/projects/:id/rfis/") || url2 === "/api/projects/:id/versions/:versionN/rfis" || url2 === "/api/projects/:id/versions/:versionN/read-questions";
218433
+ return url2 === "/api/projects/:id/rfis" || url2.startsWith("/api/projects/:id/rfis/") || url2 === "/api/projects/:id/versions/:versionN/rfis" || url2 === "/api/projects/:id/versions/:versionN/read-questions" || url2 === "/api/projects/:id/correspondence-rfis" || url2.startsWith("/api/projects/:id/correspondence-rfis/");
218348
218434
  }
218349
218435
  function registerReadScopeGuard(app, deps) {
218350
218436
  const logged = /* @__PURE__ */ new Set();
@@ -227766,7 +227852,20 @@ function normalizeCitationEntries(value2) {
227766
227852
  const kind2 = e13.kind;
227767
227853
  if (e13.status === "unresolved") {
227768
227854
  if (e13.read !== "no" || !str26(e13.reason, 300)) return null;
227769
- out.push({ anchor: e13.anchor, kind: kind2, status: "unresolved", label: e13.label, read: "no", reason: e13.reason });
227855
+ if (Object.keys(e13).some((key8) => !["anchor", "kind", "status", "label", "read", "reason", "problem", "memberId", "projectId"].includes(key8))) return null;
227856
+ if (e13.problem !== void 0 && (kind2 !== "member" || !CITATION_PROBLEMS.includes(e13.problem))) return null;
227857
+ const names3 = e13.problem !== void 0 && isReferenceProblem(e13.problem) && e13.problem !== "ambiguous";
227858
+ if (names3 ? !str26(e13.memberId, 200) || !str26(e13.projectId, 200) : e13.memberId !== void 0 || e13.projectId !== void 0) return null;
227859
+ out.push({
227860
+ anchor: e13.anchor,
227861
+ kind: kind2,
227862
+ status: "unresolved",
227863
+ label: e13.label,
227864
+ read: "no",
227865
+ reason: e13.reason,
227866
+ ...e13.problem !== void 0 ? { problem: e13.problem } : {},
227867
+ ...names3 ? { memberId: e13.memberId, projectId: e13.projectId } : {}
227868
+ });
227770
227869
  continue;
227771
227870
  }
227772
227871
  if (e13.status !== "resolved" || !e13.ref || typeof e13.ref !== "object" || Array.isArray(e13.ref)) return null;
@@ -227895,21 +227994,36 @@ async function appendChatCitationIfTurnCurrent(owner4, chatId2, expected2, event
227895
227994
  const selected = resolveChatScopeProject(chat, entry2.ref.projectId);
227896
227995
  if (selected.status !== "selected" || selected.projectUuid !== entry2.ref.projectUuid) return { appended: false, reason: "moved-on" };
227897
227996
  }
227898
- const held3 = /* @__PURE__ */ new Set();
227997
+ const held3 = /* @__PURE__ */ new Map();
227998
+ const current = /* @__PURE__ */ new Map();
227899
227999
  for (const event2 of events) {
227900
228000
  if (event2.type !== "citation" || event2.turnId !== active2.turnId) continue;
227901
228001
  const stored2 = event2.payload.entries;
227902
228002
  if (Array.isArray(stored2)) {
227903
- for (const row3 of stored2) if (row3 && typeof row3.anchor === "string") held3.add(row3.anchor);
228003
+ for (const row3 of stored2) {
228004
+ const anchor3 = row3 && typeof row3.anchor === "string" ? row3.anchor : null;
228005
+ if (anchor3) {
228006
+ held3.set(anchor3, (held3.get(anchor3) ?? 0) + 1);
228007
+ current.set(anchor3, row3);
228008
+ }
228009
+ }
227904
228010
  }
227905
228011
  }
227906
- for (const entry2 of entries2) held3.add(entry2.anchor);
228012
+ const kept = entries2.filter((entry2) => {
228013
+ if (entry2.status !== "unresolved" || entry2.memberId === void 0) return true;
228014
+ const now5 = current.get(entry2.anchor);
228015
+ const ref = now5?.status === "resolved" && now5.kind === "member" ? now5.ref : null;
228016
+ return !(ref && ref.memberId === entry2.memberId && ref.projectId === entry2.projectId);
228017
+ });
228018
+ if (!kept.length) return { appended: false, reason: "superseded" };
228019
+ if (kept.some((entry2) => (held3.get(entry2.anchor) ?? 0) >= MAX_CITATION_ENTRIES_PER_ANCHOR)) return { appended: false, reason: "over-limit-anchor" };
228020
+ for (const entry2 of kept) held3.set(entry2.anchor, (held3.get(entry2.anchor) ?? 0) + 1);
227907
228021
  if (held3.size > MAX_CITATION_ANCHORS_PER_TURN) return { appended: false, reason: "over-limit" };
227908
228022
  const event = appendChatEventLocked(resolved, id2, {
227909
228023
  eventId: rowId3,
227910
228024
  turnId: active2.turnId,
227911
228025
  type: "citation",
227912
- payload: { citationId: rowId3, entries: entries2, ...callId ? { callId } : {} }
228026
+ payload: { citationId: rowId3, entries: kept, ...callId ? { callId } : {} }
227913
228027
  });
227914
228028
  return { appended: true, event };
227915
228029
  });
@@ -229801,7 +229915,7 @@ async function settleUnattendedDecline(owner4, chatId2, turnId, approvalId, stat
229801
229915
  return { ...current, unattendedDeclines: list5.map((entry2, i) => i !== index ? entry2 : state4 === "assumed" ? { ...entry2, state: "declined", question: true } : { ...entry2, state: state4 }) };
229802
229916
  });
229803
229917
  }
229804
- var import_node_crypto113, import_node_fs129, import_node_path116, UUID35, REQUEST_UUID, SHA25612, CHAT_FILE, CHAT_DIRECTORY, EVENTS_DIRECTORY, TURNS_DIRECTORY, FOLLOWUPS_DIRECTORY, ATTACHMENTS_DIRECTORY, REQUEST_LINKS_DIRECTORY, MAX_CHAT_BYTES, MAX_EVENT_BYTES, MAX_USER_MESSAGE_EVENT_BYTES, MAX_TURN_BYTES, MAX_SUBJECT_INDEX_BYTES, MAX_FOLLOWUP_BYTES, MAX_TEXT_BYTES, MAX_DRAFT_BYTES, MAX_ATTACHMENT_BYTES, MAX_ATTACHMENTS, MAX_IMAGES_PER_MESSAGE, MAX_INTEGRATION_BINDINGS, MAX_ATTACHMENT_TOTAL_BYTES, SECRET_KEY, PICTURE_PDF_EXTENSIONS, MEDIA_EXTENSIONS, ChatStoreError, DISMISS_TARGET, REHOME_STATES, UNITS, UNREADABLE_CHAT_MESSAGE, MOVED_DIRECTORY, requestChatCheckpointForTest, reportedUnreadable, INSTRUCTOR_ANSWER_ACCESS_COPY, RELEASE_PROFILE_WORDS, TEKLA_READ_KEYS, TEKLA_SELECTION_KEYS, TEKLA_PART_KEYS, TEKLA_PART_TEXT_LIMIT, TEKLA_READ_PAYLOAD_BUDGET, isCount4, isWeight, MAX_SUBJECT_LINK_CALLS_PER_TURN, FILTER_SNAPSHOTS_DIRECTORY, MAX_FILTER_SNAPSHOT_BYTES, FILTER_SNAPSHOT_FILE, FILTER_SAVED_NOTES_FILE, MAX_FILTER_SAVED_NOTES, MAX_FILTER_SAVED_NOTES_BYTES, FILTER_PROPOSALS_DIRECTORY, MAX_FILTER_PROPOSAL_BYTES, SHA256_HEX2, CITATION_KINDS, MAX_CITATION_ANCHORS_PER_TURN, CITATION_ANCHOR, MAX_ASSUMED_CLAIM_CHARS, startupOwnerNotes, CHAT_RETENTION_BATCH_EVENTS, subjectIndexWarnings, isMissing, PROMOTABLE_FOLLOWUP_STATES, CHAT_STORE_LIMITS;
229918
+ var import_node_crypto113, import_node_fs129, import_node_path116, UUID35, REQUEST_UUID, SHA25612, CHAT_FILE, CHAT_DIRECTORY, EVENTS_DIRECTORY, TURNS_DIRECTORY, FOLLOWUPS_DIRECTORY, ATTACHMENTS_DIRECTORY, REQUEST_LINKS_DIRECTORY, MAX_CHAT_BYTES, MAX_EVENT_BYTES, MAX_USER_MESSAGE_EVENT_BYTES, MAX_TURN_BYTES, MAX_SUBJECT_INDEX_BYTES, MAX_FOLLOWUP_BYTES, MAX_TEXT_BYTES, MAX_DRAFT_BYTES, MAX_ATTACHMENT_BYTES, MAX_ATTACHMENTS, MAX_IMAGES_PER_MESSAGE, MAX_INTEGRATION_BINDINGS, MAX_ATTACHMENT_TOTAL_BYTES, SECRET_KEY, PICTURE_PDF_EXTENSIONS, MEDIA_EXTENSIONS, ChatStoreError, DISMISS_TARGET, REHOME_STATES, UNITS, UNREADABLE_CHAT_MESSAGE, MOVED_DIRECTORY, requestChatCheckpointForTest, reportedUnreadable, INSTRUCTOR_ANSWER_ACCESS_COPY, RELEASE_PROFILE_WORDS, TEKLA_READ_KEYS, TEKLA_SELECTION_KEYS, TEKLA_PART_KEYS, TEKLA_PART_TEXT_LIMIT, TEKLA_READ_PAYLOAD_BUDGET, isCount4, isWeight, MAX_SUBJECT_LINK_CALLS_PER_TURN, FILTER_SNAPSHOTS_DIRECTORY, MAX_FILTER_SNAPSHOT_BYTES, FILTER_SNAPSHOT_FILE, FILTER_SAVED_NOTES_FILE, MAX_FILTER_SAVED_NOTES, MAX_FILTER_SAVED_NOTES_BYTES, FILTER_PROPOSALS_DIRECTORY, MAX_FILTER_PROPOSAL_BYTES, SHA256_HEX2, CITATION_REFERENCE_PROBLEMS, CITATION_PROBLEMS, isReferenceProblem, CITATION_KINDS, MAX_CITATION_ANCHORS_PER_TURN, MAX_CITATION_ENTRIES_PER_ANCHOR, CITATION_ANCHOR, MAX_ASSUMED_CLAIM_CHARS, startupOwnerNotes, CHAT_RETENTION_BATCH_EVENTS, subjectIndexWarnings, isMissing, PROMOTABLE_FOLLOWUP_STATES, CHAT_STORE_LIMITS;
229805
229919
  var init_chat_store = __esm({
229806
229920
  "chat-store.ts"() {
229807
229921
  "use strict";
@@ -229941,8 +230055,12 @@ var init_chat_store = __esm({
229941
230055
  FILTER_PROPOSALS_DIRECTORY = "filter-proposals";
229942
230056
  MAX_FILTER_PROPOSAL_BYTES = 2 * 1024 * 1024;
229943
230057
  SHA256_HEX2 = /^[0-9a-f]{64}$/;
230058
+ CITATION_REFERENCE_PROBLEMS = ["id-as-mark", "wrong-mark", "id-spelling", "ambiguous"];
230059
+ CITATION_PROBLEMS = [...CITATION_REFERENCE_PROBLEMS, "stale", "absent"];
230060
+ isReferenceProblem = (problem3) => CITATION_REFERENCE_PROBLEMS.includes(problem3);
229944
230061
  CITATION_KINDS = ["sheet", "kb-page", "member", "attachment", "project-file"];
229945
230062
  MAX_CITATION_ANCHORS_PER_TURN = 40;
230063
+ MAX_CITATION_ENTRIES_PER_ANCHOR = 4;
229946
230064
  CITATION_ANCHOR = /^[a-z0-9-]{1,16}$/;
229947
230065
  MAX_ASSUMED_CLAIM_CHARS = 300;
229948
230066
  startupOwnerNotes = /* @__PURE__ */ new Set();
@@ -237452,7 +237570,30 @@ function derivedId(...parts) {
237452
237570
  const hex3 = bytes6.toString("hex");
237453
237571
  return `${hex3.slice(0, 8)}-${hex3.slice(8, 12)}-${hex3.slice(12, 16)}-${hex3.slice(16, 20)}-${hex3.slice(20)}`;
237454
237572
  }
237455
- var import_node_crypto127, import_node_fs143, CITE_TOOL_NAME, CITE_DESCRIPTION, CITE_ROUTING, MAX_SOURCES_PER_CALL, SOURCE_SCHEMA, CITE_INPUT_SCHEMA, CITE_ZOD_SHAPE, SOURCE_FIELDS, KIND_FIELDS, plain4, bounded3, SHOWN_TO_AI, citedName, unresolved2, ChatCitationService, ChatCitationSources;
237573
+ function repairsBefore(events, sequence) {
237574
+ const out = /* @__PURE__ */ new Map();
237575
+ for (const event of events) {
237576
+ if (event.type !== "citation" || event.sequence >= sequence) continue;
237577
+ for (const entry2 of normalizeCitationEntries(event.payload.entries) ?? []) {
237578
+ if (entry2.status === "unresolved" && isReferenceProblem(entry2.problem)) out.set(entry2.anchor, (out.get(entry2.anchor) ?? 0) + 1);
237579
+ }
237580
+ }
237581
+ return out;
237582
+ }
237583
+ function repairOf(entry2, before2, listed3 = false) {
237584
+ if (entry2.status !== "unresolved" || !isReferenceProblem(entry2.problem)) return {};
237585
+ if (before2 >= MAX_REFERENCE_REPAIRS) {
237586
+ return { repair: null, stop: "You have been told how to correct this reference before. Do not cite this anchor again: say in words what the claim rests on." };
237587
+ }
237588
+ if (entry2.problem === "ambiguous") {
237589
+ return { repair: listed3 ? "Call floless_cite again for this anchor with the memberId of the member you mean, from candidates." : "Call floless_cite again for this anchor with what you cited to be told the members it matches, then cite the one you mean by its memberId." };
237590
+ }
237591
+ return {
237592
+ repair: "Call floless_cite again with fix. It replaces this entry; the claim keeps its anchor.",
237593
+ fix: { projectId: entry2.projectId, sources: [{ anchor: entry2.anchor, kind: "member", memberId: entry2.memberId }] }
237594
+ };
237595
+ }
237596
+ var import_node_crypto127, import_node_fs143, CITE_TOOL_NAME, CITE_DESCRIPTION, CITE_ROUTING, MAX_SOURCES_PER_CALL, MAX_REFERENCE_REPAIRS, SOURCE_SCHEMA, CITE_INPUT_SCHEMA, CITE_ZOD_SHAPE, SOURCE_FIELDS, KIND_FIELDS, plain4, bounded3, SHOWN_TO_AI, citedName, unresolved2, ChatCitationService, ChatCitationSources;
237456
237597
  var init_chat_citation = __esm({
237457
237598
  "chat-citation.ts"() {
237458
237599
  "use strict";
@@ -237467,9 +237608,10 @@ var init_chat_citation = __esm({
237467
237608
  init_attachment_text();
237468
237609
  init_chat_project_file();
237469
237610
  CITE_TOOL_NAME = "floless_cite";
237470
- CITE_DESCRIPTION = `Name the sources behind the project facts in your answer, so the person can open each one. For each source give an anchor (lowercase letters, digits or "-", at most 16 characters) and put :cite[anchor] in your answer right after the claim it supports. kind "sheet": a drawing sheet you looked at with floless_evidence_read in this answer, by that look's evidenceId. kind "kb-page": a Knowledge page of this project, by slug (and generationId when you read an earlier version). kind "member": a member of this project's steel model, by its mark (and memberId when two members share the mark). kind "attachment": a file the person attached to this conversation, by its fileName (or attachmentId when several share the name). kind "project-file": a file that lives in the project's own folder (not one attached to a message), by its path relative to that folder, for example "model/frame.ifc". FloLess checks each source against what you were actually shown; one it cannot match is shown to the person as "no source". A later source with the same anchor replaces the earlier one. Cite only what supports the claim.`;
237611
+ CITE_DESCRIPTION = `Name the sources behind the project facts in your answer, so the person can open each one. For each source give an anchor (lowercase letters, digits or "-", at most 16 characters) and put :cite[anchor] in your answer right after the claim it supports. kind "sheet": a drawing sheet you looked at with floless_evidence_read in this answer, by that look's evidenceId. kind "kb-page": a Knowledge page of this project, by slug (and generationId when you read an earlier version). kind "member": a member of this project's steel model, by its memberId (the id FloLess's model viewer shows, under Mark when no drawing gave the member a mark), or by mark, but only a mark a drawing gave it. kind "attachment": a file the person attached to this conversation, by its fileName (or attachmentId when several share the name). kind "project-file": a file that lives in the project's own folder (not one attached to a message), by its path relative to that folder, for example "model/frame.ifc". FloLess checks each source against what you were actually shown; one it cannot match is shown to the person as "no source". When FloLess answers a source with a fix, the reference was yours to correct: call this tool again with the fix. A later source with the same anchor replaces the earlier one. Cite only what supports the claim.`;
237471
237612
  CITE_ROUTING = `When your answer states a project dimension, quantity, material or grade, or a decision, cite where it comes from: call ${CITE_TOOL_NAME} with the sheet you looked at, the Knowledge page you read, the model member, the attached file or the file in the project folder, and put :cite[anchor] right after the claim. If you have no source for it, say plainly that it is an assumption and mark it :assume[a few words]. Citing changes nothing in the project.`;
237472
237613
  MAX_SOURCES_PER_CALL = 12;
237614
+ MAX_REFERENCE_REPAIRS = 2;
237473
237615
  SOURCE_SCHEMA = Object.freeze({
237474
237616
  type: "object",
237475
237617
  properties: Object.freeze({
@@ -237478,8 +237620,8 @@ var init_chat_citation = __esm({
237478
237620
  evidenceId: Object.freeze({ type: "string", minLength: 1, maxLength: 64, description: 'kind "sheet": the evidenceId of a sheet you looked at in this answer.' }),
237479
237621
  slug: Object.freeze({ type: "string", minLength: 1, maxLength: 200, description: `kind "kb-page": the page's slug.` }),
237480
237622
  generationId: Object.freeze({ type: "string", minLength: 1, maxLength: 64, description: 'kind "kb-page": the version you read, when not the newest.' }),
237481
- mark: Object.freeze({ type: "string", minLength: 1, maxLength: MAX_MARK_CHARS, description: `kind "member": the member's mark, as the drawings give it.` }),
237482
- memberId: Object.freeze({ type: "string", minLength: 1, maxLength: 200, description: `kind "member": the member's id, when the mark alone names more than one member.` }),
237623
+ mark: Object.freeze({ type: "string", minLength: 1, maxLength: MAX_MARK_CHARS, description: 'kind "member": a mark a drawing gave the member. Never its id.' }),
237624
+ memberId: Object.freeze({ type: "string", minLength: 1, maxLength: 200, description: `kind "member": the member's id, as the model viewer shows it.` }),
237483
237625
  fileName: Object.freeze({ type: "string", minLength: 1, maxLength: 255, description: `kind "attachment": the attached file's name.` }),
237484
237626
  attachmentId: Object.freeze({ type: "string", minLength: 1, maxLength: 64, description: `kind "attachment": the file's attachmentId, instead of fileName when several files share the name.` }),
237485
237627
  path: Object.freeze({ type: "string", minLength: 1, maxLength: 400, description: `kind "project-file": the file's path relative to the project folder, for example model/frame.ifc. No "..", no drive.` })
@@ -237576,7 +237718,7 @@ var init_chat_citation = __esm({
237576
237718
  console.warn("[chat] a citation pin was kept as intent", JSON.stringify({ pinId: pin.input.pinId, error: error62 instanceof Error ? error62.message : String(error62) }));
237577
237719
  }
237578
237720
  }
237579
- return { success: true, text: this.resultText(recordedEntries) };
237721
+ return { success: true, text: this.resultText(recordedEntries, repairsBefore(events, prior.sequence)) };
237580
237722
  }
237581
237723
  }
237582
237724
  const entries2 = [];
@@ -237596,6 +237738,7 @@ var init_chat_citation = __esm({
237596
237738
  }
237597
237739
  const citationId = callId ? derivedId(chat.chatId, turn.turnId, "citation-call", callId) : derivedId(chat.chatId, turn.turnId, "citation", JSON.stringify(entries2));
237598
237740
  const pins = this.pinPlan(citationId, chat.chatId, entries2);
237741
+ const sameAs = (stored3) => new Map([...candidates].filter(([anchor3]) => JSON.stringify(stored3.find((e13) => e13.anchor === anchor3)) === JSON.stringify(entries2.find((e13) => e13.anchor === anchor3))));
237599
237742
  const known3 = this.recorded(owner4, chat.chatId, citationId);
237600
237743
  if (known3 === "unknown") {
237601
237744
  return { success: false, text: "FloLess could not read this conversation's record just now, so nothing was cited. Say where your facts come from in words." };
@@ -237608,7 +237751,10 @@ var init_chat_citation = __esm({
237608
237751
  console.warn("[chat] a citation pin was kept as intent", JSON.stringify({ pinId: pin.input.pinId, error: error62 instanceof Error ? error62.message : String(error62) }));
237609
237752
  }
237610
237753
  }
237611
- return { success: true, text: this.resultText(entries2) };
237754
+ const after3 = this.turnEvents(owner4, chat.chatId, turn.turnId, events);
237755
+ const prior = after3.find((event) => event.eventId === citationId);
237756
+ const stored3 = prior ? normalizeCitationEntries(prior.payload.entries) ?? entries2 : entries2;
237757
+ return { success: true, text: this.resultText(stored3, repairsBefore(after3, prior?.sequence ?? Number.MAX_SAFE_INTEGER), sameAs(stored3)) };
237612
237758
  }
237613
237759
  const begun = [];
237614
237760
  const release2 = () => {
@@ -237642,7 +237788,7 @@ var init_chat_citation = __esm({
237642
237788
  }
237643
237789
  if (!appended.appended) {
237644
237790
  release2();
237645
- return { success: false, text: appended.reason === "over-limit" ? `This answer already cites ${MAX_CITATION_ANCHORS_PER_TURN} sources, the most FloLess shows for one answer. Nothing more was cited.` : "This answer has ended or the project left the conversation, so nothing was cited." };
237791
+ return { success: false, text: appended.reason === "over-limit" ? `This answer already cites ${MAX_CITATION_ANCHORS_PER_TURN} sources, the most FloLess shows for one answer. Nothing more was cited.` : appended.reason === "over-limit-anchor" ? `A claim in this call has already been cited ${MAX_CITATION_ENTRIES_PER_ANCHOR} times in this answer, so nothing was cited. Do not cite it again: say in words what it rests on.` : appended.reason === "superseded" ? "These claims already cite those members correctly in this answer, so nothing more was cited." : "This answer has ended or the project left the conversation, so nothing was cited." };
237646
237792
  }
237647
237793
  for (const pin of begun) {
237648
237794
  try {
@@ -237657,12 +237803,29 @@ var init_chat_citation = __esm({
237657
237803
  console.warn("[chat] a citation was saved but not announced live", error62 instanceof Error ? error62.message : String(error62));
237658
237804
  }
237659
237805
  const stored2 = normalizeCitationEntries(appended.event.payload.entries) ?? entries2;
237660
- return { success: true, text: this.resultText(stored2, JSON.stringify(stored2) === JSON.stringify(entries2) ? candidates : void 0) };
237806
+ const after2 = this.turnEvents(owner4, chat.chatId, turn.turnId, events);
237807
+ return { success: true, text: this.resultText(stored2, repairsBefore(after2, appended.event.sequence), sameAs(stored2)) };
237808
+ }
237809
+ /** This turn's events, read again (the record changed since the call began); the call's first read when that fails. */
237810
+ turnEvents(owner4, chatId2, turnId, fallback2) {
237811
+ try {
237812
+ return this.deps.listEvents(owner4, chatId2).filter((event) => event.turnId === turnId);
237813
+ } catch (error62) {
237814
+ console.warn("[chat] citing: the record could not be read again", JSON.stringify({ chatId: chatId2, error: error62 instanceof Error ? error62.message : String(error62) }));
237815
+ return fallback2;
237816
+ }
237661
237817
  }
237662
- resultText(entries2, candidates) {
237818
+ resultText(entries2, repairs2, candidates) {
237663
237819
  return JSON.stringify({
237664
- cited: entries2.map((entry2) => entry2.status === "resolved" ? { anchor: entry2.anchor, source: entry2.label, shownToYou: SHOWN_TO_AI.has(entry2.read) } : { anchor: entry2.anchor, source: null, reason: entry2.reason, ...candidates?.get(entry2.anchor) ? { candidates: candidates.get(entry2.anchor) } : {} }),
237665
- note: 'Put :cite[anchor] right after each claim. An anchor with no source is shown to the person as "no source"; say what it rests on.'
237820
+ cited: entries2.map((entry2) => entry2.status === "resolved" ? { anchor: entry2.anchor, source: entry2.label, shownToYou: SHOWN_TO_AI.has(entry2.read) } : {
237821
+ anchor: entry2.anchor,
237822
+ source: null,
237823
+ reason: entry2.reason,
237824
+ ...entry2.problem ? { problem: entry2.problem } : {},
237825
+ ...candidates?.get(entry2.anchor) ? { candidates: candidates.get(entry2.anchor) } : {},
237826
+ ...repairOf(entry2, repairs2.get(entry2.anchor) ?? 0, !!candidates?.get(entry2.anchor))
237827
+ }),
237828
+ note: 'Put :cite[anchor] right after each claim. A source answered with a fix is your reference to correct: call floless_cite again with the fix, and it replaces that entry. An anchor with no source is shown to the person as "no source"; say what it rests on.'
237666
237829
  });
237667
237830
  }
237668
237831
  /** Whether this citation is in the conversation's record: `unknown` when the record could not be read just now. */
@@ -237705,48 +237868,92 @@ var init_chat_citation = __esm({
237705
237868
  }
237706
237869
  }
237707
237870
  /**
237708
- * A member of the model, by id or by the mark a drawing gave it. Resolver rows are one per mark, so candidates are
237709
- * counted by member: a mark two members carry names two members, and FloLess picks neither; the AI is told both by id.
237871
+ * A member of the model, by id or by the mark a drawing gave it. Resolver rows are one per mark, so members are counted
237872
+ * by id: a mark two members carry names two members, and FloLess picks neither; the AI is told both by id.
237710
237873
  * Given to the AI only when a message of this turn carried that member's exact @-mention line for this same model
237711
237874
  * version.
237875
+ *
237876
+ * #2930/#2884: the model viewer shows a member's id under "Mark" when no drawing gave it one, so the AI cites ids as
237877
+ * marks. A member that exists but was named the wrong way is a REFERENCE problem (`id-as-mark`, `wrong-mark`,
237878
+ * `id-spelling`, `ambiguous`) that the AI is told how to correct, with the member's id and project; it is never
237879
+ * resolved from the wrong field, and never reported as a member that is not there. `stale` and `absent` mean what
237880
+ * they say. A mark a drawing really gave the member always wins over these.
237712
237881
  */
237713
237882
  member(source2, read5, delivered, projectId14, projectUuid2, candidates) {
237714
237883
  if (read5.status === "no-model") return unresolved2(source2, "a member", MENTION_REASONS["no-model"]);
237715
237884
  if (read5.status === "not-steel") return unresolved2(source2, "a member", MENTION_REASONS["not-steel"]);
237716
237885
  if (read5.status !== "ok") return unresolved2(source2, "a member", MENTION_REASONS.unreadable);
237717
- const rows4 = read5.refs.filter((ref2) => ref2.kind === "member");
237718
- let hits;
237886
+ const rows4 = read5.refs.filter((ref) => ref.kind === "member");
237887
+ const fold = (value2) => value2.toLowerCase();
237888
+ const idsOf = (hits) => [...new Set(hits.map((ref) => ref.id))];
237889
+ const q10 = (value2) => quoteRefText(value2, 200);
237890
+ const failed2 = (problem3, reason, memberId) => ({ ...unresolved2(source2, "a member", bounded3(reason, 300)), problem: problem3, ...memberId !== void 0 ? { memberId, projectId: projectId14 } : {} });
237891
+ const cited = (ref) => this.citedMember(source2, ref, rows4, read5.etag, delivered, projectId14, projectUuid2);
237892
+ const several = (ids2, byMark2, reason) => {
237893
+ candidates.set(source2.anchor, ids2.map((id2) => {
237894
+ const ref = byMark2.find((row3) => row3.id === id2) ?? rows4.find((row3) => row3.id === id2);
237895
+ return {
237896
+ memberId: quoteRefText(ref.id, 200),
237897
+ mark: quoteRefText(ref.mark),
237898
+ profile: ref.profile ? quoteRefText(ref.profile) : null,
237899
+ readOn: ref.views.map((view) => quoteRefText(view.sheet))
237900
+ };
237901
+ }));
237902
+ return failed2("ambiguous", reason);
237903
+ };
237719
237904
  if (source2.memberId !== void 0) {
237720
- hits = rows4.filter((ref2) => ref2.id === source2.memberId && (source2.mark === void 0 || ref2.mark === source2.mark));
237721
- } else {
237722
- hits = rows4.filter((ref2) => ref2.mark === source2.mark);
237723
- if (!hits.length) hits = rows4.filter((ref2) => ref2.mark !== null && ref2.mark.toLowerCase() === source2.mark.toLowerCase());
237724
- }
237725
- const byMember = /* @__PURE__ */ new Map();
237726
- for (const hit of hits) if (!byMember.has(hit.id)) byMember.set(hit.id, hit);
237727
- if (byMember.size === 0) {
237728
- return unresolved2(source2, "a member", source2.memberId !== void 0 && source2.mark !== void 0 && rows4.some((ref2) => ref2.id === source2.memberId) ? "that member does not carry this mark in the current model" : "FloLess found no such member in the current model");
237729
- }
237730
- if (byMember.size > 1) {
237731
- candidates.set(source2.anchor, [...byMember.values()].map((ref2) => ({
237732
- memberId: quoteRefText(ref2.id, 200),
237733
- mark: quoteRefText(ref2.mark),
237734
- profile: ref2.profile ? quoteRefText(ref2.profile) : null,
237735
- readOn: ref2.views.map((view) => quoteRefText(view.sheet))
237736
- })));
237737
- return unresolved2(source2, "a member", `${byMember.size} members carry this mark; cite the one you mean by its memberId`);
237738
- }
237739
- const ref = [...byMember.values()][0];
237905
+ const own7 = rows4.filter((ref) => ref.id === source2.memberId);
237906
+ if (!own7.length) {
237907
+ const spelled = idsOf(rows4.filter((ref) => fold(ref.id) === fold(source2.memberId)));
237908
+ if (spelled.length === 1) return failed2("id-spelling", `the model spells this member's id ${q10(spelled[0])}; cite it with that memberId`, spelled[0]);
237909
+ if (spelled.length > 1) return several(spelled, [], `${spelled.length} members have this id in other letter cases; cite the one you mean by its exact memberId`);
237910
+ return this.absentMember(source2, rows4, delivered, read5.etag, failed2);
237911
+ }
237912
+ if (source2.mark === void 0) return cited(own7[0]);
237913
+ const carried2 = own7.find((ref) => ref.mark === source2.mark);
237914
+ if (carried2) return cited(carried2);
237915
+ const id2 = own7[0].id;
237916
+ if (fold(source2.mark) === fold(id2)) {
237917
+ return failed2("id-as-mark", `${q10(source2.mark)} is this member's id in the model, not a mark a drawing gave it; cite it with memberId ${q10(id2)} and no mark`, id2);
237918
+ }
237919
+ const marks = own7.map((ref) => ref.mark).filter((mark2) => mark2 !== null);
237920
+ return failed2("wrong-mark", marks.length ? `this member does not carry that mark (the drawings give it ${marks.slice(0, 3).map(q10).join(", ")}); cite it with memberId ${q10(id2)} alone` : `this member has no mark from a drawing; cite it with memberId ${q10(id2)} and no mark`, id2);
237921
+ }
237922
+ const mark = source2.mark;
237923
+ let byMark = rows4.filter((ref) => ref.mark === mark);
237924
+ if (!byMark.length) byMark = rows4.filter((ref) => ref.mark !== null && fold(ref.mark) === fold(mark));
237925
+ let byId2 = idsOf(rows4.filter((ref) => ref.id === mark));
237926
+ if (!byId2.length) byId2 = idsOf(rows4.filter((ref) => fold(ref.id) === fold(mark)));
237927
+ const markIds = idsOf(byMark);
237928
+ const all2 = [.../* @__PURE__ */ new Set([...markIds, ...byId2])];
237929
+ if (all2.length === 0) return this.absentMember(source2, rows4, delivered, read5.etag, failed2);
237930
+ if (all2.length > 1) {
237931
+ return several(all2, byMark, byId2.some((id2) => !markIds.includes(id2)) ? `${all2.length} members match this, as a mark or as an id; cite the one you mean by its memberId` : `${all2.length} members carry this mark; cite the one you mean by its memberId`);
237932
+ }
237933
+ if (markIds.length) return cited(byMark[0]);
237934
+ return failed2("id-as-mark", `${q10(mark)} is this member's id in the model, not a mark a drawing gave it; cite it with memberId ${q10(byId2[0])} and no mark`, byId2[0]);
237935
+ }
237936
+ /**
237937
+ * #2930: nothing in the model by that mark or id. `stale` only when this turn gave the AI an @-mention of a member, by
237938
+ * that id or mark, from another model version, and that member's id is not in the model now; otherwise `absent`.
237939
+ */
237940
+ absentMember(source2, rows4, delivered, etag, failed2) {
237941
+ const named2 = (m) => source2.memberId !== void 0 ? m.id === source2.memberId : m.mark === source2.mark || m.id === source2.mark;
237942
+ const gone3 = delivered.messages.some((message2) => mentionsGivenIn(message2.text, message2.displayText, message2.mentions).some((m) => m.kind === "member" && m.resolved && m.modelEtag !== etag && named2(m) && !rows4.some((ref) => ref.id === m.id)));
237943
+ return gone3 ? failed2("stale", "this member was in the model when it was mentioned, but the model has changed since and it is not there now") : failed2("absent", "FloLess found no such member in the current model");
237944
+ }
237945
+ /** A member found: named by the mark it was cited by; cited by id only, by its mark when it has exactly one. */
237946
+ citedMember(source2, ref, rows4, etag, delivered, projectId14, projectUuid2) {
237740
237947
  const marks = rows4.filter((row3) => row3.id === ref.id);
237741
237948
  const mark = source2.mark !== void 0 ? ref.mark : marks.length === 1 ? marks[0].mark : null;
237742
- const given = delivered.messages.some((message2) => mentionsGivenIn(message2.text, message2.displayText, message2.mentions).some((m) => m.kind === "member" && m.resolved && m.id === ref.id && m.modelEtag === read5.etag));
237949
+ const given = delivered.messages.some((message2) => mentionsGivenIn(message2.text, message2.displayText, message2.mentions).some((m) => m.kind === "member" && m.resolved && m.id === ref.id && m.modelEtag === etag));
237743
237950
  return {
237744
237951
  anchor: source2.anchor,
237745
237952
  kind: "member",
237746
237953
  status: "resolved",
237747
237954
  label: bounded3(`Member ${mark ?? ref.id}`),
237748
237955
  read: given ? "mentioned" : "not-recorded",
237749
- ref: { projectId: projectId14, projectUuid: projectUuid2, memberId: ref.id, mark, profile: ref.profile, modelEtag: read5.etag, views: ref.views.slice(0, 4) }
237956
+ ref: { projectId: projectId14, projectUuid: projectUuid2, memberId: ref.id, mark, profile: ref.profile, modelEtag: etag, views: ref.views.slice(0, 4) }
237750
237957
  };
237751
237958
  }
237752
237959
  /**
@@ -264634,9 +264841,9 @@ var init_app_publication_guard = __esm({
264634
264841
  function classifyGmailAwareVersion(version2) {
264635
264842
  if (version2 == null || version2 === "") return "older";
264636
264843
  if (!/^\d+\.\d+\.\d+$/.test(version2)) return "unrecognised";
264637
- if (compareDotted(version2, RFI_GMAIL_AWARE_MIN) < 0) return "older";
264638
- if (compareDotted(version2, RFI_GMAIL_AWARE_BEFORE) >= 0) return "newer";
264639
- return "reviewed";
264844
+ const line3 = version2.split(".").slice(0, 2).join(".");
264845
+ if (RFI_GMAIL_REVIEWED_AWARE_LINES.includes(line3)) return "reviewed";
264846
+ return compareDotted(`${line3}.0`, `${NEWEST_REVIEWED_AWARE_LINE}.0`) > 0 ? "newer" : "older";
264640
264847
  }
264641
264848
  function internalRfiWorkflowDir(roots) {
264642
264849
  const envRoot = process.env.FLOLESS_INTERNAL_WORKFLOWS_DIR;
@@ -264761,7 +264968,7 @@ function evaluateGmailReadiness(runtimeVersion, description, credentials, appAcc
264761
264968
  if (line3 === "older") {
264762
264969
  return {
264763
264970
  status: "update-aware",
264764
- message: "Connected Gmail needs AWARE 0.157 or newer. Update AWARE from the status bar."
264971
+ message: `Connected Gmail needs AWARE ${NEWEST_REVIEWED_AWARE_LINE}. Update AWARE from the status bar.`
264765
264972
  };
264766
264973
  }
264767
264974
  if (line3 !== "reviewed") {
@@ -265161,7 +265368,7 @@ function updateRunId(ownerPath5, runId2, onRunId, privateFileSecurity) {
265161
265368
  onRunId?.(runId2);
265162
265369
  }
265163
265370
  function terminal(events) {
265164
- return events.some((event) => event.kind === "run-end" && (event.status === "success" || event.status === "error"));
265371
+ return events.some((event) => event.kind === "run-end" && (event.status === "ok" || event.status === "error"));
265165
265372
  }
265166
265373
  function classifyGmailTrace(traceText, expectedAttemptId) {
265167
265374
  if (!traceText) return { status: "outcome-unknown", code: "gmail.send.trace-missing" };
@@ -265179,7 +265386,7 @@ function classifyGmailTrace(traceText, expectedAttemptId) {
265179
265386
  const threadId = value2("thread-id");
265180
265387
  const rfcMessageId = value2("rfc-message-id");
265181
265388
  const attemptId3 = value2("attempt-id");
265182
- if (ended && starts.length === 1 && outputs2.length === 1 && endings.length === 1 && endings[0]?.status === "success" && errors.length === 0 && output2?.status === "accepted" && messageId && messageId === gmailMessageId && threadId && rfcMessageId && rfcMessageId !== gmailMessageId && attemptId3 === expectedAttemptId) {
265389
+ if (ended && starts.length === 1 && outputs2.length === 1 && endings.length === 1 && endings[0]?.status === "ok" && errors.length === 0 && output2?.status === "accepted" && messageId && messageId === gmailMessageId && threadId && rfcMessageId && rfcMessageId !== gmailMessageId && attemptId3 === expectedAttemptId) {
265183
265390
  return { status: "accepted", receipt: { messageId, gmailMessageId, threadId, rfcMessageId, attemptId: attemptId3 } };
265184
265391
  }
265185
265392
  if (outputs2.length > 0) return { status: "outcome-unknown", code: "gmail.send.trace-contradictory" };
@@ -265402,7 +265609,7 @@ function recoverOwnedRfiDeliveryStaging(home5 = awareHome2(), isFinalized = () =
265402
265609
  }
265403
265610
  return { recovered, runId: runId2, preservedEvidence, errors };
265404
265611
  }
265405
- var import_node_crypto152, import_node_child_process20, import_node_fs167, import_node_os72, import_node_path153, import_node_url6, import_yaml19, INTERNAL_RFI_GMAIL_APP_ID, RFI_GMAIL_AWARE_MIN, RFI_GMAIL_AWARE_BEFORE, RFI_GMAIL_AGENT_VERSION, RFI_GMAIL_AGENT_DIGEST, HERE, SOURCE_NAME, LOCK_NAME, OWNER_NAME, CONFIG_NAME, STAGING_OWNER_NAME, PUBLICATION_MANIFEST_NAME, EVIDENCE_DIR_NAME, DEFAULT_TIMEOUT_MS, RFI_GMAIL_FENCE_KEY, MAX_ADDRESS_BYTES, MAX_SUBJECT_BYTES, MAX_BODY_BYTES, MAX_ATTEMPT_BYTES, PAYLOAD_HASH, RUN_ID4, awareHome2, DEFAULT_DEPS3, DEFAULT_PRIVATE_FILE_SECURITY, ExistingStagingUnknownError, EvidencePersistenceUnknownError;
265612
+ var import_node_crypto152, import_node_child_process20, import_node_fs167, import_node_os72, import_node_path153, import_node_url6, import_yaml19, INTERNAL_RFI_GMAIL_APP_ID, RFI_GMAIL_REVIEWED_AWARE_LINES, NEWEST_REVIEWED_AWARE_LINE, RFI_GMAIL_AGENT_VERSION, RFI_GMAIL_AGENT_DIGEST, HERE, SOURCE_NAME, LOCK_NAME, OWNER_NAME, CONFIG_NAME, STAGING_OWNER_NAME, PUBLICATION_MANIFEST_NAME, EVIDENCE_DIR_NAME, DEFAULT_TIMEOUT_MS, RFI_GMAIL_FENCE_KEY, MAX_ADDRESS_BYTES, MAX_SUBJECT_BYTES, MAX_BODY_BYTES, MAX_ATTEMPT_BYTES, PAYLOAD_HASH, RUN_ID4, awareHome2, DEFAULT_DEPS3, DEFAULT_PRIVATE_FILE_SECURITY, ExistingStagingUnknownError, EvidencePersistenceUnknownError;
265406
265613
  var init_rfi_delivery = __esm({
265407
265614
  "rfi-delivery.ts"() {
265408
265615
  "use strict";
@@ -265425,8 +265632,8 @@ var init_rfi_delivery = __esm({
265425
265632
  init_google_client();
265426
265633
  init_rfi_delivery_journal();
265427
265634
  INTERNAL_RFI_GMAIL_APP_ID = "floless-rfi-gmail-send";
265428
- RFI_GMAIL_AWARE_MIN = "0.157.0";
265429
- RFI_GMAIL_AWARE_BEFORE = "0.158.0";
265635
+ RFI_GMAIL_REVIEWED_AWARE_LINES = Object.freeze(["0.157", "0.165"]);
265636
+ NEWEST_REVIEWED_AWARE_LINE = RFI_GMAIL_REVIEWED_AWARE_LINES[RFI_GMAIL_REVIEWED_AWARE_LINES.length - 1];
265430
265637
  RFI_GMAIL_AGENT_VERSION = "2.2.0";
265431
265638
  RFI_GMAIL_AGENT_DIGEST = "sha256:b831f6b4e35fe5de503111d028be53df378bf8368dc531fccc844766bf01fda1";
265432
265639
  HERE = (0, import_node_path153.dirname)((0, import_node_url6.fileURLToPath)(__import_meta_url));
@@ -267774,6 +267981,11 @@ function requestAttentionNow(request) {
267774
267981
  function requestsOfProject(all2, projectId14, projectUuid2) {
267775
267982
  return all2.filter((r) => r.project === projectId14 && (!r.journalOwner || r.journalOwner.projectUuid === projectUuid2));
267776
267983
  }
267984
+ function rfiSummaryOf(project3, projectId14, storeKindOf = correspondenceRfiKind) {
267985
+ const kind2 = storeKindOf(project3);
267986
+ if (kind2 === "unknown") throw new Error("which kind of project this is could not be read");
267987
+ return kind2 === "keeps" ? correspondenceOpenSummary(projectId14) : openRfiSummary(projectId14);
267988
+ }
267777
267989
  function projectBriefSources(projectId14, readers = {}, now5 = Date.now) {
267778
267990
  const project3 = getProject(projectId14);
267779
267991
  if (!project3) return null;
@@ -267832,7 +268044,7 @@ function projectBriefSources(projectId14, readers = {}, now5 = Date.now) {
267832
268044
  },
267833
268045
  openLoops: () => {
267834
268046
  const requests = requestsOfProject(listRequests(), projectId14, project3.uuid);
267835
- const rfis = openRfiSummary(projectId14);
268047
+ const rfis = rfiSummaryOf(project3, projectId14);
267836
268048
  const counts4 = openLoopCounts(requests, requestAttentionNow);
267837
268049
  return {
267838
268050
  requests: counts4.requests,
@@ -267879,8 +268091,16 @@ function assistantReasonFacts() {
267879
268091
  const found2 = findReasonWorkflow(listWorkflowOwnerships(), id2, project3, binding3 ?? null, (projectId14) => getProject(projectId14)?.uuid);
267880
268092
  return found2 ? workflowFacts2(found2) : null;
267881
268093
  },
267882
- // The RFI list's own view of that one record (rfi-routes.ts), so a grouped RFI is judged by its members.
267883
- rfi: async (projectId14, rfiId4) => rfiOpenFact(projectId14, rfiId4),
268094
+ // The RFI list's own view of that one record, from the store the brief named it from (#2470 R6.6d): the RFIs step's
268095
+ // for General, Trace, Revit, Tekla and Drawing Checker; Steel's (rfi-routes.ts), where a grouped RFI is judged by its
268096
+ // members. A project whose kind can't be read throws, so the reason is not claimed.
268097
+ rfi: async (projectId14, rfiId4) => {
268098
+ const project3 = getProject(projectId14);
268099
+ if (!project3) return rfiOpenFact(projectId14, rfiId4);
268100
+ const kind2 = correspondenceRfiKind(project3);
268101
+ if (kind2 === "unknown") throw new Error("which kind of project this is could not be read");
268102
+ return kind2 === "keeps" ? correspondenceOpenFact(projectId14, rfiId4) : rfiOpenFact(projectId14, rfiId4);
268103
+ },
267884
268104
  // Waiting on the person exactly as the Requests screen judges it.
267885
268105
  request: async (id2) => {
267886
268106
  const found2 = listRequests().find((r) => r.id.toLowerCase() === id2.toLowerCase());
@@ -267903,6 +268123,7 @@ var init_chat_project_brief_sources = __esm({
267903
268123
  init_projects_store();
267904
268124
  init_project_links();
267905
268125
  init_rfi_routes();
268126
+ init_rfi_correspondence();
267906
268127
  init_routines();
267907
268128
  init_design_set_store();
267908
268129
  init_run_summary();
@@ -272549,16 +272770,16 @@ function correspondenceDisposalCheck(projectId14, archived) {
272549
272770
  }
272550
272771
  return hasUnresolvedDelivery(peek.file) ? { ok: false, error: archived ? "This archived project has a Gmail delivery that must be recovered before it can be deleted." : "This project has a Gmail delivery that must be recovered before it can be archived." } : { ok: true };
272551
272772
  }
272552
- function generalProject(deps, id2) {
272773
+ function correspondenceProject(deps, id2) {
272553
272774
  const project3 = deps.project(id2);
272554
272775
  if (!project3) return { ok: false, status: 404, code: "project-not-found", error: "FloLess can\u2019t find that project in this Workspace. It may have been removed." };
272555
- if (project3.app !== GENERAL_PROJECT_APP_ID) return { ok: false, status: 409, code: "not-general", error: "This project\u2019s RFIs are in its steel editor. Open them there." };
272556
- if (!project3.uuid) return { ok: false, status: 409, code: "project-unsigned", error: "This project has no identity yet, so it can\u2019t keep RFIs. Duplicate it from the Workspaces page to give it one." };
272776
+ const refusal6 = correspondenceProjectRefusal(project3, deps.templateOf);
272777
+ if (refusal6) return { ok: false, ...refusal6 };
272557
272778
  return project3;
272558
272779
  }
272559
272780
  function identityGuard(deps, id2, body3) {
272560
272781
  return () => {
272561
- const project3 = generalProject(deps, id2);
272782
+ const project3 = correspondenceProject(deps, id2);
272562
272783
  if ("ok" in project3) return { ok: false, code: project3.code, error: project3.error };
272563
272784
  const refusal6 = checkExpectedIdentity(body3, { rootId: deps.rootId(), project: project3 }, CORRESPONDENCE_IDENTITY_MESSAGES);
272564
272785
  return refusal6 ? { ok: false, ...refusal6 } : null;
@@ -272577,7 +272798,7 @@ function registerCorrespondenceDeliveryRoutes(app, deps) {
272577
272798
  addDeliveryDisposalCheck(app, correspondenceDisposalCheck);
272578
272799
  const base3 = "/api/projects/:id/correspondence-rfis";
272579
272800
  app.get(`${base3}/gmail-readiness`, async (req, reply) => {
272580
- const project3 = generalProject(deps, req.params.id);
272801
+ const project3 = correspondenceProject(deps, req.params.id);
272581
272802
  if ("ok" in project3) return reply.status(project3.status).send({ ok: false, code: project3.code, error: project3.error });
272582
272803
  try {
272583
272804
  return { ok: true, readiness: await delivery.inspectReadiness() };
@@ -272588,7 +272809,7 @@ function registerCorrespondenceDeliveryRoutes(app, deps) {
272588
272809
  });
272589
272810
  const admit2 = (id2, rawBody, allowed) => {
272590
272811
  const body3 = isObject15(rawBody) ? rawBody : {};
272591
- const project3 = generalProject(deps, id2);
272812
+ const project3 = correspondenceProject(deps, id2);
272592
272813
  if ("ok" in project3) return { refusal: { status: project3.status, body: { ok: false, code: project3.code, error: project3.error } } };
272593
272814
  if (!onlyKeys13(body3, [...allowed, ...IDENTITY_KEYS])) {
272594
272815
  return { refusal: { status: 400, body: { ok: false, code: "rfi-body-unknown-field", error: "that request carries a field this server does not know" } } };
@@ -272703,7 +272924,6 @@ var init_rfi_correspondence_delivery = __esm({
272703
272924
  "rfi-correspondence-delivery.ts"() {
272704
272925
  "use strict";
272705
272926
  import_node_crypto162 = require("node:crypto");
272706
- init_project_types();
272707
272927
  init_project_directory();
272708
272928
  init_rfi_delivery_journal();
272709
272929
  init_rfi_delivery_engine();
@@ -272751,15 +272971,15 @@ function send3(reply, error62) {
272751
272971
  if (error62 instanceof CorrespondenceRfiError) return reply.status(error62.status).send({ ok: false, code: error62.code, error: error62.message });
272752
272972
  throw error62;
272753
272973
  }
272754
- function generalProject2(deps, id2) {
272974
+ function correspondenceProject2(deps, id2) {
272755
272975
  const project3 = deps.project(id2);
272756
272976
  if (!project3) throw new CorrespondenceRfiError(404, "project-not-found", "FloLess can\u2019t find that project in this Workspace. It may have been removed.");
272757
- if (project3.app !== GENERAL_PROJECT_APP_ID) throw new CorrespondenceRfiError(409, "not-general", "This project\u2019s RFIs are in its steel editor. Open them there.");
272758
- if (!project3.uuid) throw new CorrespondenceRfiError(409, "project-unsigned", "This project has no identity yet, so it can\u2019t keep RFIs. Duplicate it from the Workspaces page to give it one.");
272759
- return project3;
272977
+ const admission = correspondenceProjectAdmission(project3, deps.templateOf);
272978
+ if (!admission.ok) throw new CorrespondenceRfiError(admission.refusal.status, admission.refusal.code, admission.refusal.error);
272979
+ return { ...project3, uuid: project3.uuid, linksProjects: admission.template === GENERAL_PROJECT_APP_ID };
272760
272980
  }
272761
272981
  function lockedProject(deps, id2, body3) {
272762
- const project3 = generalProject2(deps, id2);
272982
+ const project3 = correspondenceProject2(deps, id2);
272763
272983
  const refusal6 = checkExpectedIdentity(body3, { rootId: deps.rootId(), project: project3 }, CORRESPONDENCE_IDENTITY_MESSAGES);
272764
272984
  if (refusal6) throw new CorrespondenceRfiError(409, refusal6.code, refusal6.error);
272765
272985
  return project3;
@@ -272770,6 +272990,7 @@ function storeOrRefuse(projectId14) {
272770
272990
  return read5.file;
272771
272991
  }
272772
272992
  function linkedTargets(deps, project3, actor, purpose) {
272993
+ if (!project3.linksProjects) return [];
272773
272994
  return deps.links(project3).map((link2) => {
272774
272995
  if (link2.state !== "live" || !link2.target) {
272775
272996
  const reason = link2.state === "archived" ? `${link2.name} is archived.` : link2.state === "missing" ? `${link2.name} isn\u2019t in this Workspace any more.` : link2.state === "needs-reconnect" ? `${link2.name} came from another Workspace and needs reconnecting on the Modules step.` : link2.state === "not-available" ? `${link2.name} isn\u2019t available on this account.` : link2.reason ?? `${link2.name} is unavailable just now.`;
@@ -272828,8 +273049,8 @@ function registerCorrespondenceRfiRoutes(app, deps) {
272828
273049
  app.get("/api/projects/:id/correspondence-rfis", async (req, reply) => {
272829
273050
  try {
272830
273051
  const actor = deps.actor(req);
272831
- return await deps.withProjectLock(generalProject2(deps, req.params.id).id, () => {
272832
- const project3 = generalProject2(deps, req.params.id);
273052
+ return await deps.withProjectLock(correspondenceProject2(deps, req.params.id).id, () => {
273053
+ const project3 = correspondenceProject2(deps, req.params.id);
272833
273054
  const rootId2 = deps.rootId();
272834
273055
  const head2 = { ok: true, rootId: rootId2, project: { id: project3.id, uuid: project3.uuid.toLowerCase(), name: project3.name ?? project3.id } };
272835
273056
  const read5 = readCorrespondenceStore(project3.id);
@@ -272888,8 +273109,8 @@ function registerCorrespondenceRfiRoutes(app, deps) {
272888
273109
  try {
272889
273110
  const actor = deps.actor(req);
272890
273111
  const q10 = typeof req.query.q === "string" ? req.query.q.slice(0, 200) : "";
272891
- return await deps.withProjectLock(generalProject2(deps, req.params.id).id, () => {
272892
- const project3 = generalProject2(deps, req.params.id);
273112
+ return await deps.withProjectLock(correspondenceProject2(deps, req.params.id).id, () => {
273113
+ const project3 = correspondenceProject2(deps, req.params.id);
272893
273114
  let knowledge;
272894
273115
  try {
272895
273116
  const current = currentKnowledgePages(project3.id, q10);
@@ -272918,8 +273139,8 @@ function registerCorrespondenceRfiRoutes(app, deps) {
272918
273139
  });
272919
273140
  app.get("/api/projects/:id/correspondence-rfis/:rfiId/text", async (req, reply) => {
272920
273141
  try {
272921
- return await deps.withProjectLock(generalProject2(deps, req.params.id).id, () => {
272922
- const project3 = generalProject2(deps, req.params.id);
273142
+ return await deps.withProjectLock(correspondenceProject2(deps, req.params.id).id, () => {
273143
+ const project3 = correspondenceProject2(deps, req.params.id);
272923
273144
  const record9 = storeOrRefuse(project3.id).records.find((r) => r.id === req.params.rfiId);
272924
273145
  if (!record9) throw new CorrespondenceRfiError(404, "rfi-not-found", "FloLess can\u2019t find that RFI in this project any more.");
272925
273146
  return { ok: true, rfiId: record9.id, ...correspondenceEmailText(record9, project3.name ?? project3.id) };
@@ -272930,7 +273151,7 @@ function registerCorrespondenceRfiRoutes(app, deps) {
272930
273151
  });
272931
273152
  app.post("/api/projects/:id/correspondence-rfis", async (req, reply) => {
272932
273153
  try {
272933
- const lockId = generalProject2(deps, req.params.id).id;
273154
+ const lockId = correspondenceProject2(deps, req.params.id).id;
272934
273155
  const body3 = req.body ?? {};
272935
273156
  const actor = deps.actor(req);
272936
273157
  const problem3 = fileInputProblem({ title: body3.title, question: body3.question, citations: body3.citations, markSentTo: body3.markSentTo });
@@ -272953,6 +273174,9 @@ function registerCorrespondenceRfiRoutes(app, deps) {
272953
273174
  return resolved.citation;
272954
273175
  }
272955
273176
  if (c.kind === "linked-drawing" && typeof c.linkedProjectUuid === "string" && typeof c.pageId === "string" && typeof c.sourceHash === "string") {
273177
+ if (!project4.linksProjects) {
273178
+ throw new CorrespondenceRfiError(409, "citation-not-linkable", "This project\u2019s RFIs cite its own Knowledge. Choose a Knowledge page instead.");
273179
+ }
272956
273180
  const t = targets.find((x) => x.link.projectUuid === c.linkedProjectUuid.toLowerCase());
272957
273181
  if (!t) throw new CorrespondenceRfiError(409, "citation-link-removed", "That project isn\u2019t linked here any more. Choose another sheet.");
272958
273182
  if ("why" in t) throw new CorrespondenceRfiError(409, t.why === "out-of-scope" ? "citation-out-of-scope" : "citation-project-unavailable", t.reason);
@@ -273008,7 +273232,7 @@ function registerCorrespondenceRfiRoutes(app, deps) {
273008
273232
  try {
273009
273233
  const verb = req.params.verb;
273010
273234
  if (!VERBS.includes(verb)) throw new CorrespondenceRfiError(404, "unknown-verb", "FloLess doesn\u2019t know that RFI action.");
273011
- const lockId = generalProject2(deps, req.params.id).id;
273235
+ const lockId = correspondenceProject2(deps, req.params.id).id;
273012
273236
  const body3 = req.body ?? {};
273013
273237
  const actor = deps.actor(req);
273014
273238
  if (typeof body3.operationKey !== "string" || !Number.isSafeInteger(body3.recordRevision)) {
@@ -273057,7 +273281,7 @@ function registerCorrespondenceRfiRoutes(app, deps) {
273057
273281
  });
273058
273282
  app.post("/api/projects/:id/correspondence-rfis/repair", async (req, reply) => {
273059
273283
  try {
273060
- const lockId = generalProject2(deps, req.params.id).id;
273284
+ const lockId = correspondenceProject2(deps, req.params.id).id;
273061
273285
  const body3 = req.body ?? {};
273062
273286
  const outcome = await deps.withProjectLock(lockId, () => repairCorrespondenceStore(lockedProject(deps, req.params.id, body3).id));
273063
273287
  if (outcome.outcome === "still-quarantined") return { ok: true, outcome: outcome.outcome, message: outcome.message };
@@ -318397,7 +318621,7 @@ var init_rfis_correspondence = __esm({
318397
318621
  init_zod();
318398
318622
  init_catalog();
318399
318623
  init_rfi_action_fields();
318400
- projectId9 = external_exports.string().min(1).describe("The General project id, as listed by projects.list.");
318624
+ projectId9 = external_exports.string().min(1).describe("The id of a General, Trace, Revit, Tekla or Drawing Checker project, as listed by projects.list. A steel project's RFIs use the rfis.* actions instead.");
318401
318625
  rootId = external_exports.string().min(1).max(200).describe("The rootId from rfis.correspondence-list, so the change lands in the Workspace you read.");
318402
318626
  projectUuid = external_exports.string().uuid().describe("The project.uuid from rfis.correspondence-list.");
318403
318627
  rfiId3 = external_exports.string().regex(/^RFI-\d{3,}$/).describe("The RFI id, such as RFI-001, from rfis.correspondence-list.");
@@ -318420,8 +318644,8 @@ var init_rfis_correspondence = __esm({
318420
318644
  correspondenceRfiActions = [
318421
318645
  defineAction({
318422
318646
  id: "rfis.correspondence-list",
318423
- title: "List a General project's RFIs",
318424
- description: "Lists the RFIs of one General project as its RFIs step shows them: status, what was sent and answered, and whether each cited Knowledge page or drawing sheet is still current. Read it before changing one.",
318647
+ title: "List the RFIs on a project's RFIs step",
318648
+ description: "Lists the RFIs of one General, Trace, Revit, Tekla or Drawing Checker project as its RFIs step shows them: status, what was sent and answered, and whether each cited Knowledge page or drawing sheet is still current. Read it before changing one.",
318425
318649
  risk: "read",
318426
318650
  riskReason: "Reads the project's RFIs and checks what they cite; changes nothing and sends nothing.",
318427
318651
  scope: "project",
@@ -318431,8 +318655,8 @@ var init_rfis_correspondence = __esm({
318431
318655
  }),
318432
318656
  defineAction({
318433
318657
  id: "rfis.correspondence-citable",
318434
- title: "List what a General project's RFI can cite",
318435
- description: "Lists the pages of this project's Knowledge and the saved drawing sheets of the projects linked on its Modules step that a new RFI can cite. A linked project outside this chat's scope is named but its sheets are not read.",
318658
+ title: "List what a project's RFI can cite",
318659
+ description: "Lists the pages of this project's Knowledge that a new RFI can cite and, on a General project only, the saved drawing sheets of the projects linked on its Modules step. A linked project outside this chat's scope is named but its sheets are not read.",
318436
318660
  risk: "read",
318437
318661
  riskReason: "Reads Knowledge page titles and saved sheet names; changes nothing.",
318438
318662
  scope: "project",
@@ -318453,7 +318677,7 @@ var init_rfis_correspondence = __esm({
318453
318677
  }),
318454
318678
  defineAction({
318455
318679
  id: "rfis.correspondence-file",
318456
- title: "File an RFI in a General project",
318680
+ title: "File an RFI on a project's RFIs step",
318457
318681
  description: "Files a new RFI with its question and up to five citations from rfis.correspondence-citable. It records the question only. To also record that it was sent, use the file-and-mark-sent action.",
318458
318682
  risk: "write",
318459
318683
  riskReason: "Adds an open RFI to the project; it sends nothing, and it can be closed as withdrawn.",
@@ -318485,7 +318709,7 @@ var init_rfis_correspondence = __esm({
318485
318709
  }),
318486
318710
  defineAction({
318487
318711
  id: "rfis.correspondence-mark-sent",
318488
- title: "Record that a General project's RFI was sent",
318712
+ title: "Record that a project's RFI was sent",
318489
318713
  description: "Records that the person sent an open RFI to one email address. FloLess sends nothing: use it only after the person sent it themself. To send through the connected Gmail account use rfis.correspondence-deliver.",
318490
318714
  risk: "destructive",
318491
318715
  riskReason: "Writes down that the question was told to someone outside; that entry cannot be unsaid, so you confirm it on a card.",
@@ -318501,7 +318725,7 @@ var init_rfis_correspondence = __esm({
318501
318725
  }),
318502
318726
  defineAction({
318503
318727
  id: "rfis.correspondence-answer",
318504
- title: "Record the answer to a General project's RFI",
318728
+ title: "Record the answer to a project's RFI",
318505
318729
  description: "Records the answer that came back on an open or sent RFI. Record only what the person was actually told.",
318506
318730
  risk: "write",
318507
318731
  riskReason: "Adds the answer to the RFI's history; it sends nothing, and the RFI can be closed or reopened afterwards.",
@@ -318517,7 +318741,7 @@ var init_rfis_correspondence = __esm({
318517
318741
  }),
318518
318742
  defineAction({
318519
318743
  id: "rfis.correspondence-close",
318520
- title: "Close a General project's RFI",
318744
+ title: "Close a project's RFI",
318521
318745
  description: "Closes an RFI: as answered (only once it has an answer), withdrawn, superseded or won't fix. Every reason but answered needs a short note.",
318522
318746
  risk: "write",
318523
318747
  riskReason: "Closes the RFI in its history; it sends nothing and can be reopened.",
@@ -318541,7 +318765,7 @@ var init_rfis_correspondence = __esm({
318541
318765
  }),
318542
318766
  defineAction({
318543
318767
  id: "rfis.correspondence-reopen",
318544
- title: "Reopen a General project's RFI",
318768
+ title: "Reopen a project's RFI",
318545
318769
  description: "Reopens a closed RFI, with the reason. Its earlier sends and answers stay in its history.",
318546
318770
  risk: "write",
318547
318771
  riskReason: "Reopens the RFI in its history; it sends nothing and it can be closed again.",
@@ -318557,8 +318781,8 @@ var init_rfis_correspondence = __esm({
318557
318781
  }),
318558
318782
  defineAction({
318559
318783
  id: "rfis.correspondence-gmail-readiness",
318560
- title: "Check whether a General project's RFI can be sent through Gmail",
318561
- description: "Says whether the connected Google account is ready to send an RFI of this General project, and if not, what to do about it. Read this before offering to send one.",
318784
+ title: "Check whether a project's RFI can be sent through Gmail",
318785
+ description: "Says whether the connected Google account is ready to send an RFI of this project, and if not, what to do about it. Read this before offering to send one.",
318562
318786
  risk: "read",
318563
318787
  riskReason: "Checks the connection only; it sends nothing and changes nothing.",
318564
318788
  scope: "project",
@@ -318568,7 +318792,7 @@ var init_rfis_correspondence = __esm({
318568
318792
  }),
318569
318793
  defineAction({
318570
318794
  id: "rfis.correspondence-deliver",
318571
- title: "Send a General project's RFI through the connected Gmail account",
318795
+ title: "Send a project's RFI through the connected Gmail account",
318572
318796
  description: "Emails the RFI, exactly as Copy email text gives it plus a reference line, to one person through the Google account connected to FloLess. Check rfis.correspondence-gmail-readiness first. A recorded attempt means Gmail accepted it for delivery, which does not prove it reached the inbox.",
318573
318797
  risk: "destructive",
318574
318798
  riskReason: "Sends a real email to an outside party; it cannot be recalled, and the send is recorded in the correspondence history.",
@@ -318584,7 +318808,7 @@ var init_rfis_correspondence = __esm({
318584
318808
  }),
318585
318809
  defineAction({
318586
318810
  id: "rfis.correspondence-deliver-continue",
318587
- title: "Finish a General project's Gmail send that was left half done",
318811
+ title: "Finish a project's Gmail send that was left half done",
318588
318812
  description: 'Finishes the one Gmail send FloLess began but did not finish recording (its status is "prepared"). It never starts a second send. Do not use it when the status is "outcome unknown".',
318589
318813
  risk: "destructive",
318590
318814
  riskReason: "May hand the reserved email to Gmail for the first time, which cannot be recalled.",
@@ -318601,7 +318825,7 @@ var init_rfis_correspondence = __esm({
318601
318825
  }),
318602
318826
  defineAction({
318603
318827
  id: "rfis.correspondence-deliver-confirm-sent",
318604
- title: "Record that a General project's unconfirmed Gmail send was found in Sent",
318828
+ title: "Record that a project's unconfirmed Gmail send was found in Sent",
318605
318829
  description: "Only when the person has found the exact FloLess marker of this send in the connected account's Sent folder. It records that fact. It is never a resend and never a guess.",
318606
318830
  risk: "destructive",
318607
318831
  riskReason: "Writes into the correspondence history that you found this message in the sender's Sent folder, which cannot be unsaid. It does not say the email was delivered, and it sends nothing.",
@@ -318615,10 +318839,10 @@ var init_rfis_correspondence = __esm({
318615
318839
  body: { operationKey: operationKeyOf(ctx), ...identity6(i) }
318616
318840
  })
318617
318841
  }),
318618
- // #2470 R6.6e: the ways out of a Gmail send FloLess could not confirm, in a General project. The person chooses.
318842
+ // #2470 R6.6e: the ways out of a Gmail send FloLess could not confirm, on a project's RFIs step. The person chooses.
318619
318843
  defineAction({
318620
318844
  id: "rfis.correspondence-deliver-try-again",
318621
- title: "Send a General project's unconfirmed RFI again through Gmail",
318845
+ title: "Send a project's unconfirmed RFI again through Gmail",
318622
318846
  description: 'For a Gmail send of this RFI that FloLess could not confirm (status "outcome unknown"): settles that send as unconfirmed and sends the RFI again as a new email. The engineer may then get it twice. Check the Sent folder first: if it is there, record that instead.',
318623
318847
  risk: "destructive",
318624
318848
  riskReason: "Sends a real email that cannot be recalled, possibly a second copy of one Gmail already sent, and records the earlier send as unconfirmed for good.",
@@ -318634,7 +318858,7 @@ var init_rfis_correspondence = __esm({
318634
318858
  }),
318635
318859
  defineAction({
318636
318860
  id: "rfis.correspondence-deliver-sent-another-way",
318637
- title: "Record that a General project's unconfirmed RFI was sent another way",
318861
+ title: "Record that a project's unconfirmed RFI was sent another way",
318638
318862
  description: "For a Gmail send of this RFI that FloLess could not confirm: records that the person sent the RFI themselves, by email or another way they name, and settles the Gmail send as unconfirmed. Use only on the person's word. It sends nothing.",
318639
318863
  risk: "destructive",
318640
318864
  riskReason: "Writes into the correspondence history that the person sent this RFI themselves and marks it sent, which cannot be unsaid; the Gmail send is settled as unconfirmed for good.",
@@ -318650,7 +318874,7 @@ var init_rfis_correspondence = __esm({
318650
318874
  }),
318651
318875
  defineAction({
318652
318876
  id: "rfis.correspondence-deliver-leave-unconfirmed",
318653
- title: "Leave a General project's Gmail send unconfirmed",
318877
+ title: "Leave a project's Gmail send unconfirmed",
318654
318878
  description: "For a Gmail send of this RFI that FloLess could not confirm or did not finish: settles it as unconfirmed, so the RFI can move on. FloLess will not send it, and cannot say whether Gmail already did. Use only on the person's word.",
318655
318879
  risk: "destructive",
318656
318880
  riskReason: "Settles the send for good: FloLess will never finish or confirm it, though Gmail may already have sent it. It sends nothing.",
@@ -321327,8 +321551,8 @@ var init_chat = __esm({
321327
321551
  chatCitationActions = [
321328
321552
  defineAction({
321329
321553
  id: "chat.cite-assume",
321330
- title: "Go on with a claim as an assumption",
321331
- description: 'Opens this conversation. Under the answer, the claim with no source has a "Go on with this as an assumption" button that only you can press.',
321554
+ title: "Record a claim as an assumption",
321555
+ description: 'Opens this conversation. Under the answer, the claim with no source has a "Record as an assumption" button that only you can press. It saves your decision, and nothing runs until your next message.',
321332
321556
  risk: "human-only",
321333
321557
  riskReason: "Going on without a source is your decision, recorded with your account and the date; the AI never records an assumption for you.",
321334
321558
  scope: "global",
@@ -324154,7 +324378,7 @@ var init_integrations = __esm({
324154
324378
  title: "Start signing in to a service",
324155
324379
  description: "Opens the service\u2019s own sign-in in your browser so you can connect your account. You sign in there yourself. FloLess never sees your password, and the AI never gets any key or token.",
324156
324380
  risk: "destructive",
324157
- riskReason: "It opens a sign-in window on your computer and, once you finish it, stores a connection for that service, so you confirm it first. Signing in is always done by you. For Google Workspace it may first switch this computer to FloLess\u2019s own Google sign-in, which stays even if you cancel.",
324381
+ riskReason: "It opens a sign-in window on your computer and, once you finish it, stores a connection for that service, so you confirm it first. Signing in is always done by you. For Google Workspace it may first switch this computer to FloLess\u2019s own Google sign-in. For Microsoft 365 it switches to FloLess\u2019s own Microsoft sign-in unless you already use your own Microsoft app, so other Microsoft accounts signed in the old way will need Reconnect. Either switch stays even if you cancel.",
324158
324382
  scope: "global",
324159
324383
  route: { method: "POST", path: "/api/connect/:id" },
324160
324384
  input: external_exports.object({
@@ -354637,6 +354861,9 @@ function assertChosenAccount(read5, integration, label2, alias3) {
354637
354861
  );
354638
354862
  }
354639
354863
  }
354864
+ function isAgentCallUnsupported(error62) {
354865
+ return error62?.detail?.error?.code === "E_CALL_UNSUPPORTED";
354866
+ }
354640
354867
  function supported(integration) {
354641
354868
  const row3 = SUPPORTED_CHAT_INTEGRATIONS.find((candidate2) => candidate2.integration === integration);
354642
354869
  if (!row3) throw new ChatIntegrationPolicyError(
@@ -365196,6 +365423,37 @@ var init_read_setup_routes = __esm({
365196
365423
  }
365197
365424
  });
365198
365425
 
365426
+ // sign-in-supersession.ts
365427
+ function createSignInSupersession() {
365428
+ let generation = 0;
365429
+ let cancelActive = null;
365430
+ return {
365431
+ begin() {
365432
+ const mine = ++generation;
365433
+ const open8 = cancelActive;
365434
+ cancelActive = null;
365435
+ open8?.();
365436
+ let own7 = null;
365437
+ return {
365438
+ superseded: () => mine !== generation,
365439
+ adopt(cancel) {
365440
+ own7 = cancel;
365441
+ if (mine !== generation) cancel();
365442
+ else cancelActive = cancel;
365443
+ },
365444
+ end() {
365445
+ if (own7 && cancelActive === own7) cancelActive = null;
365446
+ }
365447
+ };
365448
+ }
365449
+ };
365450
+ }
365451
+ var init_sign_in_supersession = __esm({
365452
+ "sign-in-supersession.ts"() {
365453
+ "use strict";
365454
+ }
365455
+ });
365456
+
365199
365457
  // credential-renewal.ts
365200
365458
  function slotKey(row3) {
365201
365459
  return `${row3.integration}\0${row3.alias ?? ""}\0${row3.generation ?? ""}`;
@@ -365850,7 +366108,7 @@ function beginGoogleConnectFenceLifetime(options2) {
365850
366108
  void reportOnce(false);
365851
366109
  if (!startedSettled) {
365852
366110
  startedSettled = true;
365853
- rejectStarted(new Error(`Google Workspace sign-in timed out after ${options2.timeoutMs}ms`));
366111
+ rejectStarted(new Error(`${options2.label ?? "Google Workspace"} sign-in timed out after ${options2.timeoutMs}ms`));
365854
366112
  }
365855
366113
  cancel?.();
365856
366114
  }, options2.timeoutMs);
@@ -365861,7 +366119,7 @@ function beginGoogleConnectFenceLifetime(options2) {
365861
366119
  clearTimeout(timer);
365862
366120
  if (!startedSettled) {
365863
366121
  startedSettled = true;
365864
- rejectStarted(new Error("Google Workspace sign-in ended before it started"));
366122
+ rejectStarted(new Error(`${options2.label ?? "Google Workspace"} sign-in ended before it started`));
365865
366123
  }
365866
366124
  void (timedOut ? reportPromise : reportOnce(ok2)).then(resolveCompletion, rejectCompletion);
365867
366125
  };
@@ -366526,7 +366784,7 @@ async function startServer() {
366526
366784
  }
366527
366785
  const recoveredRfiDelivery = !projectIdentityReady || !workspaceRootState().available ? null : await withRfiGmailFence(() => recoverOwnedRfiDeliveryStaging(void 0, (evidence) => {
366528
366786
  if (steelEvidenceFinalized(listProjects().map((project3) => project3.id), evidence)) return true;
366529
- return correspondenceEvidenceFinalized(listProjects().filter((project3) => project3.app === GENERAL_PROJECT_APP_ID).map((project3) => project3.id), evidence);
366787
+ return correspondenceEvidenceFinalized(listProjects().filter((project3) => correspondenceRfiKind(project3) !== "not").map((project3) => project3.id), evidence);
366530
366788
  }), { label: "recovering private RFI Gmail delivery", expectedMs: 1e4 }).catch((error62) => {
366531
366789
  if (error62 instanceof WorkspaceRootError) {
366532
366790
  app.log.info({ error: error62.message }, "skipped project RFI recovery while the selected workspace root is unavailable");
@@ -368081,6 +368339,7 @@ async function startServer() {
368081
368339
  }
368082
368340
  } catch (error62) {
368083
368341
  unavailableReason2 = error62 instanceof Error ? error62.message : String(error62);
368342
+ if (isAgentCallUnsupported(error62)) unavailableCode = "call-unsupported";
368084
368343
  }
368085
368344
  }
368086
368345
  return {
@@ -368225,6 +368484,76 @@ async function startServer() {
368225
368484
  });
368226
368485
  return childStarted;
368227
368486
  }
368487
+ const MICROSOFT_INTEGRATION = "microsoft-365";
368488
+ const MICROSOFT_CONNECT_FENCE_KEY = "microsoft-365-connect";
368489
+ const MICROSOFT_SETUP_FAILED = "FloLess couldn\u2019t prepare its Microsoft sign-in on this computer. Try connecting again, and if it keeps happening, report the problem from the menu.";
368490
+ const MICROSOFT_SWITCHED_UNFINISHED = "Microsoft sign-in didn\u2019t finish. FloLess now uses its own Microsoft sign-in, so click Connect to sign in again, and reconnect any other Microsoft account you signed in before.";
368491
+ const MICROSOFT_SIGN_IN_REPLACED = "A newer Microsoft sign-in started, so this one stopped. Finish the newest one in your browser.";
368492
+ const microsoftSignIns = createSignInSupersession();
368493
+ function startFencedMicrosoftConnect(id2, opts) {
368494
+ let startedResolve;
368495
+ let startedReject;
368496
+ let started = false;
368497
+ const childStarted = new Promise((resolve76, reject4) => {
368498
+ startedResolve = resolve76;
368499
+ startedReject = reject4;
368500
+ });
368501
+ const attempt2 = microsoftSignIns.begin();
368502
+ const background = withLifecycleLock("internal-export", MICROSOFT_CONNECT_FENCE_KEY, async () => {
368503
+ if (attempt2.superseded()) {
368504
+ started = true;
368505
+ startedResolve({ started: false, message: MICROSOFT_SIGN_IN_REPLACED });
368506
+ return;
368507
+ }
368508
+ let profile;
368509
+ try {
368510
+ profile = ensureManagedProfile(id2);
368511
+ } catch (error62) {
368512
+ app.log.warn({ id: id2, err: error62 instanceof Error ? error62.message : "unknown" }, "preparing FloLess Microsoft sign-in failed");
368513
+ await finishConnect(id2, false, MICROSOFT_SETUP_FAILED);
368514
+ started = true;
368515
+ startedResolve({ started: false, message: MICROSOFT_SETUP_FAILED });
368516
+ return;
368517
+ }
368518
+ const lifetime = beginGoogleConnectFenceLifetime({
368519
+ label: "Microsoft 365",
368520
+ timeoutMs: GOOGLE_CONNECT_MAX_MS,
368521
+ start: async (onClosed) => {
368522
+ const close2 = (ok2, detail) => {
368523
+ if (!ok2) app.log.warn({ id: id2, alias: opts.alias, flow: opts.flow, profile, ...detail }, "Microsoft 365 sign-in did not finish");
368524
+ onClosed(ok2);
368525
+ };
368526
+ const handle = opts.flow === "device-code" ? await aware.connectDeviceCode(id2, (event) => {
368527
+ if (event.phase === "result") close2(event.status === "connected", { status: event.status, error: event.error ?? null });
368528
+ }, { alias: opts.alias }) : await aware.connectOAuth(
368529
+ id2,
368530
+ (result2) => close2(result2.status === "connected", { status: result2.status, code: result2.code }),
368531
+ { alias: opts.alias }
368532
+ );
368533
+ attempt2.adopt(handle.cancel);
368534
+ const answer4 = attempt2.superseded() ? { started: false, message: MICROSOFT_SIGN_IN_REPLACED } : { started: true, ..."prompt" in handle ? { prompt: handle.prompt } : {} };
368535
+ return { started: answer4, cancel: handle.cancel };
368536
+ },
368537
+ // A stopped, replaced sign-in reports nothing (a credential it did store still is). Writing the profile just now
368538
+ // switched this computer's Microsoft sign-ins, so an unfinished one says so.
368539
+ reportResult: (ok2) => ok2 || !attempt2.superseded() ? finishConnect(id2, ok2, profile === "written" ? MICROSOFT_SWITCHED_UNFINISHED : void 0) : void 0
368540
+ });
368541
+ void lifetime.started.then((value2) => {
368542
+ started = true;
368543
+ startedResolve(value2);
368544
+ }, startedReject);
368545
+ try {
368546
+ await lifetime.completion;
368547
+ } finally {
368548
+ attempt2.end();
368549
+ }
368550
+ }, { label: "connecting Microsoft 365" });
368551
+ void background.catch((error62) => {
368552
+ if (!started) startedReject(error62);
368553
+ app.log.warn({ id: id2, err: error62 instanceof Error ? error62.message : "unknown" }, "Microsoft 365 sign-in failed under its connect fence");
368554
+ });
368555
+ return childStarted;
368556
+ }
368228
368557
  async function startFencedGoogleDeviceCode(id2, alias3) {
368229
368558
  let startedResolve;
368230
368559
  let startedReject;
@@ -368261,13 +368590,18 @@ async function startServer() {
368261
368590
  const request = parseConnectRequest(req.body);
368262
368591
  if ("error" in request) return reply.status(400).send({ ok: false, error: request.error });
368263
368592
  const { alias: alias3, drive } = request;
368264
- try {
368265
- ensureManagedProfile(id2);
368266
- } catch (err2) {
368267
- app.log.warn({ id: id2, err: String(err2) }, "ensureManagedProfile failed");
368593
+ if (id2 !== MICROSOFT_INTEGRATION) {
368594
+ try {
368595
+ ensureManagedProfile(id2);
368596
+ } catch (err2) {
368597
+ app.log.warn({ id: id2, err: String(err2) }, "ensureManagedProfile failed");
368598
+ }
368268
368599
  }
368269
368600
  const requested = req.body?.flow;
368270
368601
  const flow = requested === "device-code" || requested === "oauth" ? requested : DEFAULT_CONNECT_FLOW[id2] ?? "oauth";
368602
+ if (id2 === MICROSOFT_INTEGRATION) {
368603
+ return { ok: true, id: id2, flow, ...await startFencedMicrosoftConnect(id2, { alias: alias3, flow }) };
368604
+ }
368271
368605
  if (flow === "device-code") {
368272
368606
  if (id2 === GOOGLE_INTEGRATION) {
368273
368607
  const rows4 = await aware.connectList().catch((error62) => {
@@ -368293,7 +368627,7 @@ async function startServer() {
368293
368627
  return { ok: true, id: id2, flow, prompt };
368294
368628
  }
368295
368629
  const preset = OAUTH_PRESETS[id2];
368296
- if (preset && !await isPortBindable(preset.callbackPort)) {
368630
+ if (preset?.callbackPort != null && !await isPortBindable(preset.callbackPort)) {
368297
368631
  broadcast({
368298
368632
  type: "connect-result",
368299
368633
  id: id2,
@@ -368700,6 +369034,7 @@ async function startServer() {
368700
369034
  throw error62;
368701
369035
  }
368702
369036
  },
369037
+ templateOf: resolveTemplateIdStrict,
368703
369038
  rootId: () => activeWorkspaceRoot().rootId,
368704
369039
  links: (project3) => {
368705
369040
  const rows4 = projectLinksDeps.rows();
@@ -368722,6 +369057,7 @@ async function startServer() {
368722
369057
  throw error62;
368723
369058
  }
368724
369059
  },
369060
+ templateOf: resolveTemplateIdStrict,
368725
369061
  rootId: () => activeWorkspaceRoot().rootId,
368726
369062
  withProjectLock: (projectId14, work) => withProjectMutationLock(projectId14, () => work(), { label: "changing a project\u2019s RFIs" }),
368727
369063
  broadcast: (projectId14) => broadcast({ type: "projects-changed", projectId: projectId14 }),
@@ -377761,7 +378097,7 @@ ${v10.prompt}` : "";
377761
378097
  try {
377762
378098
  if (!knowledgeRetentionToken || !projectIdentityReady || !workspaceRootState().available) return;
377763
378099
  const chatSweep = await reconcileChatKnowledgeRetentionAsync({ root: knowledgeRetentionToken.root });
377764
- const rfiSweep = await reconcileRfiCitationRetention(listProjects().filter((project3) => project3.app === GENERAL_PROJECT_APP_ID));
378100
+ const rfiSweep = await sweepRfiCitationRetention(listProjects());
377765
378101
  assertWorkspaceRootCurrent(knowledgeRetentionToken.root);
377766
378102
  const decision = applyKnowledgeRetentionSweeps(
377767
378103
  knowledgeRetentionToken.root.rootId,
@@ -378168,6 +378504,7 @@ var init_index = __esm({
378168
378504
  init_project_links_routes();
378169
378505
  init_rfi_correspondence_routes();
378170
378506
  init_rfi_correspondence_delivery();
378507
+ init_rfi_correspondence();
378171
378508
  init_rfi_correspondence_citations();
378172
378509
  init_project_journal_sink();
378173
378510
  init_project_access();
@@ -378483,6 +378820,7 @@ var init_index = __esm({
378483
378820
  init_read_request_scope();
378484
378821
  init_revision_agent_scratch();
378485
378822
  init_chat_integration_policy();
378823
+ init_sign_in_supersession();
378486
378824
  init_credential_renewal();
378487
378825
  init_chat_integration_relay();
378488
378826
  init_chat_integration_tools();