@floless/app 0.149.0 → 0.149.1

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.
@@ -1670,7 +1670,7 @@ function appVersion() {
1670
1670
  return resolveVersion({
1671
1671
  isSea: isSea(),
1672
1672
  sqVersionXml: readSqVersionXml(),
1673
- define: true ? "0.149.0" : void 0,
1673
+ define: true ? "0.149.1" : void 0,
1674
1674
  pkgVersion: readPkgVersion()
1675
1675
  });
1676
1676
  }
@@ -1686,7 +1686,7 @@ function resolveChannel(s) {
1686
1686
  function appChannel() {
1687
1687
  return resolveChannel({
1688
1688
  isSea: isSea(),
1689
- define: true ? "0.149.0" : void 0,
1689
+ define: true ? "0.149.1" : void 0,
1690
1690
  // argv[1] is the entry the runtime actually loaded (…/dist/floless-server.cjs), which is what
1691
1691
  // carries the npx cache prefix. Absent under the SEA exe, which never reaches the npx branch.
1692
1692
  modulePath: process.argv[1]
@@ -1861,7 +1861,7 @@ var init_network_policy_active = __esm({
1861
1861
  });
1862
1862
 
1863
1863
  // bounded-response.ts
1864
- async function readBoundedText(response, maxBytes) {
1864
+ async function readBoundedText(response, maxBytes, signal) {
1865
1865
  const declared = Number(response.headers.get("content-length"));
1866
1866
  if (Number.isFinite(declared) && declared > maxBytes) {
1867
1867
  await response.body?.cancel().catch(() => void 0);
@@ -1871,18 +1871,32 @@ async function readBoundedText(response, maxBytes) {
1871
1871
  const reader = response.body.getReader();
1872
1872
  const chunks = [];
1873
1873
  let total2 = 0;
1874
+ let cancelling = null;
1875
+ const onAbort = () => {
1876
+ cancelling ??= reader.cancel(signal?.reason).catch(() => void 0);
1877
+ };
1878
+ signal?.addEventListener("abort", onAbort, { once: true });
1874
1879
  try {
1880
+ if (signal?.aborted) onAbort();
1875
1881
  while (true) {
1876
1882
  const { done, value } = await reader.read();
1877
- if (done) break;
1878
- total2 += value.byteLength;
1879
- if (total2 > maxBytes) {
1880
- await reader.cancel().catch(() => void 0);
1881
- throw new ResponseTooLargeError(maxBytes);
1883
+ if (!done) {
1884
+ total2 += value.byteLength;
1885
+ if (total2 > maxBytes) {
1886
+ await reader.cancel().catch(() => void 0);
1887
+ throw new ResponseTooLargeError(maxBytes);
1888
+ }
1889
+ }
1890
+ if (signal?.aborted) {
1891
+ onAbort();
1892
+ await cancelling;
1893
+ throw signal.reason ?? new Error("aborted");
1882
1894
  }
1895
+ if (done) break;
1883
1896
  chunks.push(value);
1884
1897
  }
1885
1898
  } finally {
1899
+ signal?.removeEventListener("abort", onAbort);
1886
1900
  reader.releaseLock();
1887
1901
  }
1888
1902
  return Buffer.concat(chunks, total2).toString("utf8");
@@ -91283,7 +91297,8 @@ var init_desktop_access_client = __esm({
91283
91297
  }
91284
91298
  }
91285
91299
  async request(trace, stage, url2, init) {
91286
- const signal = AbortSignal.timeout(this.deps.requestTimeoutMs);
91300
+ const bound = this.deps.requestTimeoutMs;
91301
+ const signal = AbortSignal.timeout(typeof bound === "function" ? bound(stage) : bound);
91287
91302
  return trace.stage(stage, async () => {
91288
91303
  try {
91289
91304
  return { response: await this.deps.fetch(url2, { ...init, redirect: "error", signal }), signal };
@@ -91296,7 +91311,7 @@ var init_desktop_access_client = __esm({
91296
91311
  async readJson(trace, stage, response, signal) {
91297
91312
  const text9 = await trace.stage(stage, async () => {
91298
91313
  try {
91299
- return await readBoundedText(response, 128 * 1024);
91314
+ return await readBoundedText(response, 128 * 1024, signal);
91300
91315
  } catch (error62) {
91301
91316
  if (error62 instanceof ResponseTooLargeError) throw new Error("desktop-access-response-too-large");
91302
91317
  throw new TransportFailure(stage, signal.aborted ? "timeout" : "unreadable");
@@ -143184,7 +143199,10 @@ function normalizeTeklaReadOperations(value) {
143184
143199
  if (!Array.isArray(value) || !value.length || value.length > TEKLA_CHAT_READ_OPERATIONS.length || new Set(value).size !== value.length || value.some((item) => !TEKLA_CHAT_READ_OPERATIONS.includes(item))) return null;
143185
143200
  return TEKLA_CHAT_READ_OPERATIONS.filter((operation) => value.includes(operation));
143186
143201
  }
143187
- var TEKLA_MODEL_READ_OPERATION, TEKLA_SELECTION_READ_OPERATION, TEKLA_CHAT_READ_OPERATIONS, TEKLA_MODEL_LIBRARY_PATTERN, TEKLA_READ_TOOL_NAME, TEKLA_SELECTION_TOOL_NAME, TEKLA_TOOL_OPERATIONS, TEKLA_SELECTION_ROW_LIMIT, TEKLA_LINKED_PART_CHECK_LIMIT, TEKLA_ALLOWANCE_SCOPE, TEKLA_ALLOWANCE_HISTORY_LIMIT, TEKLA_LINKED_PARTS_CHECKS;
143202
+ function sameConnector(a, b) {
143203
+ return a.provider === b.provider && a.server === b.server && (a.app ?? null) === (b.app ?? null);
143204
+ }
143205
+ var TEKLA_MODEL_READ_OPERATION, TEKLA_SELECTION_READ_OPERATION, TEKLA_CHAT_READ_OPERATIONS, TEKLA_MODEL_LIBRARY_PATTERN, TEKLA_READ_TOOL_NAME, TEKLA_SELECTION_TOOL_NAME, TEKLA_TOOL_OPERATIONS, TEKLA_SELECTION_ROW_LIMIT, TEKLA_LINKED_PART_CHECK_LIMIT, TEKLA_ALLOWANCE_SCOPE, TEKLA_ALLOWANCE_HISTORY_LIMIT, CONNECTOR_ALLOWANCE_LIMIT, CONNECTOR_ALLOWANCE_HISTORY_LIMIT, TEKLA_LINKED_PARTS_CHECKS;
143188
143206
  var init_chat_types = __esm({
143189
143207
  "chat-types.ts"() {
143190
143208
  "use strict";
@@ -143205,6 +143223,8 @@ var init_chat_types = __esm({
143205
143223
  TEKLA_LINKED_PART_CHECK_LIMIT = 1e3;
143206
143224
  TEKLA_ALLOWANCE_SCOPE = 3;
143207
143225
  TEKLA_ALLOWANCE_HISTORY_LIMIT = 20;
143226
+ CONNECTOR_ALLOWANCE_LIMIT = 32;
143227
+ CONNECTOR_ALLOWANCE_HISTORY_LIMIT = 20;
143208
143228
  TEKLA_LINKED_PARTS_CHECKS = ["unavailable", "partial"];
143209
143229
  }
143210
143230
  });
@@ -145853,6 +145873,124 @@ var init_knowledge_store = __esm({
145853
145873
  }
145854
145874
  });
145855
145875
 
145876
+ // chat-connector-allowance.ts
145877
+ function isName(value) {
145878
+ return typeof value === "string" && NAME2.test(value);
145879
+ }
145880
+ function parseConnectorIdentity(value) {
145881
+ const row2 = value;
145882
+ if (!row2 || typeof row2 !== "object") return null;
145883
+ if (row2.provider !== "claude" && row2.provider !== "codex") return null;
145884
+ if (!isName(row2.server)) return null;
145885
+ const app = row2.app ?? null;
145886
+ if (app !== null && !isName(app)) return null;
145887
+ return { provider: row2.provider, server: row2.server, app };
145888
+ }
145889
+ function parseConnectorCall(value) {
145890
+ const identity4 = parseConnectorIdentity(value);
145891
+ const row2 = value;
145892
+ if (!identity4 || typeof row2.verified !== "boolean") return null;
145893
+ const tool = typeof row2.tool === "string" && row2.tool.trim() && row2.tool.length <= 256 && !/[\u0000-\u001f]/u.test(row2.tool) ? row2.tool.trim() : null;
145894
+ if (!tool) return null;
145895
+ return { ...identity4, tool, verified: row2.verified };
145896
+ }
145897
+ function parseEntry(value) {
145898
+ const identity4 = parseConnectorIdentity(value);
145899
+ const row2 = value;
145900
+ if (!identity4 || typeof row2.grantedAt !== "string" || !Number.isFinite(Date.parse(row2.grantedAt)) || typeof row2.approvalId !== "string" || !UUID21.test(row2.approvalId)) return null;
145901
+ return { ...identity4, grantedAt: row2.grantedAt, approvalId: row2.approvalId.toLowerCase() };
145902
+ }
145903
+ function parseDecision(value) {
145904
+ const identity4 = parseConnectorIdentity(value);
145905
+ const row2 = value;
145906
+ if (!identity4 || row2.action !== "grant" && row2.action !== "revoke" || typeof row2.at !== "string" || !Number.isSafeInteger(row2.revision) || (row2.revision ?? 0) < 1) return null;
145907
+ const approvalId = typeof row2.approvalId === "string" && UUID21.test(row2.approvalId) ? row2.approvalId.toLowerCase() : void 0;
145908
+ return { ...identity4, action: row2.action, at: row2.at, revision: row2.revision, ...approvalId ? { approvalId } : {} };
145909
+ }
145910
+ function parseConnectorAllowance(value) {
145911
+ if (value === void 0 || value === null) return void 0;
145912
+ const row2 = value;
145913
+ if (typeof row2 !== "object" || !Number.isSafeInteger(row2.revision) || (row2.revision ?? -1) < 0) {
145914
+ throw new ConnectorAllowanceError("invalid connector allowance");
145915
+ }
145916
+ const allowed = [];
145917
+ for (const entry2 of Array.isArray(row2.allowed) ? row2.allowed : []) {
145918
+ const parsed = parseEntry(entry2);
145919
+ if (parsed && !allowed.some((kept) => sameConnector(kept, parsed))) allowed.push(parsed);
145920
+ }
145921
+ const history = (Array.isArray(row2.history) ? row2.history : []).map(parseDecision).filter((decision) => decision !== null);
145922
+ return {
145923
+ revision: row2.revision,
145924
+ allowed: allowed.slice(-CONNECTOR_ALLOWANCE_LIMIT),
145925
+ history: history.slice(-CONNECTOR_ALLOWANCE_HISTORY_LIMIT)
145926
+ };
145927
+ }
145928
+ function connectorAllowanceRevision(chat) {
145929
+ return chat.connectorAllowance?.revision ?? 0;
145930
+ }
145931
+ function connectorChatAllowable(approval) {
145932
+ return Boolean(approval.explicitOnly && approval.connector?.verified);
145933
+ }
145934
+ function connectorAllowanceCovers(chat, approval) {
145935
+ if (!connectorChatAllowable(approval)) return false;
145936
+ const call = approval.connector;
145937
+ return Boolean(chat.connectorAllowance?.allowed.some((entry2) => sameConnector(entry2, call)));
145938
+ }
145939
+ function withDecision(allowance, decision, allowed) {
145940
+ return {
145941
+ revision: decision.revision,
145942
+ allowed: allowed.slice(-CONNECTOR_ALLOWANCE_LIMIT),
145943
+ history: [...allowance.history, decision].slice(-CONNECTOR_ALLOWANCE_HISTORY_LIMIT)
145944
+ };
145945
+ }
145946
+ function grantConnectorAllowance(chat, connector, approvalId, at = (/* @__PURE__ */ new Date()).toISOString()) {
145947
+ const current = chat.connectorAllowance ?? EMPTY;
145948
+ const identity4 = { provider: connector.provider, server: connector.server, app: connector.app ?? null };
145949
+ const id2 = approvalId.toLowerCase();
145950
+ const revision = current.revision + 1;
145951
+ const allowed = [...current.allowed.filter((entry2) => !sameConnector(entry2, identity4)), { ...identity4, grantedAt: at, approvalId: id2 }];
145952
+ return withDecision(current, { ...identity4, action: "grant", at, revision, approvalId: id2 }, allowed);
145953
+ }
145954
+ function revokeConnectorAllowance(chat, connector, at = (/* @__PURE__ */ new Date()).toISOString()) {
145955
+ const current = chat.connectorAllowance ?? EMPTY;
145956
+ const revision = current.revision + 1;
145957
+ if (connector) {
145958
+ const allowed = current.allowed.filter((entry2) => !sameConnector(entry2, connector));
145959
+ return withDecision(current, { ...connector, app: connector.app ?? null, action: "revoke", at, revision }, allowed);
145960
+ }
145961
+ let next = { ...current, revision };
145962
+ for (const entry2 of current.allowed) {
145963
+ next = { ...next, history: [...next.history, { provider: entry2.provider, server: entry2.server, app: entry2.app, action: "revoke", at, revision }].slice(-CONNECTOR_ALLOWANCE_HISTORY_LIMIT) };
145964
+ }
145965
+ return { ...next, allowed: [] };
145966
+ }
145967
+ function connectorLabel(connector) {
145968
+ const raw2 = (connector.app ?? connector.server).replace(/^claude[._ ]ai[_ ]/i, "");
145969
+ return raw2.replace(/[_-]+/g, " ").replace(/\b\w/g, (letter) => letter.toUpperCase()).slice(0, 80);
145970
+ }
145971
+ function connectorApprovalQuestion(call, inputs) {
145972
+ const shown2 = inputs.replace(/\s+/g, " ").trim().slice(0, 600);
145973
+ return `Allow ${connectorLabel(call)} to run ${call.tool}?${shown2 ? ` It will receive: ${shown2}.` : ""} FloLess cannot check what this connector does, so check it before you approve.`;
145974
+ }
145975
+ var UUID21, NAME2, ConnectorAllowanceError, EMPTY, OWN_CONNECTORS_OFF_ROUTING;
145976
+ var init_chat_connector_allowance = __esm({
145977
+ "chat-connector-allowance.ts"() {
145978
+ "use strict";
145979
+ init_chat_types();
145980
+ UUID21 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
145981
+ NAME2 = /^[A-Za-z0-9][A-Za-z0-9_.: -]{0,127}$/u;
145982
+ ConnectorAllowanceError = class extends Error {
145983
+ constructor(message2, code = "chat-connector-allowance-invalid") {
145984
+ super(message2);
145985
+ this.code = code;
145986
+ }
145987
+ code;
145988
+ };
145989
+ EMPTY = { revision: 0, allowed: [], history: [] };
145990
+ OWN_CONNECTORS_OFF_ROUTING = (provider3) => `The person's own ${provider3} connectors are off for this conversation. If they ask for something only one of their own connectors could do (their mail, files, calendar or another account), say that their ${provider3} connectors are off in this chat and that they can turn on "Use my ${provider3} connectors in this chat" in this chat's settings (the gear button), or connect the service in FloLess.`;
145991
+ }
145992
+ });
145993
+
145856
145994
  // chat-store.ts
145857
145995
  function assertMessageAttachmentCaps(chat, attachmentIds, imageMessage) {
145858
145996
  const types = attachmentIds.map((attachmentId) => chat.attachments.find((row2) => row2.attachmentId === attachmentId).mediaType);
@@ -145864,7 +146002,7 @@ function assertMessageAttachmentCaps(chat, attachmentIds, imageMessage) {
145864
146002
  }
145865
146003
  }
145866
146004
  function assertUuid2(value, label2) {
145867
- if (typeof value !== "string" || !UUID21.test(value)) throw new ChatStoreError(`invalid ${label2}`);
146005
+ if (typeof value !== "string" || !UUID22.test(value)) throw new ChatStoreError(`invalid ${label2}`);
145868
146006
  return value.toLowerCase();
145869
146007
  }
145870
146008
  function assertSafeDirectory2(parent, path, label2) {
@@ -145898,13 +146036,15 @@ function optionalName(value, label2, max2 = 160) {
145898
146036
  }
145899
146037
  function parseSettings(value) {
145900
146038
  const row2 = value;
145901
- if (!row2 || typeof row2 !== "object" || !["read-only", "workspace-write", "full-access"].includes(String(row2.permissionProfile))) {
146039
+ if (!row2 || typeof row2 !== "object" || !["read-only", "workspace-write", "full-access"].includes(String(row2.permissionProfile)) || row2.useOwnConnectors !== void 0 && typeof row2.useOwnConnectors !== "boolean") {
145902
146040
  throw new ChatStoreError("invalid chat settings", 409);
145903
146041
  }
145904
146042
  return {
145905
146043
  model: optionalName(row2.model, "model"),
145906
146044
  effort: optionalName(row2.effort, "effort"),
145907
- permissionProfile: row2.permissionProfile
146045
+ permissionProfile: row2.permissionProfile,
146046
+ // Stored only when on, so a conversation that never turned them on keeps its exact shape (#1907).
146047
+ ...row2.useOwnConnectors === true ? { useOwnConnectors: true } : {}
145908
146048
  };
145909
146049
  }
145910
146050
  function parseRunContext(value) {
@@ -146100,7 +146240,7 @@ function readSmallJson2(path, maxBytes) {
146100
146240
  }
146101
146241
  function parseOwner2(value) {
146102
146242
  const row2 = value;
146103
- if (!row2 || typeof row2 !== "object" || typeof row2.rootId !== "string" || !UUID21.test(row2.rootId) || !Number.isSafeInteger(row2.rootGeneration) || (row2.rootGeneration ?? 0) < 1) {
146243
+ if (!row2 || typeof row2 !== "object" || typeof row2.rootId !== "string" || !UUID22.test(row2.rootId) || !Number.isSafeInteger(row2.rootGeneration) || (row2.rootGeneration ?? 0) < 1) {
146104
146244
  throw new ChatStoreError("invalid chat owner", 409);
146105
146245
  }
146106
146246
  if (row2.kind === "project") {
@@ -146131,14 +146271,14 @@ function parseOwner2(value) {
146131
146271
  }
146132
146272
  function parseAttachment(value) {
146133
146273
  const row2 = value;
146134
- if (!row2 || typeof row2 !== "object" || typeof row2.attachmentId !== "string" || !UUID21.test(row2.attachmentId) || typeof row2.fileName !== "string" || (0, import_node_path87.basename)(row2.fileName) !== row2.fileName || typeof row2.mediaType !== "string" || !MEDIA_EXTENSIONS[row2.mediaType] || !Number.isSafeInteger(row2.bytes) || (row2.bytes ?? 0) < 1 || (row2.bytes ?? 0) > MAX_ATTACHMENT_BYTES || typeof row2.digest !== "string" || !SHA25611.test(row2.digest) || typeof row2.relativePath !== "string" || (0, import_node_path87.dirname)(row2.relativePath) !== ATTACHMENTS_DIRECTORY || typeof row2.createdAt !== "string" || !Number.isFinite(Date.parse(row2.createdAt)) || row2.turnId !== null && (typeof row2.turnId !== "string" || !UUID21.test(row2.turnId)) || row2.purpose !== void 0 && (row2.purpose !== "answer-evidence" || row2.turnId !== null)) {
146274
+ if (!row2 || typeof row2 !== "object" || typeof row2.attachmentId !== "string" || !UUID22.test(row2.attachmentId) || typeof row2.fileName !== "string" || (0, import_node_path87.basename)(row2.fileName) !== row2.fileName || typeof row2.mediaType !== "string" || !MEDIA_EXTENSIONS[row2.mediaType] || !Number.isSafeInteger(row2.bytes) || (row2.bytes ?? 0) < 1 || (row2.bytes ?? 0) > MAX_ATTACHMENT_BYTES || typeof row2.digest !== "string" || !SHA25611.test(row2.digest) || typeof row2.relativePath !== "string" || (0, import_node_path87.dirname)(row2.relativePath) !== ATTACHMENTS_DIRECTORY || typeof row2.createdAt !== "string" || !Number.isFinite(Date.parse(row2.createdAt)) || row2.turnId !== null && (typeof row2.turnId !== "string" || !UUID22.test(row2.turnId)) || row2.purpose !== void 0 && (row2.purpose !== "answer-evidence" || row2.turnId !== null)) {
146135
146275
  throw new ChatStoreError("invalid chat attachment", 409);
146136
146276
  }
146137
146277
  return row2;
146138
146278
  }
146139
146279
  function parseIntegrationBinding(value) {
146140
146280
  const row2 = value;
146141
- if (!row2 || typeof row2 !== "object" || typeof row2.integration !== "string" || !/^[a-z0-9][a-z0-9._-]{0,127}$/u.test(row2.integration) || row2.alias !== null && (typeof row2.alias !== "string" || !row2.alias || row2.alias.length > 128 || /[^\x20-\x7e]/u.test(row2.alias)) || typeof row2.agent !== "string" || !/^[a-z0-9][a-z0-9._-]{0,127}$/u.test(row2.agent) || typeof row2.command !== "string" || !/^[a-z0-9][a-z0-9._-]{0,127}$/u.test(row2.command) || row2.effect !== "read" || typeof row2.installedVersion !== "string" || !row2.installedVersion || row2.installedVersion.length > 128 || typeof row2.manifestSha256 !== "string" || !SHA25611.test(row2.manifestSha256) || typeof row2.operationSha256 !== "string" || !SHA25611.test(row2.operationSha256) || typeof row2.bindingId !== "string" || !UUID21.test(row2.bindingId) || !Number.isSafeInteger(row2.bindingRevision) || (row2.bindingRevision ?? 0) < 1 || typeof row2.credentialGeneration !== "string" || !UUID21.test(row2.credentialGeneration) || typeof row2.principalStableId !== "string" || !row2.principalStableId || Buffer.byteLength(row2.principalStableId, "utf8") > 4096 || row2.presentationLabel !== null && (typeof row2.presentationLabel !== "string" || !row2.presentationLabel.trim() || Buffer.byteLength(row2.presentationLabel, "utf8") > 4096) || typeof row2.selectedAt !== "string" || !Number.isFinite(Date.parse(row2.selectedAt))) {
146281
+ if (!row2 || typeof row2 !== "object" || typeof row2.integration !== "string" || !/^[a-z0-9][a-z0-9._-]{0,127}$/u.test(row2.integration) || row2.alias !== null && (typeof row2.alias !== "string" || !row2.alias || row2.alias.length > 128 || /[^\x20-\x7e]/u.test(row2.alias)) || typeof row2.agent !== "string" || !/^[a-z0-9][a-z0-9._-]{0,127}$/u.test(row2.agent) || typeof row2.command !== "string" || !/^[a-z0-9][a-z0-9._-]{0,127}$/u.test(row2.command) || row2.effect !== "read" || typeof row2.installedVersion !== "string" || !row2.installedVersion || row2.installedVersion.length > 128 || typeof row2.manifestSha256 !== "string" || !SHA25611.test(row2.manifestSha256) || typeof row2.operationSha256 !== "string" || !SHA25611.test(row2.operationSha256) || typeof row2.bindingId !== "string" || !UUID22.test(row2.bindingId) || !Number.isSafeInteger(row2.bindingRevision) || (row2.bindingRevision ?? 0) < 1 || typeof row2.credentialGeneration !== "string" || !UUID22.test(row2.credentialGeneration) || typeof row2.principalStableId !== "string" || !row2.principalStableId || Buffer.byteLength(row2.principalStableId, "utf8") > 4096 || row2.presentationLabel !== null && (typeof row2.presentationLabel !== "string" || !row2.presentationLabel.trim() || Buffer.byteLength(row2.presentationLabel, "utf8") > 4096) || typeof row2.selectedAt !== "string" || !Number.isFinite(Date.parse(row2.selectedAt))) {
146142
146282
  throw new ChatStoreError("invalid chat integration binding", 409, "chat-integration-binding-invalid");
146143
146283
  }
146144
146284
  return {
@@ -146183,7 +146323,7 @@ function parseTeklaAllowance(row2) {
146183
146323
  const result2 = {};
146184
146324
  if (row2.allowedForChat !== void 0) {
146185
146325
  const allowed = row2.allowedForChat;
146186
- if (!allowed || typeof allowed !== "object" || Array.isArray(allowed) || !isIsoDate(allowed.grantedAt) || typeof allowed.approvalId !== "string" || !UUID21.test(allowed.approvalId)) throw invalid8();
146326
+ if (!allowed || typeof allowed !== "object" || Array.isArray(allowed) || !isIsoDate(allowed.grantedAt) || typeof allowed.approvalId !== "string" || !UUID22.test(allowed.approvalId)) throw invalid8();
146187
146327
  if (allowed.scope === TEKLA_ALLOWANCE_SCOPE) {
146188
146328
  result2.allowedForChat = { grantedAt: allowed.grantedAt, approvalId: allowed.approvalId.toLowerCase(), scope: TEKLA_ALLOWANCE_SCOPE };
146189
146329
  }
@@ -146196,7 +146336,7 @@ function parseTeklaAllowance(row2) {
146196
146336
  if (!Array.isArray(row2.allowanceHistory) || row2.allowanceHistory.length > TEKLA_ALLOWANCE_HISTORY_LIMIT) throw invalid8();
146197
146337
  result2.allowanceHistory = row2.allowanceHistory.map((entry2) => {
146198
146338
  const item = entry2;
146199
- if (!item || typeof item !== "object" || Array.isArray(item) || item.action !== "grant" && item.action !== "revoke" || !isIsoDate(item.at) || !isRevision2(item.revision) || item.approvalId !== void 0 && (typeof item.approvalId !== "string" || !UUID21.test(item.approvalId)) || item.action === "grant" !== (item.approvalId !== void 0)) throw invalid8();
146339
+ if (!item || typeof item !== "object" || Array.isArray(item) || item.action !== "grant" && item.action !== "revoke" || !isIsoDate(item.at) || !isRevision2(item.revision) || item.approvalId !== void 0 && (typeof item.approvalId !== "string" || !UUID22.test(item.approvalId)) || item.action === "grant" !== (item.approvalId !== void 0)) throw invalid8();
146200
146340
  return {
146201
146341
  action: item.action,
146202
146342
  at: item.at,
@@ -146232,25 +146372,39 @@ async function revokeChatTeklaAllowance(owner3, chatId) {
146232
146372
  return { ...chat, teklaModelRead: next };
146233
146373
  });
146234
146374
  }
146375
+ function parseConnectorAllowanceOrThrow(value) {
146376
+ try {
146377
+ return parseConnectorAllowance(value);
146378
+ } catch {
146379
+ throw new ChatStoreError("invalid chat connector allowance", 409);
146380
+ }
146381
+ }
146382
+ async function revokeChatConnectorAllowance(owner3, chatId, connector) {
146383
+ return updateChat(owner3, chatId, (chat) => ({ ...chat, connectorAllowance: revokeConnectorAllowance(chat, connector) }));
146384
+ }
146235
146385
  function parsePendingApproval(value, owner3) {
146236
146386
  if (value === null || value === void 0) return null;
146237
146387
  const row2 = value;
146238
146388
  if (row2.explicitOnly !== void 0 && row2.explicitOnly !== true || row2.tool !== void 0 && (typeof row2.tool !== "string" || !/^[a-z][a-z0-9_]{0,127}$/u.test(row2.tool))) {
146239
146389
  throw new ChatStoreError("invalid pending chat approval", 409);
146240
146390
  }
146241
- if (typeof row2.approvalId !== "string" || !UUID21.test(row2.approvalId) || typeof row2.nativeRequestId !== "string" || !row2.nativeRequestId.trim() || row2.nativeRequestId.length > 2048 || typeof row2.turnId !== "string" || !UUID21.test(row2.turnId) || typeof row2.ownershipGeneration !== "string" || !UUID21.test(row2.ownershipGeneration) || row2.rootGeneration !== owner3.rootGeneration || typeof row2.connectionRevision !== "string" || !UUID21.test(row2.connectionRevision) || typeof row2.summary !== "string" || !row2.summary.trim() || Buffer.byteLength(row2.summary, "utf8") > 16 * 1024 || typeof row2.requestedAt !== "string" || !Number.isFinite(Date.parse(row2.requestedAt))) {
146391
+ if (row2.connector !== void 0 && (row2.explicitOnly !== true || !parseConnectorCall(row2.connector))) {
146242
146392
  throw new ChatStoreError("invalid pending chat approval", 409);
146243
146393
  }
146244
- return row2;
146394
+ if (typeof row2.approvalId !== "string" || !UUID22.test(row2.approvalId) || typeof row2.nativeRequestId !== "string" || !row2.nativeRequestId.trim() || row2.nativeRequestId.length > 2048 || typeof row2.turnId !== "string" || !UUID22.test(row2.turnId) || typeof row2.ownershipGeneration !== "string" || !UUID22.test(row2.ownershipGeneration) || row2.rootGeneration !== owner3.rootGeneration || typeof row2.connectionRevision !== "string" || !UUID22.test(row2.connectionRevision) || typeof row2.summary !== "string" || !row2.summary.trim() || Buffer.byteLength(row2.summary, "utf8") > 16 * 1024 || typeof row2.requestedAt !== "string" || !Number.isFinite(Date.parse(row2.requestedAt))) {
146395
+ throw new ChatStoreError("invalid pending chat approval", 409);
146396
+ }
146397
+ const parsed = row2;
146398
+ return row2.connector !== void 0 ? { ...parsed, connector: parseConnectorCall(row2.connector) } : parsed;
146245
146399
  }
146246
146400
  function parseChat(value, expectedId) {
146247
146401
  const row2 = value;
146248
- if (!row2 || row2.version !== 1 || typeof row2.chatId !== "string" || !UUID21.test(row2.chatId) || expectedId && row2.chatId.toLowerCase() !== expectedId.toLowerCase() || row2.provider !== "claude" && row2.provider !== "codex" || row2.nativeSessionId !== null && typeof row2.nativeSessionId !== "string" || typeof row2.cwd !== "string" || !(0, import_node_path87.isAbsolute)(row2.cwd) || typeof row2.title !== "string" || !row2.title.trim() || row2.title.length > 160 || typeof row2.createdAt !== "string" || !Number.isFinite(Date.parse(row2.createdAt)) || typeof row2.updatedAt !== "string" || !Number.isFinite(Date.parse(row2.updatedAt)) || row2.archivedAt !== null && (typeof row2.archivedAt !== "string" || !Number.isFinite(Date.parse(row2.archivedAt))) || typeof row2.connectionRevision !== "string" || !UUID21.test(row2.connectionRevision) || !Array.isArray(row2.integrationBindings) || row2.integrationBindings.length > MAX_INTEGRATION_BINDINGS || row2.linkedPredecessorChatId !== null && (typeof row2.linkedPredecessorChatId !== "string" || !UUID21.test(row2.linkedPredecessorChatId)) || typeof row2.draft !== "string" || Buffer.byteLength(row2.draft, "utf8") > MAX_DRAFT_BYTES || !Array.isArray(row2.attachments) || row2.attachments.length > MAX_ATTACHMENTS || !["idle", "starting", "running", "awaiting-approval", "completed", "failed", "interrupted", "recovery"].includes(String(row2.state)) || !Number.isSafeInteger(row2.lastEventSequence) || (row2.lastEventSequence ?? -1) < 0) {
146402
+ if (!row2 || row2.version !== 1 || typeof row2.chatId !== "string" || !UUID22.test(row2.chatId) || expectedId && row2.chatId.toLowerCase() !== expectedId.toLowerCase() || row2.provider !== "claude" && row2.provider !== "codex" || row2.nativeSessionId !== null && typeof row2.nativeSessionId !== "string" || typeof row2.cwd !== "string" || !(0, import_node_path87.isAbsolute)(row2.cwd) || typeof row2.title !== "string" || !row2.title.trim() || row2.title.length > 160 || typeof row2.createdAt !== "string" || !Number.isFinite(Date.parse(row2.createdAt)) || typeof row2.updatedAt !== "string" || !Number.isFinite(Date.parse(row2.updatedAt)) || row2.archivedAt !== null && (typeof row2.archivedAt !== "string" || !Number.isFinite(Date.parse(row2.archivedAt))) || typeof row2.connectionRevision !== "string" || !UUID22.test(row2.connectionRevision) || !Array.isArray(row2.integrationBindings) || row2.integrationBindings.length > MAX_INTEGRATION_BINDINGS || row2.linkedPredecessorChatId !== null && (typeof row2.linkedPredecessorChatId !== "string" || !UUID22.test(row2.linkedPredecessorChatId)) || typeof row2.draft !== "string" || Buffer.byteLength(row2.draft, "utf8") > MAX_DRAFT_BYTES || !Array.isArray(row2.attachments) || row2.attachments.length > MAX_ATTACHMENTS || !["idle", "starting", "running", "awaiting-approval", "completed", "failed", "interrupted", "recovery"].includes(String(row2.state)) || !Number.isSafeInteger(row2.lastEventSequence) || (row2.lastEventSequence ?? -1) < 0) {
146249
146403
  throw new ChatStoreError("invalid chat metadata", 409, "chat-record-invalid");
146250
146404
  }
146251
146405
  const owner3 = parseOwner2(row2.owner);
146252
146406
  const activeTurn = row2.activeTurn ?? null;
146253
- if (activeTurn !== null && (typeof activeTurn !== "object" || !UUID21.test(String(activeTurn.turnId)) || !UUID21.test(String(activeTurn.clientSubmissionId)) || !UUID21.test(String(activeTurn.ownershipGeneration)) || !UUID21.test(String(activeTurn.connectionRevision)) || activeTurn.rootGeneration !== owner3.rootGeneration || typeof activeTurn.modifying !== "boolean" || activeTurn.accessApprovalGranted !== void 0 && typeof activeTurn.accessApprovalGranted !== "boolean" || !["accepted", "preparing", "sending", "acknowledged", "not-sent", "cancelled", "recovery"].includes(String(activeTurn.dispatchState)))) {
146407
+ if (activeTurn !== null && (typeof activeTurn !== "object" || !UUID22.test(String(activeTurn.turnId)) || !UUID22.test(String(activeTurn.clientSubmissionId)) || !UUID22.test(String(activeTurn.ownershipGeneration)) || !UUID22.test(String(activeTurn.connectionRevision)) || activeTurn.rootGeneration !== owner3.rootGeneration || typeof activeTurn.modifying !== "boolean" || activeTurn.accessApprovalGranted !== void 0 && typeof activeTurn.accessApprovalGranted !== "boolean" || !["accepted", "preparing", "sending", "acknowledged", "not-sent", "cancelled", "recovery"].includes(String(activeTurn.dispatchState)))) {
146254
146408
  throw new ChatStoreError("invalid active chat turn", 409);
146255
146409
  }
146256
146410
  return {
@@ -146266,7 +146420,8 @@ function parseChat(value, expectedId) {
146266
146420
  attachments: row2.attachments.map(parseAttachment),
146267
146421
  activeTurn,
146268
146422
  pendingApproval: parsePendingApproval(row2.pendingApproval, owner3),
146269
- ...owner3.kind === "workspace" ? { workspaceUnits: parseWorkspaceUnits(row2.workspaceUnits) } : {}
146423
+ ...owner3.kind === "workspace" ? { workspaceUnits: parseWorkspaceUnits(row2.workspaceUnits) } : {},
146424
+ ...row2.connectorAllowance !== void 0 ? { connectorAllowance: parseConnectorAllowanceOrThrow(row2.connectorAllowance) } : {}
146270
146425
  };
146271
146426
  }
146272
146427
  function unitOrNull(value) {
@@ -146413,7 +146568,7 @@ function requestLinkPath(resolved, requestId) {
146413
146568
  }
146414
146569
  function parseRequestChatLink(value, resolved, requestId) {
146415
146570
  const row2 = value;
146416
- if (!row2 || row2.version !== 1 || row2.requestId !== requestId.toLowerCase() || typeof row2.chatId !== "string" || !UUID21.test(row2.chatId) || typeof row2.initialSubmissionId !== "string" || !UUID21.test(row2.initialSubmissionId) || row2.initialTurnId !== null && (typeof row2.initialTurnId !== "string" || !UUID21.test(row2.initialTurnId)) || !["discussion", "chat", "background"].includes(String(row2.executionOwner)) || row2.source !== "instructor" && row2.source !== "request" || typeof row2.requestEventId !== "string" || !UUID21.test(row2.requestEventId) || row2.answerAttemptId !== null && (typeof row2.answerAttemptId !== "string" || !UUID21.test(row2.answerAttemptId)) || row2.answerEventId !== null && (typeof row2.answerEventId !== "string" || !UUID21.test(row2.answerEventId)) || row2.answerState !== null && row2.answerState !== "publishing" && row2.answerState !== "published" || row2.state !== "creating" && row2.state !== "ready" || typeof row2.createdAt !== "string" || !Number.isFinite(Date.parse(row2.createdAt)) || typeof row2.updatedAt !== "string" || !Number.isFinite(Date.parse(row2.updatedAt))) {
146571
+ if (!row2 || row2.version !== 1 || row2.requestId !== requestId.toLowerCase() || typeof row2.chatId !== "string" || !UUID22.test(row2.chatId) || typeof row2.initialSubmissionId !== "string" || !UUID22.test(row2.initialSubmissionId) || row2.initialTurnId !== null && (typeof row2.initialTurnId !== "string" || !UUID22.test(row2.initialTurnId)) || !["discussion", "chat", "background"].includes(String(row2.executionOwner)) || row2.source !== "instructor" && row2.source !== "request" || typeof row2.requestEventId !== "string" || !UUID22.test(row2.requestEventId) || row2.answerAttemptId !== null && (typeof row2.answerAttemptId !== "string" || !UUID22.test(row2.answerAttemptId)) || row2.answerEventId !== null && (typeof row2.answerEventId !== "string" || !UUID22.test(row2.answerEventId)) || row2.answerState !== null && row2.answerState !== "publishing" && row2.answerState !== "published" || row2.state !== "creating" && row2.state !== "ready" || typeof row2.createdAt !== "string" || !Number.isFinite(Date.parse(row2.createdAt)) || typeof row2.updatedAt !== "string" || !Number.isFinite(Date.parse(row2.updatedAt))) {
146417
146572
  throw new ChatStoreError("request chat link is invalid", 409, "request-chat-link-invalid");
146418
146573
  }
146419
146574
  const owner3 = parseOwner2(row2.owner);
@@ -146625,7 +146780,7 @@ function listChatsNow(owner3, options2, unreadable) {
146625
146780
  let readableRecord = false;
146626
146781
  let ownerWideStaleness = null;
146627
146782
  for (const name of (0, import_node_fs88.readdirSync)(base2)) {
146628
- if (!UUID21.test(name)) continue;
146783
+ if (!UUID22.test(name)) continue;
146629
146784
  let row2;
146630
146785
  try {
146631
146786
  if (unreadable) {
@@ -147063,7 +147218,7 @@ function parseChatTeklaReadPayload(value) {
147063
147218
  if (!row2 || typeof row2 !== "object" || Array.isArray(row2)) throw invalid8();
147064
147219
  const selection = row2.operation === TEKLA_SELECTION_READ_OPERATION;
147065
147220
  const allowed = (key5) => TEKLA_READ_KEYS.has(key5) || selection && row2.status === "verified-for-selection-read" && TEKLA_SELECTION_KEYS.includes(key5);
147066
- if (Object.keys(row2).some((key5) => !allowed(key5)) || typeof row2.approvalId !== "string" || !UUID21.test(row2.approvalId) || !TEKLA_CHAT_READ_OPERATIONS.includes(row2.operation) || row2.status !== "unverified" && row2.status !== (selection ? "verified-for-selection-read" : "verified-for-model-name-read") || typeof row2.library !== "string" || !row2.library || row2.library.length > 2048 || typeof row2.hostVersion !== "string" || !/^\d{4}\.0$/u.test(row2.hostVersion) || typeof row2.checkedAt !== "string" || !Number.isFinite(Date.parse(row2.checkedAt))) {
147221
+ if (Object.keys(row2).some((key5) => !allowed(key5)) || typeof row2.approvalId !== "string" || !UUID22.test(row2.approvalId) || !TEKLA_CHAT_READ_OPERATIONS.includes(row2.operation) || row2.status !== "unverified" && row2.status !== (selection ? "verified-for-selection-read" : "verified-for-model-name-read") || typeof row2.library !== "string" || !row2.library || row2.library.length > 2048 || typeof row2.hostVersion !== "string" || !/^\d{4}\.0$/u.test(row2.hostVersion) || typeof row2.checkedAt !== "string" || !Number.isFinite(Date.parse(row2.checkedAt))) {
147067
147222
  throw invalid8();
147068
147223
  }
147069
147224
  const base2 = {
@@ -147489,7 +147644,7 @@ function reconcileChatKnowledgeRetentionNow() {
147489
147644
  }
147490
147645
  function parseEvent2(value, expectedChatId) {
147491
147646
  const row2 = value;
147492
- if (!row2 || row2.version !== 1 || typeof row2.eventId !== "string" || !UUID21.test(row2.eventId) || !Number.isSafeInteger(row2.sequence) || (row2.sequence ?? 0) < 1 || row2.chatId !== expectedChatId || typeof row2.type !== "string" || typeof row2.createdAt !== "string" || !Number.isFinite(Date.parse(row2.createdAt)) || !row2.payload || typeof row2.payload !== "object" || Array.isArray(row2.payload)) {
147647
+ if (!row2 || row2.version !== 1 || typeof row2.eventId !== "string" || !UUID22.test(row2.eventId) || !Number.isSafeInteger(row2.sequence) || (row2.sequence ?? 0) < 1 || row2.chatId !== expectedChatId || typeof row2.type !== "string" || typeof row2.createdAt !== "string" || !Number.isFinite(Date.parse(row2.createdAt)) || !row2.payload || typeof row2.payload !== "object" || Array.isArray(row2.payload)) {
147493
147648
  throw new ChatStoreError("invalid chat event", 409);
147494
147649
  }
147495
147650
  return row2;
@@ -147629,7 +147784,7 @@ async function listChatSubjectLinks(owner3, source) {
147629
147784
  const chats = /* @__PURE__ */ new Map();
147630
147785
  let partial2 = false;
147631
147786
  for (const name of (0, import_node_fs88.readdirSync)(base2)) {
147632
- if (!UUID21.test(name)) continue;
147787
+ if (!UUID22.test(name)) continue;
147633
147788
  try {
147634
147789
  const read3 = readChatRecordAt(resolved, name);
147635
147790
  if (read3.ok) chats.set(read3.chat.chatId, read3.chat);
@@ -147685,7 +147840,7 @@ function turnPath(resolved, chatId, turnId) {
147685
147840
  }
147686
147841
  function parseTurn(value, chatId) {
147687
147842
  const row2 = value;
147688
- if (!row2 || row2.version !== 1 || row2.chatId !== chatId || typeof row2.turnId !== "string" || !UUID21.test(row2.turnId) || typeof row2.clientSubmissionId !== "string" || !UUID21.test(row2.clientSubmissionId) || typeof row2.text !== "string" || Buffer.byteLength(row2.text, "utf8") > MAX_TEXT_BYTES || row2.displayText !== void 0 && (typeof row2.displayText !== "string" || Buffer.byteLength(row2.displayText, "utf8") > MAX_TEXT_BYTES) || row2.retryOfSubmissionId !== void 0 && !UUID21.test(row2.retryOfSubmissionId) || row2.source !== void 0 && row2.source !== "filter-save" || row2.receiptAttempt !== void 0 && (row2.source !== "filter-save" || !Number.isSafeInteger(row2.receiptAttempt) || row2.receiptAttempt < 0) || row2.receiptOutcome !== void 0 && (row2.source !== "filter-save" || !row2.receiptOutcome || typeof row2.receiptOutcome !== "object" || Array.isArray(row2.receiptOutcome) || row2.receiptOutcome.source !== "filter-save" || !["retryable-unsent", "refused-unsent", "completed", "failed", "interrupted"].includes(String(row2.receiptOutcome.value)) || typeof row2.receiptOutcome.reason !== "string" || !/^[a-z0-9-]{1,100}$/.test(row2.receiptOutcome.reason) || typeof row2.receiptOutcome.writtenAt !== "string" || !Number.isFinite(Date.parse(row2.receiptOutcome.writtenAt))) || !Array.isArray(row2.attachmentIds) || row2.attachmentIds.some((id2) => typeof id2 !== "string" || !UUID21.test(id2)) || row2.permissionProfile !== void 0 && !["read-only", "workspace-write", "full-access"].includes(String(row2.permissionProfile)) || typeof row2.modifying !== "boolean" || typeof row2.ownershipGeneration !== "string" || !UUID21.test(row2.ownershipGeneration) || typeof row2.connectionRevision !== "string" || !UUID21.test(row2.connectionRevision) || !Number.isSafeInteger(row2.rootGeneration) || (row2.rootGeneration ?? 0) < 1 || !["accepted", "preparing", "sending", "acknowledged", "not-sent", "cancelled", "recovery"].includes(String(row2.dispatchState)) || row2.providerTurnId !== null && typeof row2.providerTurnId !== "string" || typeof row2.acceptedEventId !== "string" || !UUID21.test(row2.acceptedEventId) || row2.acceptedEventState !== "pending" && row2.acceptedEventState !== "published" || typeof row2.acceptedAt !== "string" || !Number.isFinite(Date.parse(row2.acceptedAt)) || typeof row2.updatedAt !== "string" || !Number.isFinite(Date.parse(row2.updatedAt))) {
147843
+ if (!row2 || row2.version !== 1 || row2.chatId !== chatId || typeof row2.turnId !== "string" || !UUID22.test(row2.turnId) || typeof row2.clientSubmissionId !== "string" || !UUID22.test(row2.clientSubmissionId) || typeof row2.text !== "string" || Buffer.byteLength(row2.text, "utf8") > MAX_TEXT_BYTES || row2.displayText !== void 0 && (typeof row2.displayText !== "string" || Buffer.byteLength(row2.displayText, "utf8") > MAX_TEXT_BYTES) || row2.retryOfSubmissionId !== void 0 && !UUID22.test(row2.retryOfSubmissionId) || row2.source !== void 0 && row2.source !== "filter-save" || row2.receiptAttempt !== void 0 && (row2.source !== "filter-save" || !Number.isSafeInteger(row2.receiptAttempt) || row2.receiptAttempt < 0) || row2.receiptOutcome !== void 0 && (row2.source !== "filter-save" || !row2.receiptOutcome || typeof row2.receiptOutcome !== "object" || Array.isArray(row2.receiptOutcome) || row2.receiptOutcome.source !== "filter-save" || !["retryable-unsent", "refused-unsent", "completed", "failed", "interrupted"].includes(String(row2.receiptOutcome.value)) || typeof row2.receiptOutcome.reason !== "string" || !/^[a-z0-9-]{1,100}$/.test(row2.receiptOutcome.reason) || typeof row2.receiptOutcome.writtenAt !== "string" || !Number.isFinite(Date.parse(row2.receiptOutcome.writtenAt))) || !Array.isArray(row2.attachmentIds) || row2.attachmentIds.some((id2) => typeof id2 !== "string" || !UUID22.test(id2)) || row2.permissionProfile !== void 0 && !["read-only", "workspace-write", "full-access"].includes(String(row2.permissionProfile)) || typeof row2.modifying !== "boolean" || typeof row2.ownershipGeneration !== "string" || !UUID22.test(row2.ownershipGeneration) || typeof row2.connectionRevision !== "string" || !UUID22.test(row2.connectionRevision) || !Number.isSafeInteger(row2.rootGeneration) || (row2.rootGeneration ?? 0) < 1 || !["accepted", "preparing", "sending", "acknowledged", "not-sent", "cancelled", "recovery"].includes(String(row2.dispatchState)) || row2.providerTurnId !== null && typeof row2.providerTurnId !== "string" || typeof row2.acceptedEventId !== "string" || !UUID22.test(row2.acceptedEventId) || row2.acceptedEventState !== "pending" && row2.acceptedEventState !== "published" || typeof row2.acceptedAt !== "string" || !Number.isFinite(Date.parse(row2.acceptedAt)) || typeof row2.updatedAt !== "string" || !Number.isFinite(Date.parse(row2.updatedAt))) {
147689
147844
  throw new ChatStoreError("invalid chat turn intent", 409);
147690
147845
  }
147691
147846
  if (row2.subjects !== void 0) {
@@ -147711,7 +147866,7 @@ function findChatTurnBySubmission(owner3, chatId, submissionId) {
147711
147866
  const chat = readChatAt(resolved, assertUuid2(chatId, "chat identity"));
147712
147867
  const wanted = assertUuid2(submissionId, "submission identity");
147713
147868
  const dir = (0, import_node_path87.join)(chatDirectory(resolved, chat.chatId), TURNS_DIRECTORY);
147714
- const matches = (0, import_node_fs88.readdirSync)(dir).filter((name) => UUID21.test(name.replace(/\.json$/i, ""))).map((name) => parseTurn(readSmallJson2((0, import_node_path87.join)(dir, name), MAX_TURN_BYTES), chat.chatId)).filter((turn) => turn.clientSubmissionId === wanted);
147869
+ const matches = (0, import_node_fs88.readdirSync)(dir).filter((name) => UUID22.test(name.replace(/\.json$/i, ""))).map((name) => parseTurn(readSmallJson2((0, import_node_path87.join)(dir, name), MAX_TURN_BYTES), chat.chatId)).filter((turn) => turn.clientSubmissionId === wanted);
147715
147870
  if (matches.length > 1) throw new ChatStoreError("submission identity is duplicated", 409);
147716
147871
  return matches[0] ?? null;
147717
147872
  }
@@ -147720,7 +147875,7 @@ function followupPath(resolved, chatId, submissionId) {
147720
147875
  }
147721
147876
  function parseFollowup(value, chatId) {
147722
147877
  const row2 = value;
147723
- if (!row2 || row2.version !== 1 || row2.chatId !== chatId || !UUID21.test(String(row2.parentTurnId)) || !UUID21.test(String(row2.clientSubmissionId)) || !UUID21.test(String(row2.eventId)) || !Number.isSafeInteger(row2.sequence) || (row2.sequence ?? 0) < 1 || typeof row2.text !== "string" || typeof row2.displayText !== "string" || row2.retryOfSubmissionId !== void 0 && !UUID21.test(row2.retryOfSubmissionId) || !Array.isArray(row2.attachmentIds) || row2.attachmentIds.some((id2) => !UUID21.test(id2)) || row2.modifying !== void 0 && typeof row2.modifying !== "boolean" || row2.permissionProfile !== void 0 && !["read-only", "workspace-write", "full-access"].includes(row2.permissionProfile) || row2.hostResource !== void 0 && row2.hostResource !== null && (typeof row2.hostResource !== "object" || typeof row2.hostResource.instanceId !== "string") || !["admitting", "pending", "sending", "accepted", "not-sent", "unknown", "queued-next", "dismissed"].includes(String(row2.deliveryState)) || row2.deliveryFailure !== void 0 && (typeof row2.deliveryFailure.reason !== "string" || row2.deliveryFailure.reason.length > 500 || typeof row2.deliveryFailure.retryable !== "boolean") || row2.providerMessageId !== null && typeof row2.providerMessageId !== "string" || typeof row2.createdAt !== "string" || typeof row2.updatedAt !== "string") {
147878
+ if (!row2 || row2.version !== 1 || row2.chatId !== chatId || !UUID22.test(String(row2.parentTurnId)) || !UUID22.test(String(row2.clientSubmissionId)) || !UUID22.test(String(row2.eventId)) || !Number.isSafeInteger(row2.sequence) || (row2.sequence ?? 0) < 1 || typeof row2.text !== "string" || typeof row2.displayText !== "string" || row2.retryOfSubmissionId !== void 0 && !UUID22.test(row2.retryOfSubmissionId) || !Array.isArray(row2.attachmentIds) || row2.attachmentIds.some((id2) => !UUID22.test(id2)) || row2.modifying !== void 0 && typeof row2.modifying !== "boolean" || row2.permissionProfile !== void 0 && !["read-only", "workspace-write", "full-access"].includes(row2.permissionProfile) || row2.hostResource !== void 0 && row2.hostResource !== null && (typeof row2.hostResource !== "object" || typeof row2.hostResource.instanceId !== "string") || !["admitting", "pending", "sending", "accepted", "not-sent", "unknown", "queued-next", "dismissed"].includes(String(row2.deliveryState)) || row2.deliveryFailure !== void 0 && (typeof row2.deliveryFailure.reason !== "string" || row2.deliveryFailure.reason.length > 500 || typeof row2.deliveryFailure.retryable !== "boolean") || row2.providerMessageId !== null && typeof row2.providerMessageId !== "string" || typeof row2.createdAt !== "string" || typeof row2.updatedAt !== "string") {
147724
147879
  throw new ChatStoreError("invalid chat follow-up", 409);
147725
147880
  }
147726
147881
  return row2;
@@ -147740,7 +147895,7 @@ function listChatFollowups(owner3, chatId) {
147740
147895
  if (!(0, import_node_fs88.existsSync)(dir)) return [];
147741
147896
  assertSafeDirectory2(chatDirectory(resolved, chat.chatId), dir, "follow-up journal");
147742
147897
  const rows2 = [];
147743
- for (const name of (0, import_node_fs88.readdirSync)(dir).filter((name2) => UUID21.test(name2.replace(/\.json$/i, "")))) {
147898
+ for (const name of (0, import_node_fs88.readdirSync)(dir).filter((name2) => UUID22.test(name2.replace(/\.json$/i, "")))) {
147744
147899
  try {
147745
147900
  rows2.push(parseFollowup(readSmallJson2((0, import_node_path87.join)(dir, name), MAX_FOLLOWUP_BYTES), chat.chatId));
147746
147901
  } catch (error62) {
@@ -147759,7 +147914,7 @@ function earlierChatFollowupState(resolved, chatId) {
147759
147914
  const waiting = ["pending", "queued-next", "admitting", "sending", "unknown"];
147760
147915
  if ((0, import_node_fs88.existsSync)(dir)) {
147761
147916
  assertSafeDirectory2(chatDirectory(resolved, chatId), dir, "follow-up journal");
147762
- for (const name of (0, import_node_fs88.readdirSync)(dir).filter((name2) => UUID21.test(name2.replace(/\.json$/i, "")))) {
147917
+ for (const name of (0, import_node_fs88.readdirSync)(dir).filter((name2) => UUID22.test(name2.replace(/\.json$/i, "")))) {
147763
147918
  try {
147764
147919
  const row2 = parseFollowup(readSmallJson2((0, import_node_path87.join)(dir, name), MAX_FOLLOWUP_BYTES), chatId);
147765
147920
  readable.add(row2.clientSubmissionId);
@@ -148450,7 +148605,7 @@ async function updateChatTurnIntent(owner3, chatId, turnId, mutate) {
148450
148605
  return saved;
148451
148606
  });
148452
148607
  }
148453
- var import_node_crypto72, import_node_fs88, import_node_path87, UUID21, REQUEST_UUID, SHA25611, CHAT_FILE, CHAT_DIRECTORY, WORKSPACE_WORK_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, UNITS, UNREADABLE_CHAT_MESSAGE, reportedUnreadable, TEKLA_READ_KEYS, TEKLA_SELECTION_KEYS, TEKLA_PART_KEYS, TEKLA_PART_TEXT_LIMIT, TEKLA_READ_PAYLOAD_BUDGET, isCount4, isWeight2, MAX_SUBJECT_LINK_CALLS_PER_TURN, FILTER_SNAPSHOTS_DIRECTORY, MAX_FILTER_SNAPSHOT_BYTES, FILTER_SNAPSHOT_FILE, FILTER_PROPOSALS_DIRECTORY, MAX_FILTER_PROPOSAL_BYTES, startupOwnerNotes, subjectIndexWarnings, isMissing, PROMOTABLE_FOLLOWUP_STATES, CHAT_STORE_LIMITS;
148608
+ var import_node_crypto72, import_node_fs88, import_node_path87, UUID22, REQUEST_UUID, SHA25611, CHAT_FILE, CHAT_DIRECTORY, WORKSPACE_WORK_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, UNITS, UNREADABLE_CHAT_MESSAGE, reportedUnreadable, TEKLA_READ_KEYS, TEKLA_SELECTION_KEYS, TEKLA_PART_KEYS, TEKLA_PART_TEXT_LIMIT, TEKLA_READ_PAYLOAD_BUDGET, isCount4, isWeight2, MAX_SUBJECT_LINK_CALLS_PER_TURN, FILTER_SNAPSHOTS_DIRECTORY, MAX_FILTER_SNAPSHOT_BYTES, FILTER_SNAPSHOT_FILE, FILTER_PROPOSALS_DIRECTORY, MAX_FILTER_PROPOSAL_BYTES, startupOwnerNotes, subjectIndexWarnings, isMissing, PROMOTABLE_FOLLOWUP_STATES, CHAT_STORE_LIMITS;
148454
148609
  var init_chat_store = __esm({
148455
148610
  "chat-store.ts"() {
148456
148611
  "use strict";
@@ -148468,11 +148623,12 @@ var init_chat_store = __esm({
148468
148623
  init_projects_store();
148469
148624
  init_project_directory();
148470
148625
  init_workspace_root_store();
148626
+ init_chat_connector_allowance();
148471
148627
  init_workspace_mutation_registry();
148472
148628
  init_workflow_ownership_store();
148473
148629
  init_chat_types();
148474
148630
  init_path_identity();
148475
- UUID21 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
148631
+ UUID22 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
148476
148632
  REQUEST_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
148477
148633
  SHA25611 = /^[0-9a-f]{64}$/;
148478
148634
  CHAT_FILE = "chat.json";
@@ -170778,6 +170934,12 @@ var init_chat_workspace_context = __esm({
170778
170934
  function teklaAllowanceChanged() {
170779
170935
  return new ChatCoordinatorError(TEKLA_ALLOWANCE_CHANGED, 409, "tekla-allowance-changed");
170780
170936
  }
170937
+ function connectorAllowanceChanged() {
170938
+ return new ChatCoordinatorError("The connectors allowed for this chat changed. Choose again.", 409, "connector-allowance-changed");
170939
+ }
170940
+ function chatAllowanceCovers(chat, approval) {
170941
+ return teklaChatAllowanceCovers(chat, approval) || connectorAllowanceCovers(chat, approval);
170942
+ }
170781
170943
  function protectedHome2() {
170782
170944
  const path = (0, import_node_path89.resolve)(process.env.FLOLESS_HOME ?? (0, import_node_path89.join)((0, import_node_os49.homedir)(), ".floless"));
170783
170945
  if (!(0, import_node_path89.isAbsolute)(path) || path === (0, import_node_path89.parse)(path).root) throw new ChatCoordinatorError("FloLess home is unsafe", 500);
@@ -170811,8 +170973,8 @@ function sessionBindingKey(provider3, nativeSessionId) {
170811
170973
  return (0, import_node_crypto79.createHash)("sha256").update(`${provider3}\0${nativeSessionId}`).digest("hex");
170812
170974
  }
170813
170975
  function submissionAdmissionKey(chatId, submissionId) {
170814
- if (!UUID22.test(chatId)) throw new ChatCoordinatorError("invalid chat identity", 400);
170815
- if (!UUID22.test(submissionId)) throw new ChatCoordinatorError("invalid submission identity", 400);
170976
+ if (!UUID23.test(chatId)) throw new ChatCoordinatorError("invalid chat identity", 400);
170977
+ if (!UUID23.test(submissionId)) throw new ChatCoordinatorError("invalid submission identity", 400);
170816
170978
  return `chat-submit-${(0, import_node_crypto79.createHash)("sha256").update(`${chatId.toLowerCase()}\0${submissionId.toLowerCase()}`).digest("hex")}`;
170817
170979
  }
170818
170980
  function turnFinalizationKey(generation) {
@@ -170826,7 +170988,7 @@ function readSessionBindings() {
170826
170988
  const result2 = {};
170827
170989
  for (const [key5, value] of Object.entries(raw2)) {
170828
170990
  const row2 = value;
170829
- if (!/^[0-9a-f]{64}$/.test(key5) || !row2 || row2.provider !== "claude" && row2.provider !== "codex" || typeof row2.nativeSessionId !== "string" || !row2.nativeSessionId || typeof row2.chatId !== "string" || !UUID22.test(row2.chatId) || typeof row2.ownerKey !== "string" || !row2.ownerKey || typeof row2.boundAt !== "string" || !Number.isFinite(Date.parse(row2.boundAt)) || sessionBindingKey(row2.provider, row2.nativeSessionId) !== key5) {
170991
+ if (!/^[0-9a-f]{64}$/.test(key5) || !row2 || row2.provider !== "claude" && row2.provider !== "codex" || typeof row2.nativeSessionId !== "string" || !row2.nativeSessionId || typeof row2.chatId !== "string" || !UUID23.test(row2.chatId) || typeof row2.ownerKey !== "string" || !row2.ownerKey || typeof row2.boundAt !== "string" || !Number.isFinite(Date.parse(row2.boundAt)) || sessionBindingKey(row2.provider, row2.nativeSessionId) !== key5) {
170830
170992
  throw new ChatCoordinatorError("chat session bindings are invalid", 409, "chat-session-bindings-corrupt");
170831
170993
  }
170832
170994
  result2[key5] = row2;
@@ -170854,7 +171016,7 @@ function bindSession(record7, nativeSessionId) {
170854
171016
  }
170855
171017
  }
170856
171018
  function ownerPath3(generation) {
170857
- if (!UUID22.test(generation)) throw new ChatCoordinatorError("invalid chat ownership generation", 400);
171019
+ if (!UUID23.test(generation)) throw new ChatCoordinatorError("invalid chat ownership generation", 400);
170858
171020
  return (0, import_node_path89.join)(ownersDirectory(), `${OWNER_PREFIX2}${generation}${OWNER_SUFFIX2}`);
170859
171021
  }
170860
171022
  function writeExclusive3(path, value) {
@@ -170882,14 +171044,14 @@ function ownerKey(owner3) {
170882
171044
  }
170883
171045
  function validOwner(value) {
170884
171046
  const owner3 = value;
170885
- if (!owner3 || typeof owner3 !== "object" || typeof owner3.rootId !== "string" || !UUID22.test(owner3.rootId) || !Number.isSafeInteger(owner3.rootGeneration) || (owner3.rootGeneration ?? 0) < 1) return false;
171047
+ if (!owner3 || typeof owner3 !== "object" || typeof owner3.rootId !== "string" || !UUID23.test(owner3.rootId) || !Number.isSafeInteger(owner3.rootGeneration) || (owner3.rootGeneration ?? 0) < 1) return false;
170886
171048
  if (owner3.kind === "project") {
170887
171049
  const row2 = owner3;
170888
- return typeof row2.projectId === "string" && row2.projectId.length > 0 && typeof row2.projectUuid === "string" && UUID22.test(row2.projectUuid);
171050
+ return typeof row2.projectId === "string" && row2.projectId.length > 0 && typeof row2.projectUuid === "string" && UUID23.test(row2.projectUuid);
170889
171051
  }
170890
171052
  if (owner3.kind === "workflow") {
170891
171053
  const row2 = owner3;
170892
- return typeof row2.workflowId === "string" && UUID22.test(row2.workflowId) && (row2.projectId === null || typeof row2.projectId === "string") && (row2.projectUuid === null || typeof row2.projectUuid === "string" && UUID22.test(row2.projectUuid)) && row2.projectId === null === (row2.projectUuid === null);
171054
+ return typeof row2.workflowId === "string" && UUID23.test(row2.workflowId) && (row2.projectId === null || typeof row2.projectId === "string") && (row2.projectUuid === null || typeof row2.projectUuid === "string" && UUID23.test(row2.projectUuid)) && row2.projectId === null === (row2.projectUuid === null);
170893
171055
  }
170894
171056
  return owner3.kind === "workspace";
170895
171057
  }
@@ -170906,7 +171068,7 @@ function parseHostResource(value) {
170906
171068
  }
170907
171069
  function parseOwnership2(value) {
170908
171070
  const row2 = value;
170909
- if (!row2 || row2.version !== VERSION3 || typeof row2.ownershipGeneration !== "string" || !UUID22.test(row2.ownershipGeneration) || typeof row2.chatId !== "string" || !UUID22.test(row2.chatId) || typeof row2.turnId !== "string" || !UUID22.test(row2.turnId) || typeof row2.ownerKey !== "string" || !validOwner(row2.owner) || row2.provider !== "claude" && row2.provider !== "codex" || row2.nativeSessionId !== null && typeof row2.nativeSessionId !== "string" || typeof row2.connectionRevision !== "string" || !UUID22.test(row2.connectionRevision) || !Number.isSafeInteger(row2.rootGeneration) || (row2.rootGeneration ?? 0) < 1 || typeof row2.modifying !== "boolean" || row2.hostKey !== null && typeof row2.hostKey !== "string" || !["admitting", "active", "recovery"].includes(String(row2.phase)) || !row2.workspaceMutationHandle || typeof row2.workspaceMutationHandle !== "object" || !UUID22.test(String(row2.workspaceMutationHandle.operationId)) || !UUID22.test(String(row2.workspaceMutationHandle.operationGeneration)) || typeof row2.createdAt !== "string" || !Number.isFinite(Date.parse(row2.createdAt)) || typeof row2.updatedAt !== "string" || !Number.isFinite(Date.parse(row2.updatedAt))) {
171071
+ if (!row2 || row2.version !== VERSION3 || typeof row2.ownershipGeneration !== "string" || !UUID23.test(row2.ownershipGeneration) || typeof row2.chatId !== "string" || !UUID23.test(row2.chatId) || typeof row2.turnId !== "string" || !UUID23.test(row2.turnId) || typeof row2.ownerKey !== "string" || !validOwner(row2.owner) || row2.provider !== "claude" && row2.provider !== "codex" || row2.nativeSessionId !== null && typeof row2.nativeSessionId !== "string" || typeof row2.connectionRevision !== "string" || !UUID23.test(row2.connectionRevision) || !Number.isSafeInteger(row2.rootGeneration) || (row2.rootGeneration ?? 0) < 1 || typeof row2.modifying !== "boolean" || row2.hostKey !== null && typeof row2.hostKey !== "string" || !["admitting", "active", "recovery"].includes(String(row2.phase)) || !row2.workspaceMutationHandle || typeof row2.workspaceMutationHandle !== "object" || !UUID23.test(String(row2.workspaceMutationHandle.operationId)) || !UUID23.test(String(row2.workspaceMutationHandle.operationGeneration)) || typeof row2.createdAt !== "string" || !Number.isFinite(Date.parse(row2.createdAt)) || typeof row2.updatedAt !== "string" || !Number.isFinite(Date.parse(row2.updatedAt))) {
170910
171072
  throw new ChatCoordinatorError("chat ownership record is invalid", 409, "chat-ownership-corrupt");
170911
171073
  }
170912
171074
  if (row2.ownerKey !== ownerKey(row2.owner) || row2.rootGeneration !== row2.owner.rootGeneration) {
@@ -171137,7 +171299,7 @@ async function finalizeCancelledTurn(owner3, chatId, turn, reason, append = appe
171137
171299
  });
171138
171300
  await releaseOwnershipIfPresent(turn.ownershipGeneration);
171139
171301
  }
171140
- async function finalizeNotSentTurn(owner3, chatId, turn, message2, append = appendChatEvent) {
171302
+ async function finalizeNotSentTurn(owner3, chatId, turn, message2, append = appendChatEvent, options2 = {}) {
171141
171303
  await withLifecycleLock("internal-export", turnFinalizationKey(turn.ownershipGeneration), async () => {
171142
171304
  const currentTurn = readChatTurnIntent(owner3, chatId, turn.turnId);
171143
171305
  if (currentTurn.ownershipGeneration !== turn.ownershipGeneration || currentTurn.dispatchState !== "not-sent") {
@@ -171154,7 +171316,7 @@ async function finalizeNotSentTurn(owner3, chatId, turn, message2, append = appe
171154
171316
  turnId: currentTurn.turnId,
171155
171317
  clientSubmissionId: currentTurn.clientSubmissionId,
171156
171318
  type: "error",
171157
- payload: { message: message2, outcome: "not-sent" }
171319
+ payload: { message: message2, outcome: "not-sent", ...options2.plain ? { plain: true } : {} }
171158
171320
  });
171159
171321
  }
171160
171322
  await releaseOwnershipIfPresent(currentTurn.ownershipGeneration);
@@ -171319,7 +171481,7 @@ function assertNoActiveChatForWorkflow(workflowId) {
171319
171481
  throw new ChatCoordinatorError("Stop or reconcile the active AI Chat before archiving this workflow", 409, "chat-workflow-busy");
171320
171482
  }
171321
171483
  }
171322
- var import_node_crypto79, import_node_async_hooks5, import_node_fs90, import_node_os49, import_node_path89, VERSION3, UUID22, MAX_OWNER_BYTES, MAX_SESSION_BINDINGS_BYTES, OWNER_PREFIX2, OWNER_SUFFIX2, SESSIONS_FILE, ChatCoordinatorError, TEKLA_ALLOWANCE_CHANGED, ProviderNotSentError, STREAM_EVENT_BATCH_MS, ChatStreamEventBatcher, ChatCoordinator;
171484
+ var import_node_crypto79, import_node_async_hooks5, import_node_fs90, import_node_os49, import_node_path89, VERSION3, UUID23, MAX_OWNER_BYTES, MAX_SESSION_BINDINGS_BYTES, OWNER_PREFIX2, OWNER_SUFFIX2, SESSIONS_FILE, ChatCoordinatorError, TEKLA_ALLOWANCE_CHANGED, ProviderNotSentError, STREAM_EVENT_BATCH_MS, ChatStreamEventBatcher, ChatCoordinator;
171323
171485
  var init_chat_coordinator = __esm({
171324
171486
  "chat-coordinator.ts"() {
171325
171487
  "use strict";
@@ -171337,11 +171499,12 @@ var init_chat_coordinator = __esm({
171337
171499
  init_workspace_mutation_registry();
171338
171500
  init_chat_store();
171339
171501
  init_chat_integration_tools();
171502
+ init_chat_connector_allowance();
171340
171503
  init_path_identity();
171341
171504
  init_chat_display_units();
171342
171505
  init_chat_workspace_context();
171343
171506
  VERSION3 = 1;
171344
- UUID22 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
171507
+ UUID23 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
171345
171508
  MAX_OWNER_BYTES = 128 * 1024;
171346
171509
  MAX_SESSION_BINDINGS_BYTES = 4 * 1024 * 1024;
171347
171510
  OWNER_PREFIX2 = "turn-";
@@ -171359,6 +171522,7 @@ var init_chat_coordinator = __esm({
171359
171522
  };
171360
171523
  TEKLA_ALLOWANCE_CHANGED = "The Tekla read permission for this chat changed. Choose again.";
171361
171524
  ProviderNotSentError = class extends Error {
171525
+ /** `plain`: the message is already written for the person (what happened, why, what to do), so it is shown as is. */
171362
171526
  constructor(message2, code, options2) {
171363
171527
  super(message2, options2);
171364
171528
  this.code = code;
@@ -172354,12 +172518,14 @@ var init_chat_coordinator = __esm({
172354
172518
  );
172355
172519
  turn = rollback.turn;
172356
172520
  if (!rollback.transitioned) return turn;
172521
+ const plain4 = error62 instanceof ProviderNotSentError && error62.code === "plain";
172357
172522
  await finalizeNotSentTurn(
172358
172523
  owner3,
172359
172524
  chatId,
172360
172525
  turn,
172361
172526
  error62 instanceof Error ? error62.message : String(error62),
172362
- (eventOwner, eventChatId, event) => this.appendEvent(eventOwner, eventChatId, event)
172527
+ (eventOwner, eventChatId, event) => this.appendEvent(eventOwner, eventChatId, event),
172528
+ { plain: plain4 }
172363
172529
  );
172364
172530
  await this.retireStoppedFollowups(
172365
172531
  owner3,
@@ -172371,6 +172537,7 @@ var init_chat_coordinator = __esm({
172371
172537
  console.warn("[chat] a turn was not sent because an attachment is unavailable:", error62.cause ?? error62);
172372
172538
  throw new ChatCoordinatorError("an attached file is unavailable", 409, "chat-attachment-unavailable");
172373
172539
  }
172540
+ if (plain4) throw new ChatCoordinatorError(error62.message, 409, "chat-send-refused-plain");
172374
172541
  throw new ChatCoordinatorError("provider refused the turn before it was sent", 409, "chat-send-refused");
172375
172542
  }
172376
172543
  const sendClaim = await transitionDispatchState(
@@ -172455,7 +172622,8 @@ var init_chat_coordinator = __esm({
172455
172622
  chatId,
172456
172623
  rollback.turn,
172457
172624
  error62.message,
172458
- (eventOwner, eventChatId, event) => this.appendEvent(eventOwner, eventChatId, event)
172625
+ (eventOwner, eventChatId, event) => this.appendEvent(eventOwner, eventChatId, event),
172626
+ { plain: error62.code === "plain" }
172459
172627
  );
172460
172628
  await this.retireStoppedFollowups(
172461
172629
  owner3,
@@ -172518,6 +172686,12 @@ var init_chat_coordinator = __esm({
172518
172686
  ...input2.explicitOnly === true ? { explicitOnly: true } : {},
172519
172687
  ...typeof input2.tool === "string" && /^[a-z][a-z0-9_]{0,127}$/u.test(input2.tool) ? { tool: input2.tool } : {}
172520
172688
  };
172689
+ const connector = input2.connector ? parseConnectorCall(input2.connector) : null;
172690
+ if (input2.connector && !connector) throw new ChatCoordinatorError("approval request is incomplete or too large", 400);
172691
+ if (connector) {
172692
+ approval.explicitOnly = true;
172693
+ approval.connector = connector;
172694
+ }
172521
172695
  return new Promise((resolve57, reject3) => {
172522
172696
  const aborted2 = () => {
172523
172697
  void this.pumpApprovals(owner3, chatId, turn, scope2);
@@ -172561,7 +172735,7 @@ var init_chat_coordinator = __esm({
172561
172735
  entry2.cleanup();
172562
172736
  entry2.resolve(entry2.approval);
172563
172737
  void sent.completion.catch(() => this.recoverApprovalFailure(owner3, chatId, turn, scope2));
172564
- } else if (teklaChatAllowanceCovers(chat, entry2.approval)) {
172738
+ } else if (chatAllowanceCovers(chat, entry2.approval)) {
172565
172739
  const sent = await this.deliverApproval(owner3, chatId, turn, scope2, entry2, "allow", "chat");
172566
172740
  if (!sent) continue;
172567
172741
  scope2.queue.shift();
@@ -172579,7 +172753,8 @@ var init_chat_coordinator = __esm({
172579
172753
  approvalId: entry2.approval.approvalId,
172580
172754
  summary: entry2.approval.summary,
172581
172755
  ...entry2.approval.explicitOnly ? { explicitOnly: true } : {},
172582
- ...entry2.approval.tool ? { tool: entry2.approval.tool } : {}
172756
+ ...entry2.approval.tool ? { tool: entry2.approval.tool } : {},
172757
+ ...entry2.approval.connector ? { connector: entry2.approval.connector } : {}
172583
172758
  }
172584
172759
  });
172585
172760
  }
@@ -172614,8 +172789,15 @@ var init_chat_coordinator = __esm({
172614
172789
  await updateChat(owner3, chatId, (current2) => {
172615
172790
  validateOwnership(current2, turn);
172616
172791
  if (scope2.retired) throw new ChatCoordinatorError("approval is no longer actionable");
172792
+ if (automatic === "chat" && !chatAllowanceCovers(current2, entry2.approval)) return current2;
172617
172793
  let teklaModelRead = current2.teklaModelRead;
172618
- if (grant) {
172794
+ let connectorAllowance = current2.connectorAllowance;
172795
+ if (grant && entry2.approval.connector) {
172796
+ if (connectorAllowanceRevision(current2) !== grant.allowanceRevision || !connectorChatAllowable(entry2.approval)) {
172797
+ throw connectorAllowanceChanged();
172798
+ }
172799
+ connectorAllowance = grantConnectorAllowance(current2, entry2.approval.connector, entry2.approval.approvalId);
172800
+ } else if (grant) {
172619
172801
  if (!teklaModelRead || teklaAllowanceRevision(teklaModelRead) !== grant.allowanceRevision || !teklaChatAllowable(current2, entry2.approval)) throw teklaAllowanceChanged();
172620
172802
  teklaModelRead = grantTeklaAllowance(teklaModelRead, entry2.approval.approvalId);
172621
172803
  }
@@ -172624,12 +172806,13 @@ var init_chat_coordinator = __esm({
172624
172806
  state: "running",
172625
172807
  pendingApproval: null,
172626
172808
  teklaModelRead,
172809
+ ...connectorAllowance ? { connectorAllowance } : {},
172627
172810
  activeTurn: { ...current2.activeTurn, accessApprovalGranted: scope2.grant }
172628
172811
  };
172629
172812
  });
172630
172813
  const current = readChat(owner3, chatId);
172631
172814
  const ownership = validateOwnership(current, turn);
172632
- if (scope2.retired || ownership.phase !== "active" || entry2.signal?.aborted || automatic === "request" && (!scope2.grant || entry2.approval.explicitOnly) || automatic === "chat" && !teklaChatAllowanceCovers(current, entry2.approval)) return null;
172815
+ if (scope2.retired || ownership.phase !== "active" || entry2.signal?.aborted || automatic === "request" && (!scope2.grant || entry2.approval.explicitOnly) || automatic === "chat" && !chatAllowanceCovers(current, entry2.approval)) return null;
172633
172816
  const delivery = this.transport.approve({ chat: current, approval: entry2.approval, decision });
172634
172817
  const audit = this.appendEvent(owner3, chatId, {
172635
172818
  turnId: turn.turnId,
@@ -172639,7 +172822,8 @@ var init_chat_coordinator = __esm({
172639
172822
  approvalId: entry2.approval.approvalId,
172640
172823
  decision,
172641
172824
  scope: automatic === "chat" || grant ? "chat" : scope2.grant ? "request" : "once",
172642
- automatic: automatic !== false
172825
+ automatic: automatic !== false,
172826
+ ...entry2.approval.connector ? { connector: entry2.approval.connector } : {}
172643
172827
  }
172644
172828
  });
172645
172829
  const completion = Promise.all([delivery, audit]).then(() => void 0);
@@ -172660,11 +172844,16 @@ var init_chat_coordinator = __esm({
172660
172844
  if (decision === "allow-request" && approval.explicitOnly) {
172661
172845
  throw new ChatCoordinatorError("This read needs its own approval. Choose Approve once or Deny.", 409, "approval-explicit-only");
172662
172846
  }
172663
- if (decision === "allow-chat" && !teklaChatAllowable(chat, approval)) {
172664
- throw new ChatCoordinatorError("Only Tekla reads can be allowed for the whole chat. Choose Approve once or Deny.", 409, "approval-not-chat-allowable");
172665
- }
172666
- if (decision === "allow-chat" && options2.allowanceRevision !== teklaAllowanceRevision(chat.teklaModelRead)) {
172667
- throw teklaAllowanceChanged();
172847
+ if (decision === "allow-chat" && approval.connector) {
172848
+ if (!connectorChatAllowable(approval)) {
172849
+ throw new ChatCoordinatorError("FloLess could not confirm which connector is asking, so this call can only be approved once. Choose Approve once or Deny.", 409, "approval-not-chat-allowable");
172850
+ }
172851
+ if (options2.allowanceRevision !== connectorAllowanceRevision(chat)) throw connectorAllowanceChanged();
172852
+ } else if (decision === "allow-chat") {
172853
+ if (!teklaChatAllowable(chat, approval)) {
172854
+ throw new ChatCoordinatorError("Only Tekla reads and your own connectors can be allowed for the whole chat. Choose Approve once or Deny.", 409, "approval-not-chat-allowable");
172855
+ }
172856
+ if (options2.allowanceRevision !== teklaAllowanceRevision(chat.teklaModelRead)) throw teklaAllowanceChanged();
172668
172857
  }
172669
172858
  const turn = readChatTurnIntent(owner3, chatId, approval.turnId);
172670
172859
  const ownership = validateOwnership(chat, turn);
@@ -172692,7 +172881,7 @@ var init_chat_coordinator = __esm({
172692
172881
  scope2.queue.shift();
172693
172882
  entry2.cleanup();
172694
172883
  } catch (error62) {
172695
- if (error62 instanceof ChatCoordinatorError && error62.code === "tekla-allowance-changed") {
172884
+ if (error62 instanceof ChatCoordinatorError && (error62.code === "tekla-allowance-changed" || error62.code === "connector-allowance-changed")) {
172696
172885
  scope2.claimed.delete(approvalId);
172697
172886
  allowanceChanged = error62;
172698
172887
  } else {
@@ -173778,7 +173967,7 @@ function readSmallRegularFile(path, maxBytes, label2) {
173778
173967
  function parseVersion(value) {
173779
173968
  const row2 = value;
173780
173969
  const provenance = row2?.provenance;
173781
- if (!row2 || typeof row2.versionId !== "string" || !UUID23.test(row2.versionId) || typeof row2.blobSha256 !== "string" || !SHA25612.test(row2.blobSha256) || typeof row2.filename !== "string" || !row2.filename || (0, import_node_path91.basename)(row2.filename) !== row2.filename || row2.filename.length > 255 || typeof row2.mime !== "string" || !RAW_MIMES.has(row2.mime) || !Number.isSafeInteger(row2.bytes) || (row2.bytes ?? 0) < 1 || (row2.bytes ?? 0) > MAX_SOURCE_BYTES2 || !validIso2(row2.createdAt) || !provenance || typeof provenance.projectId !== "string" || typeof provenance.projectUuid !== "string" || !UUID23.test(provenance.projectUuid) || typeof provenance.projectName !== "string" || !provenance.projectName.trim() || provenance.projectName.length > 255 || typeof provenance.projectSourceId !== "string" || !UUID23.test(provenance.projectSourceId)) {
173970
+ if (!row2 || typeof row2.versionId !== "string" || !UUID24.test(row2.versionId) || typeof row2.blobSha256 !== "string" || !SHA25612.test(row2.blobSha256) || typeof row2.filename !== "string" || !row2.filename || (0, import_node_path91.basename)(row2.filename) !== row2.filename || row2.filename.length > 255 || typeof row2.mime !== "string" || !RAW_MIMES.has(row2.mime) || !Number.isSafeInteger(row2.bytes) || (row2.bytes ?? 0) < 1 || (row2.bytes ?? 0) > MAX_SOURCE_BYTES2 || !validIso2(row2.createdAt) || !provenance || typeof provenance.projectId !== "string" || typeof provenance.projectUuid !== "string" || !UUID24.test(provenance.projectUuid) || typeof provenance.projectName !== "string" || !provenance.projectName.trim() || provenance.projectName.length > 255 || typeof provenance.projectSourceId !== "string" || !UUID24.test(provenance.projectSourceId)) {
173782
173971
  throw new CompanyKnowledgeError("company Knowledge version is invalid", 409, "company-index-invalid");
173783
173972
  }
173784
173973
  return row2;
@@ -173788,7 +173977,7 @@ function parseIndex(value, companyId) {
173788
173977
  if (!row2 || row2.version !== 1 || row2.companyId !== companyId || !Number.isSafeInteger(row2.revision) || (row2.revision ?? -1) < 0 || !Array.isArray(row2.sources) || row2.sources.length > MAX_LIBRARY_SOURCES || !validIso2(row2.updatedAt)) throw new CompanyKnowledgeError("company Knowledge index is invalid", 409, "company-index-invalid");
173789
173978
  const sources = row2.sources.map((candidate2) => {
173790
173979
  const source = candidate2;
173791
- if (!source || typeof source.librarySourceId !== "string" || !UUID23.test(source.librarySourceId) || typeof source.displayName !== "string" || !source.displayName.trim() || source.displayName.length > 255 || !validIso2(source.createdAt) || !validIso2(source.updatedAt) || source.removedAt !== null && !validIso2(source.removedAt) || !Array.isArray(source.versions) || source.versions.length < 1) {
173980
+ if (!source || typeof source.librarySourceId !== "string" || !UUID24.test(source.librarySourceId) || typeof source.displayName !== "string" || !source.displayName.trim() || source.displayName.length > 255 || !validIso2(source.createdAt) || !validIso2(source.updatedAt) || source.removedAt !== null && !validIso2(source.removedAt) || !Array.isArray(source.versions) || source.versions.length < 1) {
173792
173981
  throw new CompanyKnowledgeError("company Knowledge source is invalid", 409, "company-index-invalid");
173793
173982
  }
173794
173983
  return { ...source, versions: source.versions.map(parseVersion) };
@@ -173807,7 +173996,7 @@ function readMarker(path) {
173807
173996
  throw new CompanyKnowledgeError("company folder marker is unreadable", 409, "company-marker-invalid");
173808
173997
  }
173809
173998
  const row2 = value;
173810
- if (!row2 || row2.version !== 1 || typeof row2.companyId !== "string" || !UUID23.test(row2.companyId) || !validIso2(row2.createdAt)) {
173999
+ if (!row2 || row2.version !== 1 || typeof row2.companyId !== "string" || !UUID24.test(row2.companyId) || !validIso2(row2.createdAt)) {
173811
174000
  throw new CompanyKnowledgeError("company folder marker is invalid", 409, "company-marker-invalid");
173812
174001
  }
173813
174002
  return { version: 1, companyId: row2.companyId.toLowerCase(), createdAt: row2.createdAt };
@@ -173997,7 +174186,7 @@ async function promoteProjectKnowledgeSource(input2) {
173997
174186
  const index = readIndex(path, config2.companyId);
173998
174187
  let source;
173999
174188
  if (input2.librarySourceId) {
174000
- if (!UUID23.test(input2.librarySourceId)) throw new CompanyKnowledgeError("invalid company Knowledge source");
174189
+ if (!UUID24.test(input2.librarySourceId)) throw new CompanyKnowledgeError("invalid company Knowledge source");
174001
174190
  source = index.sources.find((row2) => row2.librarySourceId === input2.librarySourceId);
174002
174191
  if (!source || source.removedAt) throw new CompanyKnowledgeError("company Knowledge source is unavailable", 404);
174003
174192
  } else {
@@ -174073,7 +174262,7 @@ async function acceptCompanyKnowledgeVersion(input2) {
174073
174262
  }
174074
174263
  async function removeCompanyKnowledgeSource(librarySourceId) {
174075
174264
  return withLifecycleLock("internal-export", "company-knowledge", () => {
174076
- if (!UUID23.test(librarySourceId)) throw new CompanyKnowledgeError("invalid company Knowledge source");
174265
+ if (!UUID24.test(librarySourceId)) throw new CompanyKnowledgeError("invalid company Knowledge source");
174077
174266
  const { config: config2, path } = resolveConfiguredFolder();
174078
174267
  const index = readIndex(path, config2.companyId);
174079
174268
  const source = index.sources.find((row2) => row2.librarySourceId === librarySourceId);
@@ -174088,7 +174277,7 @@ async function removeCompanyKnowledgeSource(librarySourceId) {
174088
174277
  return source;
174089
174278
  });
174090
174279
  }
174091
- var import_node_crypto80, import_node_fs92, import_node_path91, UUID23, SHA25612, COMPANY_MARKER, LIBRARY_DIRECTORY, INDEX_FILE, MAX_INDEX_BYTES, MAX_SOURCE_BYTES2, MAX_SCAN_ENTRIES, MAX_LIBRARY_SOURCES, CompanyKnowledgeError;
174280
+ var import_node_crypto80, import_node_fs92, import_node_path91, UUID24, SHA25612, COMPANY_MARKER, LIBRARY_DIRECTORY, INDEX_FILE, MAX_INDEX_BYTES, MAX_SOURCE_BYTES2, MAX_SCAN_ENTRIES, MAX_LIBRARY_SOURCES, CompanyKnowledgeError;
174092
174281
  var init_company_knowledge_store = __esm({
174093
174282
  "company-knowledge-store.ts"() {
174094
174283
  "use strict";
@@ -174104,7 +174293,7 @@ var init_company_knowledge_store = __esm({
174104
174293
  init_projects_store();
174105
174294
  init_workspace_root_store();
174106
174295
  init_path_identity();
174107
- UUID23 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
174296
+ UUID24 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
174108
174297
  SHA25612 = /^[0-9a-f]{64}$/;
174109
174298
  COMPANY_MARKER = ".floless-company.json";
174110
174299
  LIBRARY_DIRECTORY = "knowledge-library";
@@ -195344,7 +195533,7 @@ function tokenInvalid() {
195344
195533
  function parseSelection2(value) {
195345
195534
  if (!isObject7(value) || Buffer.byteLength(JSON.stringify(value)) > WORKSPACE_MODEL_QUERY_LIMITS.selectionBytes) invalid2("selection is invalid");
195346
195535
  exactKeys6(value, ["schemaVersion", "projectUuid", "approvedRevisionId", "approvalVersion", "latestApproved"], "selection");
195347
- if (value.schemaVersion !== SELECTION_SCHEMA || typeof value.projectUuid !== "string" || !UUID24.test(value.projectUuid)) invalid2("selection identity is invalid");
195536
+ if (value.schemaVersion !== SELECTION_SCHEMA || typeof value.projectUuid !== "string" || !UUID25.test(value.projectUuid)) invalid2("selection identity is invalid");
195348
195537
  if (value.latestApproved === true) {
195349
195538
  if ("approvedRevisionId" in value || "approvalVersion" in value) invalid2("latest selection cannot carry an exact revision");
195350
195539
  return { schemaVersion: SELECTION_SCHEMA, projectUuid: value.projectUuid.toLowerCase(), latestApproved: true };
@@ -195474,7 +195663,7 @@ async function executeVerifiedArtifactModelQuery(input2) {
195474
195663
  }
195475
195664
  }
195476
195665
  function validateSource2(source) {
195477
- if (!UUID24.test(source.accountId) || !UUID24.test(source.projectUuid) || source.lineageRoot !== "revit-model" || source.contractType !== "revit.model/v1" && source.contractType !== "revit.model/v2" || source.modelCount !== 1 || source.primaryModelId !== source.modelId || !Number.isSafeInteger(source.approvalVersion) || source.approvalVersion < 1 || ![source.approvedRevisionId, source.approvedHandleDigest, source.manifestDigest, source.modelRevisionId, source.authorityDigest].every((value) => SHA25613.test(value))) {
195666
+ if (!UUID25.test(source.accountId) || !UUID25.test(source.projectUuid) || source.lineageRoot !== "revit-model" || source.contractType !== "revit.model/v1" && source.contractType !== "revit.model/v2" || source.modelCount !== 1 || source.primaryModelId !== source.modelId || !Number.isSafeInteger(source.approvalVersion) || source.approvalVersion < 1 || ![source.approvedRevisionId, source.approvedHandleDigest, source.manifestDigest, source.modelRevisionId, source.authorityDigest].every((value) => SHA25613.test(value))) {
195478
195667
  throw new WorkspaceModelQueryError(409, "model-query-schema-unsupported", "Approved model snapshot cannot be queried safely");
195479
195668
  }
195480
195669
  }
@@ -195499,7 +195688,7 @@ function loadOrCreateWorkspaceModelQueryKey(root11 = process.env.FLOLESS_HOME ??
195499
195688
  if (key5.byteLength !== 32) throw new WorkspaceModelQueryError(503, "model-query-key-unavailable", "Model query continuation key is unavailable");
195500
195689
  return { id: `workspace-model-query-v1:${(0, import_node_crypto96.createHash)("sha256").update(key5).digest("hex")}`, key: key5 };
195501
195690
  }
195502
- var import_node_crypto96, import_node_fs109, import_node_os56, import_node_path106, UUID24, SHA25613, QUERY_SCHEMA, QUERY_SCHEMA_V2, RESPONSE_SCHEMA, RESPONSE_SCHEMA_V2, TOKEN_SCHEMA, TOKEN_SCHEMA_V2, SELECTION_SCHEMA, TOKEN_DOMAIN, TOKEN_DOMAIN_V2, WORKSPACE_MODEL_QUERY_LIMITS, WorkspaceModelQueryError, isObject7, exactKeys6, utf8, canonicalHash, unique, ENTITY_FIELDS, PROPERTY_FIELDS_V1, PROPERTY_FIELDS, RELATION_FIELDS, RELATION_KINDS, STORAGE_TYPES, WorkspaceModelQueryService;
195691
+ var import_node_crypto96, import_node_fs109, import_node_os56, import_node_path106, UUID25, SHA25613, QUERY_SCHEMA, QUERY_SCHEMA_V2, RESPONSE_SCHEMA, RESPONSE_SCHEMA_V2, TOKEN_SCHEMA, TOKEN_SCHEMA_V2, SELECTION_SCHEMA, TOKEN_DOMAIN, TOKEN_DOMAIN_V2, WORKSPACE_MODEL_QUERY_LIMITS, WorkspaceModelQueryError, isObject7, exactKeys6, utf8, canonicalHash, unique, ENTITY_FIELDS, PROPERTY_FIELDS_V1, PROPERTY_FIELDS, RELATION_FIELDS, RELATION_KINDS, STORAGE_TYPES, WorkspaceModelQueryService;
195503
195692
  var init_workspace_model_query = __esm({
195504
195693
  "workspace-model-query.ts"() {
195505
195694
  "use strict";
@@ -195510,7 +195699,7 @@ var init_workspace_model_query = __esm({
195510
195699
  init_model_snapshot();
195511
195700
  init_model_query_worker();
195512
195701
  init_lifecycle_lock();
195513
- UUID24 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
195702
+ UUID25 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
195514
195703
  SHA25613 = /^[0-9a-f]{64}$/;
195515
195704
  QUERY_SCHEMA = "floless.workspace-model-query/v1";
195516
195705
  QUERY_SCHEMA_V2 = "floless.workspace-model-query/v2";
@@ -195816,7 +196005,7 @@ var init_workspace_model_query = __esm({
195816
196005
  const expected2 = (0, import_node_crypto96.createHmac)("sha256", this.#key.key).update(domain2).update(bytes3).digest();
195817
196006
  if (!(0, import_node_crypto96.timingSafeEqual)(tag, expected2)) tokenInvalid();
195818
196007
  const keys = ["schemaVersion", "keyId", "chainId", "accountId", "projectUuid", "lineageRoot", "approvalVersion", "approvedRevisionId", "approvedHandleDigest", "manifestDigest", "modelId", "modelRevisionId", "selectorHash", "queryHash", "cursor", "remainingRows", "remainingBytes", "issuedAt", "expiresAt"];
195819
- if (Object.keys(payload).sort().join(",") !== keys.sort().join(",") || ![TOKEN_SCHEMA, TOKEN_SCHEMA_V2].includes(String(payload.schemaVersion)) || payload.keyId !== this.#key.id || !isObject7(payload.cursor) || Object.keys(payload.cursor).sort().join(",") !== "artifactDigest,rowOffset" || ![payload.projectUuid, payload.accountId].every((value) => typeof value === "string" && UUID24.test(value)) || ![payload.approvedRevisionId, payload.approvedHandleDigest, payload.manifestDigest, payload.modelRevisionId, payload.selectorHash, payload.queryHash, payload.cursor.artifactDigest].every((value) => typeof value === "string" && SHA25613.test(value)) || !Number.isSafeInteger(payload.cursor.rowOffset) || payload.cursor.rowOffset < 0 || !Number.isSafeInteger(payload.remainingRows) || payload.remainingRows < 0 || payload.remainingRows > WORKSPACE_MODEL_QUERY_LIMITS.resultRows || !Number.isSafeInteger(payload.remainingBytes) || payload.remainingBytes < 0 || payload.remainingBytes > WORKSPACE_MODEL_QUERY_LIMITS.chainBytes || !Number.isSafeInteger(payload.issuedAt) || !Number.isSafeInteger(payload.expiresAt)) tokenInvalid();
196008
+ if (Object.keys(payload).sort().join(",") !== keys.sort().join(",") || ![TOKEN_SCHEMA, TOKEN_SCHEMA_V2].includes(String(payload.schemaVersion)) || payload.keyId !== this.#key.id || !isObject7(payload.cursor) || Object.keys(payload.cursor).sort().join(",") !== "artifactDigest,rowOffset" || ![payload.projectUuid, payload.accountId].every((value) => typeof value === "string" && UUID25.test(value)) || ![payload.approvedRevisionId, payload.approvedHandleDigest, payload.manifestDigest, payload.modelRevisionId, payload.selectorHash, payload.queryHash, payload.cursor.artifactDigest].every((value) => typeof value === "string" && SHA25613.test(value)) || !Number.isSafeInteger(payload.cursor.rowOffset) || payload.cursor.rowOffset < 0 || !Number.isSafeInteger(payload.remainingRows) || payload.remainingRows < 0 || payload.remainingRows > WORKSPACE_MODEL_QUERY_LIMITS.resultRows || !Number.isSafeInteger(payload.remainingBytes) || payload.remainingBytes < 0 || payload.remainingBytes > WORKSPACE_MODEL_QUERY_LIMITS.chainBytes || !Number.isSafeInteger(payload.issuedAt) || !Number.isSafeInteger(payload.expiresAt)) tokenInvalid();
195820
196009
  const now2 = this.#now();
195821
196010
  if (payload.issuedAt > now2 + WORKSPACE_MODEL_QUERY_LIMITS.clockSkewMs || payload.expiresAt < now2) {
195822
196011
  throw new WorkspaceModelQueryError(400, "continuation-expired", "Continuation is expired");
@@ -199560,7 +199749,7 @@ function parseCompleteReportSelection(body) {
199560
199749
  refuse12(400, "model-selection-invalid", "Choose an approved model to make the report.");
199561
199750
  }
199562
199751
  const value = request.selection;
199563
- if (value.schemaVersion !== SELECTION_SCHEMA2 || typeof value.projectUuid !== "string" || !UUID25.test(value.projectUuid)) {
199752
+ if (value.schemaVersion !== SELECTION_SCHEMA2 || typeof value.projectUuid !== "string" || !UUID26.test(value.projectUuid)) {
199564
199753
  refuse12(400, "model-selection-invalid", "Choose an approved model to make the report.");
199565
199754
  }
199566
199755
  if (exact4(value, ["schemaVersion", "projectUuid", "latestApproved"]) && value.latestApproved === true) {
@@ -199592,14 +199781,14 @@ async function resolveCompleteReport(input2) {
199592
199781
  }
199593
199782
  return resolved;
199594
199783
  }
199595
- var import_node_crypto103, UUID25, SHA25614, SELECTION_SCHEMA2, CompleteReportSelectionError;
199784
+ var import_node_crypto103, UUID26, SHA25614, SELECTION_SCHEMA2, CompleteReportSelectionError;
199596
199785
  var init_complete_model_report_controller = __esm({
199597
199786
  "complete-model-report-controller.ts"() {
199598
199787
  "use strict";
199599
199788
  import_node_crypto103 = require("node:crypto");
199600
199789
  init_model_snapshot();
199601
199790
  init_model_snapshot_store();
199602
- UUID25 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
199791
+ UUID26 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
199603
199792
  SHA25614 = /^[0-9a-f]{64}$/;
199604
199793
  SELECTION_SCHEMA2 = "floless.workspace-model-selection/v1";
199605
199794
  CompleteReportSelectionError = class extends Error {
@@ -199707,7 +199896,7 @@ function parseHeader(raw2) {
199707
199896
  if (header.schemaVersion !== "aware.html-report.bundle/v1" || typeof header.documentPrefix !== "string" || typeof header.documentSuffix !== "string" || typeof header.provider !== "string" || typeof header.revisionId !== "string" || !safeInteger2(header.objects) || !safeInteger2(header.properties) || Buffer.byteLength(header.documentPrefix) + Buffer.byteLength(header.documentSuffix) > MAX_HEADER_BYTES) invalid3();
199708
199897
  return header;
199709
199898
  }
199710
- function parseEntry(raw2, ordinal2, layout) {
199899
+ function parseEntry2(raw2, ordinal2, layout) {
199711
199900
  const offset = safeU64(raw2.readBigUInt64LE(0));
199712
199901
  const length3 = raw2.readUInt32LE(8);
199713
199902
  const numberOrNull = (at) => {
@@ -199723,7 +199912,7 @@ function parseEntry(raw2, ordinal2, layout) {
199723
199912
  }
199724
199913
  async function readEntry(file2, layout, ordinal2) {
199725
199914
  if (!safeInteger2(ordinal2) || ordinal2 >= layout.chunkCount) invalid3();
199726
- return parseEntry(await readExact(file2, ENTRY_BYTES, layout.indexOffset + ordinal2 * ENTRY_BYTES), ordinal2, layout);
199915
+ return parseEntry2(await readExact(file2, ENTRY_BYTES, layout.indexOffset + ordinal2 * ENTRY_BYTES), ordinal2, layout);
199727
199916
  }
199728
199917
  async function inspectBundle(file2, expectedBytes, verifyAllChunks) {
199729
199918
  const info = await file2.stat();
@@ -199761,7 +199950,7 @@ async function inspectBundle(file2, expectedBytes, verifyAllChunks) {
199761
199950
  for (let i = 0; i < chunkCount; i += 1) {
199762
199951
  const raw2 = await readExact(file2, ENTRY_BYTES, layout.indexOffset + i * ENTRY_BYTES);
199763
199952
  footerHash.update(raw2);
199764
- const entry2 = parseEntry(raw2, i, layout);
199953
+ const entry2 = parseEntry2(raw2, i, layout);
199765
199954
  if (entry2.offset !== expectedFragmentOffset + 4) invalid3();
199766
199955
  const lengthPrefix = await readExact(file2, 4, expectedFragmentOffset);
199767
199956
  if (lengthPrefix.readUInt32LE(0) !== entry2.length) invalid3();
@@ -202846,8 +203035,8 @@ function classifiedFailure(importer, spec, facts2) {
202846
203035
  cause: facts2 ? describeCause(facts2) : oneLine(spec.reason ?? spec.code, CAUSE_LIMIT)
202847
203036
  };
202848
203037
  if (spec.providerCode && /^xeorvt-[a-z0-9-]{1,90}$/.test(spec.providerCode)) failure2.providerCode = spec.providerCode;
202849
- if (spec.diagnosticId && UUID26.test(spec.diagnosticId)) failure2.diagnosticId = spec.diagnosticId;
202850
- if (spec.awareRunId && UUID26.test(spec.awareRunId)) failure2.awareRunId = spec.awareRunId;
203038
+ if (spec.diagnosticId && UUID27.test(spec.diagnosticId)) failure2.diagnosticId = spec.diagnosticId;
203039
+ if (spec.awareRunId && UUID27.test(spec.awareRunId)) failure2.awareRunId = spec.awareRunId;
202851
203040
  if (typeof spec.providerMessage === "string" && spec.providerMessage.trim()) failure2.providerMessage = oneLine(spec.providerMessage, PROVIDER_MESSAGE_LIMIT);
202852
203041
  if (spec.reason && RECOVERY_REASONS.includes(spec.reason)) failure2.reason = spec.reason;
202853
203042
  if (spec.coverage) failure2.coverage = spec.coverage;
@@ -202907,7 +203096,7 @@ function importFailureLogLine(operationId, diagnostic) {
202907
203096
  return `[floless] ${NOUN[diagnostic.importer]} import ${oneLine(operationId, 80)} ${diagnostic.escalatedAt ? "escalated" : "failed"} at ${oneLine(diagnostic.stage, 40)} after ${seconds}s: kind=${diagnostic.kind} reason=${diagnostic.reason ?? "-"} code=${oneLine(diagnostic.code, 96)} provider=${diagnostic.providerCode ?? "-"} diagnostic=${diagnostic.diagnosticId ?? "-"} run=${diagnostic.awareRunId ?? "-"} cause=${diagnostic.cause}`;
202908
203097
  }
202909
203098
  function reportDetails(importer, record7) {
202910
- if (record7.state !== "failed" || !UUID26.test(record7.operationId)) return null;
203099
+ if (record7.state !== "failed" || !UUID27.test(record7.operationId)) return null;
202911
203100
  const failure2 = record7.failure ?? {};
202912
203101
  const d = failure2.diagnostic ?? {};
202913
203102
  const out = { importer, operationId: record7.operationId };
@@ -202919,11 +203108,11 @@ function reportDetails(importer, record7) {
202919
203108
  if (typeof code === "string" && CODE.test(code)) out.code = code;
202920
203109
  if (typeof d.reason === "string" && RECOVERY_REASONS.includes(d.reason)) out.reason = d.reason;
202921
203110
  if (typeof d.providerCode === "string" && /^xeorvt-[a-z0-9-]{1,90}$/.test(d.providerCode)) out.providerCode = d.providerCode;
202922
- if (typeof d.diagnosticId === "string" && UUID26.test(d.diagnosticId)) out.diagnosticId = d.diagnosticId;
202923
- if (typeof d.awareRunId === "string" && UUID26.test(d.awareRunId)) out.awareRunId = d.awareRunId;
203111
+ if (typeof d.diagnosticId === "string" && UUID27.test(d.diagnosticId)) out.diagnosticId = d.diagnosticId;
203112
+ if (typeof d.awareRunId === "string" && UUID27.test(d.awareRunId)) out.awareRunId = d.awareRunId;
202924
203113
  return out;
202925
203114
  }
202926
- var IMPORT_FAILURE_KINDS, RECOVERY_REASONS, USER_MESSAGE_LIMIT, HARD_MESSAGE_BOUND, PROVIDER_MESSAGE_LIMIT, CAUSE_LIMIT, TITLE_LIMIT, CONTROL_EXCEPT_NEWLINE, CONTROL2, CODE, UUID26, NOUN, KIND_COPY2, RECOVERY, STAGES, ISO;
203115
+ var IMPORT_FAILURE_KINDS, RECOVERY_REASONS, USER_MESSAGE_LIMIT, HARD_MESSAGE_BOUND, PROVIDER_MESSAGE_LIMIT, CAUSE_LIMIT, TITLE_LIMIT, CONTROL_EXCEPT_NEWLINE, CONTROL2, CODE, UUID27, NOUN, KIND_COPY2, RECOVERY, STAGES, ISO;
202927
203116
  var init_import_failure = __esm({
202928
203117
  "import-failure.ts"() {
202929
203118
  "use strict";
@@ -202965,7 +203154,7 @@ var init_import_failure = __esm({
202965
203154
  CONTROL_EXCEPT_NEWLINE = new RegExp("[\\u0000-\\u0009\\u000b-\\u001f\\u007f]+", "g");
202966
203155
  CONTROL2 = new RegExp("[\\u0000-\\u001f\\u007f]+", "g");
202967
203156
  CODE = /^[a-z0-9_-]{1,96}$/;
202968
- UUID26 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
203157
+ UUID27 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
202969
203158
  NOUN = { revit: "Revit", tekla: "Tekla" };
202970
203159
  KIND_COPY2 = {
202971
203160
  model: (i) => ({
@@ -203826,7 +204015,7 @@ function statePayload(state4) {
203826
204015
  };
203827
204016
  }
203828
204017
  function validateBase(base2) {
203829
- if (!UUID27.test(base2.projectUuid)) throw new ModelEditorStateError(409, "state-binding-mismatch", "project UUID is invalid");
204018
+ if (!UUID28.test(base2.projectUuid)) throw new ModelEditorStateError(409, "state-binding-mismatch", "project UUID is invalid");
203830
204019
  boundedString2(base2.modelId, "modelId", 512);
203831
204020
  digest7(base2.baseRevisionId, "baseRevisionId");
203832
204021
  digest7(base2.sourceDigest, "sourceDigest");
@@ -203841,7 +204030,7 @@ function pinJournalDirectory(root11) {
203841
204030
  return (0, import_node_path126.join)(root11, "model-cas", "journal");
203842
204031
  }
203843
204032
  function isSnapshotPinJournal(value) {
203844
- if (!record5(value) || value.schema !== PIN_JOURNAL_SCHEMA || typeof value.operationId !== "string" || !UUID27.test(String(value.projectUuid)) || !SHA25616.test(String(value.baseRevisionId)) || !SHA25616.test(String(value.stateObjectDigest)) || !Number.isSafeInteger(value.add) || !Number.isSafeInteger(value.remove) || !["prepared", "ledger-written", "published", "aborted"].includes(String(value.state))) return false;
204033
+ if (!record5(value) || value.schema !== PIN_JOURNAL_SCHEMA || typeof value.operationId !== "string" || !UUID28.test(String(value.projectUuid)) || !SHA25616.test(String(value.baseRevisionId)) || !SHA25616.test(String(value.stateObjectDigest)) || !Number.isSafeInteger(value.add) || !Number.isSafeInteger(value.remove) || !["prepared", "ledger-written", "published", "aborted"].includes(String(value.state))) return false;
203845
204034
  return value.previousRefs === void 0 || record5(value.previousRefs) && Object.values(value.previousRefs).every((count4) => typeof count4 === "number" && Number.isSafeInteger(count4) && count4 >= 0);
203846
204035
  }
203847
204036
  function sendError5(reply, error62) {
@@ -203894,7 +204083,7 @@ function registerModelEditorStateRoutes(app, deps) {
203894
204083
  }
203895
204084
  });
203896
204085
  }
203897
- var import_node_crypto110, import_node_fs129, import_node_os63, import_node_path126, MODEL_EDITOR_STATE_LIMITS, STATE_SCHEMA, FRAME_SCHEMA, HEAD_SCHEMA, PIN_JOURNAL_SCHEMA, SHA25616, UUID27, FORBIDDEN_SESSION_KEYS, ModelEditorStateError, ModelEditorStateStore, FileModelEditorSnapshotPinPort;
204086
+ var import_node_crypto110, import_node_fs129, import_node_os63, import_node_path126, MODEL_EDITOR_STATE_LIMITS, STATE_SCHEMA, FRAME_SCHEMA, HEAD_SCHEMA, PIN_JOURNAL_SCHEMA, SHA25616, UUID28, FORBIDDEN_SESSION_KEYS, ModelEditorStateError, ModelEditorStateStore, FileModelEditorSnapshotPinPort;
203898
204087
  var init_model_editor_state = __esm({
203899
204088
  "model-editor-state.ts"() {
203900
204089
  "use strict";
@@ -203919,7 +204108,7 @@ var init_model_editor_state = __esm({
203919
204108
  HEAD_SCHEMA = "floless.model-editor-state-head/v1";
203920
204109
  PIN_JOURNAL_SCHEMA = "floless.model-editor-state-pin-journal/v1";
203921
204110
  SHA25616 = /^[0-9a-f]{64}$/;
203922
- UUID27 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
204111
+ UUID28 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
203923
204112
  FORBIDDEN_SESSION_KEYS = /* @__PURE__ */ new Set(["selection", "hover", "activeTool", "snapToggles"]);
203924
204113
  ModelEditorStateError = class extends Error {
203925
204114
  constructor(status, code, message2) {
@@ -204020,7 +204209,7 @@ var init_model_editor_state = __esm({
204020
204209
  /** Called only while the project slug + Revit UUID locks are held. Each head is tombstoned under
204021
204210
  * the innermost CAS pin transaction before its retained revision pins and immutable objects leave. */
204022
204211
  async deleteProject(projectUuid) {
204023
- if (!UUID27.test(projectUuid)) throw new ModelEditorStateError(409, "state-binding-mismatch", "project UUID is invalid");
204212
+ if (!UUID28.test(projectUuid)) throw new ModelEditorStateError(409, "state-binding-mismatch", "project UUID is invalid");
204024
204213
  const normalized2 = projectUuid.toLowerCase();
204025
204214
  const directory = (0, import_node_path126.join)(this.root, "heads", normalized2);
204026
204215
  if (!(0, import_node_fs129.existsSync)(directory)) return 0;
@@ -204506,7 +204695,7 @@ function validate5(value, expectedUuid) {
204506
204695
  throw new ModelSnapshotError("model_identity_required", "Revit project lifecycle identity is missing");
204507
204696
  }
204508
204697
  const record7 = value;
204509
- if (record7.schema !== "floless.revit-project-lifecycle/v1" || !UUID28.test(record7.accountId) || !UUID28.test(record7.projectUuid) || expectedUuid && record7.projectUuid !== expectedUuid || !Number.isSafeInteger(record7.generation) || record7.generation < 0 || !Number.isSafeInteger(record7.entitlementRevision) || record7.entitlementRevision < 0) {
204698
+ if (record7.schema !== "floless.revit-project-lifecycle/v1" || !UUID29.test(record7.accountId) || !UUID29.test(record7.projectUuid) || expectedUuid && record7.projectUuid !== expectedUuid || !Number.isSafeInteger(record7.generation) || record7.generation < 0 || !Number.isSafeInteger(record7.entitlementRevision) || record7.entitlementRevision < 0) {
204510
204699
  throw new ModelSnapshotError("model_identity_required", "Revit project lifecycle identity is invalid");
204511
204700
  }
204512
204701
  const validSource = (source) => source == null || typeof source.filename === "string" && /\.rvt$/i.test(source.filename) && /^[0-9a-f]{64}$/.test(source.sha256) && Number.isSafeInteger(source.bytes) && source.bytes >= 0;
@@ -204568,7 +204757,7 @@ function clearRevitProjectModelAuthority(projectId2) {
204568
204757
  function initializeRevitProjectLifecycle(projectId2, accountId, entitlementRevision) {
204569
204758
  const project = getProject(projectId2);
204570
204759
  if (!project?.uuid) throw new ModelSnapshotError("model_identity_required", "project incarnation UUID is required");
204571
- if (!UUID28.test(accountId) || !Number.isSafeInteger(entitlementRevision) || entitlementRevision < 0) {
204760
+ if (!UUID29.test(accountId) || !Number.isSafeInteger(entitlementRevision) || entitlementRevision < 0) {
204572
204761
  throw new ModelSnapshotError("model_invalid_input", "signed account identity and entitlement revision are required");
204573
204762
  }
204574
204763
  clearRevitProjectModelAuthority(projectId2);
@@ -204612,7 +204801,7 @@ function readRevitProjectLifecycle(projectId2) {
204612
204801
  }
204613
204802
  }
204614
204803
  function findRevitProjectLifecycle(projectUuid) {
204615
- if (!UUID28.test(projectUuid)) throw new ModelSnapshotError("model_identity_required", "project incarnation UUID is required");
204804
+ if (!UUID29.test(projectUuid)) throw new ModelSnapshotError("model_identity_required", "project incarnation UUID is required");
204616
204805
  const project = listProjects().find((candidate2) => candidate2.uuid === projectUuid);
204617
204806
  if (!project) return null;
204618
204807
  return { projectId: project.id, lifecycle: readRevitProjectLifecycle(project.id) };
@@ -204732,7 +204921,7 @@ function rebindRevitDraftToApprovedVersion(projectId2, version2) {
204732
204921
  function revitApprovedHandleForVersion(projectId2, version2) {
204733
204922
  return readRevitProjectLifecycle(projectId2).approvedVersions[String(version2)] ?? null;
204734
204923
  }
204735
- var import_node_fs131, import_node_path128, UUID28, FILE2;
204924
+ var import_node_fs131, import_node_path128, UUID29, FILE2;
204736
204925
  var init_revit_project_lifecycle = __esm({
204737
204926
  "revit-project-lifecycle.ts"() {
204738
204927
  "use strict";
@@ -204742,7 +204931,7 @@ var init_revit_project_lifecycle = __esm({
204742
204931
  init_projects_store();
204743
204932
  init_revit_project_lock();
204744
204933
  init_model_snapshot();
204745
- UUID28 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
204934
+ UUID29 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
204746
204935
  FILE2 = ".floless-model-lifecycle.json";
204747
204936
  }
204748
204937
  });
@@ -205544,7 +205733,7 @@ function revitRunFailureSpec(facts2) {
205544
205733
  const run2 = facts2.aware;
205545
205734
  const runId = run2?.runId;
205546
205735
  const traceText = run2?.traceText;
205547
- if (runId && UUID29.test(runId) && traceText && Buffer.byteLength(traceText) <= TRACE_LIMIT_BYTES) {
205736
+ if (runId && UUID30.test(runId) && traceText && Buffer.byteLength(traceText) <= TRACE_LIMIT_BYTES) {
205548
205737
  for (const line2 of traceText.split(/\r?\n/)) {
205549
205738
  if (!line2) continue;
205550
205739
  try {
@@ -205554,7 +205743,7 @@ function revitRunFailureSpec(facts2) {
205554
205743
  if (event.kind !== "node-error" || eventRunId !== runId || event.node !== NODE || !structured) continue;
205555
205744
  if (typeof structured.code === "string" && /^reference-[a-z0-9-]{1,90}$/.test(structured.code)) code = structured.code;
205556
205745
  if (typeof structured.providerCode === "string" && /^xeorvt-[a-z0-9-]{1,90}$/.test(structured.providerCode)) providerCode = structured.providerCode;
205557
- if (typeof structured.diagnosticId === "string" && UUID29.test(structured.diagnosticId)) diagnosticId = structured.diagnosticId;
205746
+ if (typeof structured.diagnosticId === "string" && UUID30.test(structured.diagnosticId)) diagnosticId = structured.diagnosticId;
205558
205747
  if (typeof structured.retryable === "boolean") awareRetryable = structured.retryable;
205559
205748
  const message2 = structured.message ?? event.message;
205560
205749
  if (typeof message2 === "string") providerMessage = message2;
@@ -205568,7 +205757,7 @@ function revitRunFailureSpec(facts2) {
205568
205757
  providerCode,
205569
205758
  diagnosticId,
205570
205759
  providerMessage,
205571
- awareRunId: runId && UUID29.test(runId) ? runId : void 0,
205760
+ awareRunId: runId && UUID30.test(runId) ? runId : void 0,
205572
205761
  kind: entry2.kind,
205573
205762
  // A code this table knows states its own verdict; otherwise AWARE's word stands (default: retryable).
205574
205763
  retryable: entry2.retryable ?? awareRetryable ?? true,
@@ -205576,13 +205765,13 @@ function revitRunFailureSpec(facts2) {
205576
205765
  message: entry2.message ?? ""
205577
205766
  };
205578
205767
  }
205579
- var NODE, TRACE_LIMIT_BYTES, UUID29, PROVIDER_CODES, REVIT_MAPPED_CODES;
205768
+ var NODE, TRACE_LIMIT_BYTES, UUID30, PROVIDER_CODES, REVIT_MAPPED_CODES;
205580
205769
  var init_revit_import_failure = __esm({
205581
205770
  "revit-import-failure.ts"() {
205582
205771
  "use strict";
205583
205772
  NODE = "read-snapshot";
205584
205773
  TRACE_LIMIT_BYTES = 1024 * 1024;
205585
- UUID29 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
205774
+ UUID30 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
205586
205775
  PROVIDER_CODES = {
205587
205776
  // ── model: the provider FINISHED and the result says the file is the problem ──────────────────
205588
205777
  "xeorvt-provider-conversion-failed": {
@@ -209217,7 +209406,7 @@ function assertTeklaSessionCurrent(expected2, current) {
209217
209406
  }
209218
209407
  function trustedCoverageCounts(facts2) {
209219
209408
  const run2 = facts2.aware;
209220
- if (run2?.awareKind !== "run" || !run2.runId || !UUID30.test(run2.runId)) return null;
209409
+ if (run2?.awareKind !== "run" || !run2.runId || !UUID31.test(run2.runId)) return null;
209221
209410
  const trace = run2.traceText;
209222
209411
  if (!trace || Buffer.byteLength(trace, "utf8") > TRACE_LIMIT_BYTES2) return null;
209223
209412
  let candidate2 = null;
@@ -209228,7 +209417,7 @@ function trustedCoverageCounts(facts2) {
209228
209417
  const event = JSON.parse(line2);
209229
209418
  if (event?.kind !== "node-error" || event.structured?.code !== "reference-model-coverage-incomplete") continue;
209230
209419
  matches++;
209231
- if (event.run_id !== run2.runId || event.node !== NODE3 || event.structured.phase !== "conversion" || event.structured.retryable !== false || typeof event.structured.diagnosticId !== "string" || !UUID30.test(event.structured.diagnosticId)) return null;
209420
+ if (event.run_id !== run2.runId || event.node !== NODE3 || event.structured.phase !== "conversion" || event.structured.retryable !== false || typeof event.structured.diagnosticId !== "string" || !UUID31.test(event.structured.diagnosticId)) return null;
209232
209421
  candidate2 = parseProviderCoverageMessage(event.structured.message);
209233
209422
  if (!candidate2) return null;
209234
209423
  } catch {
@@ -209265,7 +209454,7 @@ function mapTeklaFailure(facts2) {
209265
209454
  if (!line2) continue;
209266
209455
  try {
209267
209456
  const event = JSON.parse(line2);
209268
- if (event.kind === "node-error" && event.structured?.code === "reference-provider-failed" && event.structured.phase === "discovery" && typeof event.structured.diagnosticId === "string" && UUID30.test(event.structured.diagnosticId)) {
209457
+ if (event.kind === "node-error" && event.structured?.code === "reference-provider-failed" && event.structured.phase === "discovery" && typeof event.structured.diagnosticId === "string" && UUID31.test(event.structured.diagnosticId)) {
209269
209458
  providerDiscoveryId = event.structured.diagnosticId;
209270
209459
  break;
209271
209460
  }
@@ -209328,7 +209517,7 @@ function validateJournal2(value, projectId2) {
209328
209517
  if (row2.schema !== "floless.tekla-publication/v1" || row2.projectId !== projectId2 || !["prepared", "snapshot", "contract", "lifecycle"].includes(row2.phase) || typeof row2.operationId !== "string" || typeof row2.projectUuid !== "string" || !Number.isSafeInteger(row2.generation) || typeof row2.sourcePackageSha256 !== "string" || !row2.manifest || !row2.contract || !row2.handle) throw new ModelSnapshotError("model_integrity_failure", "Tekla publication journal is invalid");
209329
209518
  return row2;
209330
209519
  }
209331
- var import_node_crypto120, import_node_fs139, import_node_path136, APP3, NODE3, JOURNAL2, TIMEOUT_MS3, TRACE_LIMIT_BYTES2, UUID30, TEKLA_DEGRADED_READ_AWARE_FLOOR, AWARE_COMPLETE_WITHOUT_TILES, TeklaImportOrchestrator;
209520
+ var import_node_crypto120, import_node_fs139, import_node_path136, APP3, NODE3, JOURNAL2, TIMEOUT_MS3, TRACE_LIMIT_BYTES2, UUID31, TEKLA_DEGRADED_READ_AWARE_FLOOR, AWARE_COMPLETE_WITHOUT_TILES, TeklaImportOrchestrator;
209332
209521
  var init_tekla_import = __esm({
209333
209522
  "tekla-import.ts"() {
209334
209523
  "use strict";
@@ -209360,7 +209549,7 @@ var init_tekla_import = __esm({
209360
209549
  JOURNAL2 = ".floless-tekla-publication.json";
209361
209550
  TIMEOUT_MS3 = 31 * 6e4;
209362
209551
  TRACE_LIMIT_BYTES2 = 1024 * 1024;
209363
- UUID30 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
209552
+ UUID31 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
209364
209553
  TEKLA_DEGRADED_READ_AWARE_FLOOR = "0.146.0";
209365
209554
  AWARE_COMPLETE_WITHOUT_TILES = "A complete model conversion requires at least one geometry tile.";
209366
209555
  TeklaImportOrchestrator = class {
@@ -236177,6 +236366,25 @@ var init_chat_provider = __esm({
236177
236366
  });
236178
236367
 
236179
236368
  // chat-provider-claude.ts
236369
+ function claudeConnectorCall(toolName, mcpServer) {
236370
+ const match = /^mcp__([A-Za-z0-9][A-Za-z0-9_.-]*?)__(.+)$/u.exec(toolName);
236371
+ if (!match) return null;
236372
+ const name = typeof mcpServer?.name === "string" ? mcpServer.name.trim().slice(0, 128) : "";
236373
+ const prefix = `mcp__${name.replace(/[^A-Za-z0-9_-]/gu, "_")}__`;
236374
+ if (name && mcpServer?.source !== "sdk" && toolName.startsWith(prefix) && toolName.length > prefix.length) {
236375
+ return {
236376
+ provider: "claude",
236377
+ server: name,
236378
+ app: null,
236379
+ tool: toolName.slice(prefix.length, prefix.length + 200),
236380
+ verified: CONNECTOR_IDENTITY_NAME.test(name)
236381
+ };
236382
+ }
236383
+ return { provider: "claude", server: match[1].slice(0, 128), app: null, tool: match[2].slice(0, 200), verified: false };
236384
+ }
236385
+ function connectorInputs(input2) {
236386
+ return Object.entries(input2 ?? {}).slice(0, 12).map(([key5, value]) => `${key5}: ${typeof value === "string" ? value : JSON.stringify(value)}`).join("; ");
236387
+ }
236180
236388
  function warmFingerprint(chat, readOnly2, boundTools) {
236181
236389
  return JSON.stringify([
236182
236390
  chat.cwd,
@@ -236186,6 +236394,7 @@ function warmFingerprint(chat, readOnly2, boundTools) {
236186
236394
  chat.settings.effort,
236187
236395
  chat.connectionRevision,
236188
236396
  chat.integrationBindings.length > 0,
236397
+ chat.settings.useOwnConnectors === true,
236189
236398
  [...boundTools].sort()
236190
236399
  ]);
236191
236400
  }
@@ -236261,7 +236470,7 @@ function terminalReceipt(chat, turn) {
236261
236470
  error: cleanText(event.payload.terminalError, 8192) || "Claude turn failed"
236262
236471
  };
236263
236472
  }
236264
- var import_node_child_process29, import_node_crypto132, import_node_fs158, import_node_util13, execFile15, CLAUDE_PROBE_TIMEOUT, READ_ONLY_TOOLS, ISOLATED_READ_TOOLS, ISOLATED_WRITE_TOOLS, CLAUDE_TOOL_SHAPES, TurnRef, DEFAULT_WARM_DEPS, LiveClaudeInput, ClaudeChatProvider;
236473
+ var import_node_child_process29, import_node_crypto132, import_node_fs158, import_node_util13, execFile15, CLAUDE_PROBE_TIMEOUT, READ_ONLY_TOOLS, READ_ONLY_HOOK_TOOLS, FLOLESS_TOOL_PREFIX, CONNECTOR_IDENTITY_NAME, ISOLATED_READ_TOOLS, ISOLATED_WRITE_TOOLS, CLAUDE_TOOL_SHAPES, TurnRef, DEFAULT_WARM_DEPS, LiveClaudeInput, ClaudeChatProvider;
236265
236474
  var init_chat_provider_claude = __esm({
236266
236475
  "chat-provider-claude.ts"() {
236267
236476
  "use strict";
@@ -236279,6 +236488,7 @@ var init_chat_provider_claude = __esm({
236279
236488
  init_chat_evidence();
236280
236489
  init_chat_filter_proposal();
236281
236490
  init_chat_coordinator();
236491
+ init_chat_connector_allowance();
236282
236492
  init_terminal_runtime();
236283
236493
  init_managed_runtime();
236284
236494
  init_managed_runtime_pins();
@@ -236287,6 +236497,9 @@ var init_chat_provider_claude = __esm({
236287
236497
  execFile15 = (0, import_node_util13.promisify)(import_node_child_process29.execFile);
236288
236498
  CLAUDE_PROBE_TIMEOUT = "Claude capability check timed out";
236289
236499
  READ_ONLY_TOOLS = ["Read", "Glob", "Grep", "WebFetch", "WebSearch"];
236500
+ READ_ONLY_HOOK_TOOLS = /* @__PURE__ */ new Set([...READ_ONLY_TOOLS, "ToolSearch"]);
236501
+ FLOLESS_TOOL_PREFIX = "mcp__floless_integrations__";
236502
+ CONNECTOR_IDENTITY_NAME = /^[A-Za-z0-9][A-Za-z0-9_.: -]{0,127}$/u;
236290
236503
  ISOLATED_READ_TOOLS = ["Read", "Glob", "Grep", "Skill"];
236291
236504
  ISOLATED_WRITE_TOOLS = [...ISOLATED_READ_TOOLS, "Edit", "Write"];
236292
236505
  CLAUDE_TOOL_SHAPES = {
@@ -236402,8 +236615,12 @@ var init_chat_provider_claude = __esm({
236402
236615
  boundToolNames(chat) {
236403
236616
  return this.integrationTools?.specsFor(chat).map((spec) => spec.name) ?? [];
236404
236617
  }
236405
- isIntegrationTool(toolName) {
236406
- return this.integrationTools?.specs().some((spec) => toolName === spec.name || toolName.endsWith(`__${spec.name}`)) ?? false;
236618
+ /**
236619
+ * A FloLess tool is exactly `mcp__floless_integrations__<tool>` for a tool FloLess bound in THIS chat's in-process
236620
+ * server (#1907). A suffix match let any connector whose tool ended in a FloLess tool name pass as FloLess's own.
236621
+ */
236622
+ isIntegrationTool(chat, toolName) {
236623
+ return this.boundToolNames(chat).some((name) => toolName === `${FLOLESS_TOOL_PREFIX}${name}`);
236407
236624
  }
236408
236625
  /** Mounted only when this chat is bound for at least one FloLess tool, and declares only those tools. */
236409
236626
  integrationMcpServer(chat, ref) {
@@ -236499,8 +236716,9 @@ var init_chat_provider_claude = __esm({
236499
236716
  const isolateNativeConnectors = chat.integrationBindings.length > 0;
236500
236717
  const integrationServer = this.integrationMcpServer(chat, ref);
236501
236718
  const integrationToolNames = integrationServer ? this.integrationTools?.specsFor(chat).map((spec) => `mcp__floless_integrations__${spec.name}`) ?? [] : [];
236502
- const integrationRouting = (isolateNativeConnectors ? "This chat selected one or more FloLess integration accounts. Use only the floless_integrations tools for those services. If a FloLess integration call fails, report that failure; do not try another account, connector, browser, shell, or web route." : "No FloLess integration account is selected for this chat.") + (chat.teklaModelRead ? ` ${teklaRouting(chat.teklaModelRead)}` : "") + (integrationToolNames.includes(`mcp__floless_integrations__${LINK_SUBJECTS_TOOL_NAME}`) ? ` ${LINK_SUBJECTS_ROUTING}` : "") + (integrationToolNames.includes(`mcp__floless_integrations__${EVIDENCE_TOOL_NAME}`) ? ` ${EVIDENCE_ROUTING}` : "") + (integrationToolNames.includes(`mcp__floless_integrations__${FILTER_PROPOSE_TOOL_NAME}`) ? ` ${FILTER_PROPOSE_ROUTING}` : "");
236503
- const selectedTools = isolateNativeConnectors ? [...readOnly2 ? ISOLATED_READ_TOOLS : ISOLATED_WRITE_TOOLS, ...integrationToolNames] : readOnly2 ? [...READ_ONLY_TOOLS, ...integrationToolNames] : { type: "preset", preset: "claude_code" };
236719
+ const ownConnectorsOff = !isolateNativeConnectors && chat.settings.useOwnConnectors !== true;
236720
+ const integrationRouting = (isolateNativeConnectors ? "This chat selected one or more FloLess integration accounts. Use only the floless_integrations tools for those services. If a FloLess integration call fails, report that failure; do not try another account, connector, browser, shell, or web route." : "No FloLess integration account is selected for this chat.") + (ownConnectorsOff ? ` ${OWN_CONNECTORS_OFF_ROUTING("Claude")}` : "") + (chat.teklaModelRead ? ` ${teklaRouting(chat.teklaModelRead)}` : "") + (integrationToolNames.includes(`mcp__floless_integrations__${LINK_SUBJECTS_TOOL_NAME}`) ? ` ${LINK_SUBJECTS_ROUTING}` : "") + (integrationToolNames.includes(`mcp__floless_integrations__${EVIDENCE_TOOL_NAME}`) ? ` ${EVIDENCE_ROUTING}` : "") + (integrationToolNames.includes(`mcp__floless_integrations__${FILTER_PROPOSE_TOOL_NAME}`) ? ` ${FILTER_PROPOSE_ROUTING}` : "");
236721
+ const selectedTools = isolateNativeConnectors ? [...readOnly2 ? ISOLATED_READ_TOOLS : ISOLATED_WRITE_TOOLS, ...integrationToolNames] : { type: "preset", preset: "claude_code" };
236504
236722
  return {
236505
236723
  cwd: chat.cwd,
236506
236724
  // #1890: a workspace conversation works in its scratch folder and may READ the whole workspace (its writes stay
@@ -236510,7 +236728,10 @@ var init_chat_provider_claude = __esm({
236510
236728
  resume: chat.nativeSessionId ?? void 0,
236511
236729
  model: chat.settings.model ?? void 0,
236512
236730
  effort: chat.settings.effort ?? void 0,
236513
- permissionMode: readOnly2 ? "dontAsk" : "default",
236731
+ // 'dontAsk' never consults canUseTool, so a connector could not reach its card; only an isolated chat (no
236732
+ // connectors at all) keeps it.
236733
+ permissionMode: readOnly2 && isolateNativeConnectors ? "dontAsk" : "default",
236734
+ ...isolateNativeConnectors ? {} : { hooks: { PreToolUse: [{ hooks: [async (hookInput) => this.preToolUse(chat, readOnly2, hookInput)] }] } },
236514
236735
  tools: selectedTools,
236515
236736
  // 'dontAsk' denies every tool that is not pre-approved and never consults canUseTool, so a
236516
236737
  // bound FloLess tool was refused before its handler could raise the FloLess approval card.
@@ -236519,7 +236740,7 @@ var init_chat_provider_claude = __esm({
236519
236740
  skills: "all",
236520
236741
  systemPrompt: { type: "preset", preset: "claude_code", append: integrationRouting, snapshot: false },
236521
236742
  settingSources: ["user", "project"],
236522
- strictMcpConfig: isolateNativeConnectors,
236743
+ strictMcpConfig: isolateNativeConnectors || ownConnectorsOff,
236523
236744
  mcpServers: integrationServer ? { floless_integrations: integrationServer } : {},
236524
236745
  includePartialMessages: true,
236525
236746
  abortController,
@@ -236527,14 +236748,16 @@ var init_chat_provider_claude = __esm({
236527
236748
  ...process.env,
236528
236749
  CLAUDE_AGENT_SDK_CLIENT_APP: "floless-chat/1.0.0",
236529
236750
  DISABLE_AUTOUPDATER: "1",
236530
- ...isolateNativeConnectors ? { ENABLE_CLAUDEAI_MCP_SERVERS: "false" } : {}
236751
+ ...isolateNativeConnectors || ownConnectorsOff ? { ENABLE_CLAUDEAI_MCP_SERVERS: "false" } : {}
236531
236752
  },
236532
236753
  canUseTool: async (toolName, input2, options2) => {
236533
236754
  const bound = ref.current();
236534
236755
  if (!bound) return { behavior: "deny", message: "This Claude turn is no longer active.", toolUseID: options2.toolUseID };
236535
- if (this.isIntegrationTool(toolName)) {
236756
+ const fromFloLess = !options2.mcpServer || options2.mcpServer.source === "sdk";
236757
+ if (fromFloLess && this.isIntegrationTool(bound.chat, toolName)) {
236536
236758
  return { behavior: "allow", updatedInput: input2, toolUseID: options2.toolUseID };
236537
236759
  }
236760
+ const connector = isolateNativeConnectors ? null : claudeConnectorCall(toolName, options2.mcpServer);
236538
236761
  if (isolateNativeConnectors && !ISOLATED_WRITE_TOOLS.includes(toolName)) {
236539
236762
  return {
236540
236763
  behavior: "deny",
@@ -236542,7 +236765,7 @@ var init_chat_provider_claude = __esm({
236542
236765
  toolUseID: options2.toolUseID
236543
236766
  };
236544
236767
  }
236545
- if (readOnly2) return { behavior: "deny", message: "This chat is read-only.", toolUseID: options2.toolUseID };
236768
+ if (readOnly2 && !connector) return { behavior: "deny", message: "This chat is read-only.", toolUseID: options2.toolUseID };
236546
236769
  const nativeRequestId = `${bound.chat.chatId}:${options2.requestId}`;
236547
236770
  let rejectPending;
236548
236771
  const decision = new Promise((resolve57, reject3) => {
@@ -236562,7 +236785,13 @@ var init_chat_provider_claude = __esm({
236562
236785
  if (this.approvals.delete(nativeRequestId)) rejectPending(new Error("Claude approval was interrupted"));
236563
236786
  }, { once: true });
236564
236787
  try {
236565
- await bound.callbacks.onApproval({
236788
+ await bound.callbacks.onApproval(connector ? {
236789
+ nativeRequestId,
236790
+ summary: connectorApprovalQuestion(connector, connectorInputs(input2)),
236791
+ signal: options2.signal,
236792
+ explicitOnly: true,
236793
+ connector
236794
+ } : {
236566
236795
  nativeRequestId,
236567
236796
  summary: approvalLabel(toolName, input2, options2),
236568
236797
  signal: options2.signal
@@ -236575,6 +236804,21 @@ var init_chat_provider_claude = __esm({
236575
236804
  }
236576
236805
  };
236577
236806
  }
236807
+ /**
236808
+ * The PreToolUse hook of every chat that can see the person's own connectors (#1907). It runs before the person's own
236809
+ * allow rules, so a connector always reaches canUseTool (and its card) and a Read only chat cannot write whatever those
236810
+ * rules say. FloLess's own tools are left to their own approval.
236811
+ */
236812
+ async preToolUse(chat, readOnly2, hookInput) {
236813
+ const toolName = typeof hookInput?.tool_name === "string" ? hookInput.tool_name : "";
236814
+ const decide = (permissionDecision, permissionDecisionReason) => ({
236815
+ hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision, ...permissionDecisionReason ? { permissionDecisionReason } : {} }
236816
+ });
236817
+ if (this.isIntegrationTool(chat, toolName)) return {};
236818
+ if (toolName.startsWith("mcp__")) return decide("ask");
236819
+ if (!readOnly2) return {};
236820
+ return READ_ONLY_HOOK_TOOLS.has(toolName) ? decide("allow") : decide("deny", "This chat is read-only.");
236821
+ }
236578
236822
  async send({ chat, turn, prepared, callbacks }) {
236579
236823
  if (this.active.has(chat.chatId)) throw new Error("Claude chat already has an active turn");
236580
236824
  const payload = prepared && typeof prepared === "object" && prepared.provider === "claude" ? prepared : await this.prepare({ chat, turn });
@@ -237154,6 +237398,63 @@ var init_chat_provider_claude = __esm({
237154
237398
  });
237155
237399
 
237156
237400
  // chat-provider-codex.ts
237401
+ function connectorAskArgs(servers) {
237402
+ const args = ["-c", 'apps._default.default_tools_approval_mode="prompt"'];
237403
+ for (const name of [...servers].sort()) {
237404
+ if (CONNECTOR_SERVER_NAME.test(name)) args.push("-c", `mcp_servers.${name}.default_tools_approval_mode="prompt"`);
237405
+ }
237406
+ return args;
237407
+ }
237408
+ function codexConnectorMode(chat) {
237409
+ if (chat.integrationBindings.length > 0) return "isolated";
237410
+ return chat.settings.useOwnConnectors === true ? "asking" : "off";
237411
+ }
237412
+ function connectorProcessArgs(mode, servers) {
237413
+ if (mode === "asking") return [...connectorAskArgs(servers), "--disable", "plugins"];
237414
+ const args = mode === "isolated" ? ["--strict-config", "-c", "mcp_servers={}"] : [];
237415
+ for (const feature of DISABLED_CONNECTOR_FEATURES) args.push("--disable", feature);
237416
+ args.push("--disable", "plugins");
237417
+ for (const name of [...servers].sort()) {
237418
+ if (CONNECTOR_SERVER_NAME.test(name)) args.push("-c", `mcp_servers.${name}.enabled=false`);
237419
+ }
237420
+ return args;
237421
+ }
237422
+ function plainNotSent(message2) {
237423
+ return new ProviderNotSentError(message2, "plain");
237424
+ }
237425
+ function withTimeout(promise2, ms2) {
237426
+ return new Promise((resolve57, reject3) => {
237427
+ const timer = setTimeout(() => reject3(new Error("timed out")), ms2);
237428
+ promise2.then((value) => {
237429
+ clearTimeout(timer);
237430
+ resolve57(value);
237431
+ }, (error62) => {
237432
+ clearTimeout(timer);
237433
+ reject3(error62);
237434
+ });
237435
+ });
237436
+ }
237437
+ function connectorApprovalCall(params2, listedTools) {
237438
+ const meta3 = asObject(params2._meta);
237439
+ if (meta3.codex_approval_kind !== "mcp_tool_call") return null;
237440
+ const server = cleanText2(params2.serverName, 128);
237441
+ if (!server || !CONNECTOR_SERVER_NAME.test(server)) return { provider: "codex", server: "unknown", app: null, tool: "a tool", verified: false };
237442
+ const message2 = cleanText2(params2.message, 512);
237443
+ const named2 = /run tool "([^"]{1,200})"/u.exec(message2)?.[1] ?? "";
237444
+ const title = cleanText2(meta3.tool_title, 200);
237445
+ const tool = named2 || title;
237446
+ if (server === CODEX_APPS_SERVER) {
237447
+ const app = /^([A-Za-z0-9][A-Za-z0-9_-]{0,63})\.[^.]/u.exec(named2)?.[1] ?? null;
237448
+ return app && listedTools?.has(named2) ? { provider: "codex", server, app, tool: named2, verified: true } : app ? { provider: "codex", server, app, tool: named2, verified: false } : { provider: "codex", server, app: null, tool: tool || "a tool", verified: false };
237449
+ }
237450
+ return tool ? { provider: "codex", server, app: null, tool, verified: Boolean(named2) } : { provider: "codex", server, app: null, tool: "a tool", verified: false };
237451
+ }
237452
+ function connectorApprovalSummary(call, params2) {
237453
+ const meta3 = asObject(params2._meta);
237454
+ const shown2 = Array.isArray(meta3.tool_params_display) ? meta3.tool_params_display : [];
237455
+ const inputs = shown2.map((row2) => `${cleanText2(row2.display_name ?? row2.name, 80)}: ${cleanText2(typeof row2.value === "string" ? row2.value : JSON.stringify(row2.value), 200)}`).filter((line2) => line2.trim() !== ":").join("; ").slice(0, 600);
237456
+ return connectorApprovalQuestion(call, inputs);
237457
+ }
237157
237458
  function ownerInput5(chat) {
237158
237459
  return chatOwnerInput(chat.owner);
237159
237460
  }
@@ -237231,7 +237532,7 @@ function codexItemEvent(itemValue, sawDelta) {
237231
237532
  if (type === "contextCompaction") return { providerItemId: id2, type: "compaction", payload: { provider: "codex" } };
237232
237533
  return null;
237233
237534
  }
237234
- var import_node_child_process30, import_node_util14, import_node_readline3, import_node_fs159, execFile16, MAX_PROTOCOL_LINE, REQUEST_TIMEOUT_MS2, TURN_TIMEOUT_MS, CODEX_PROBE_TIMEOUT, ACCOUNT_CHANGED, STALLED, DISABLED_CONNECTOR_FEATURES, CodexChatProvider;
237535
+ var import_node_child_process30, import_node_util14, import_node_readline3, import_node_fs159, execFile16, MAX_PROTOCOL_LINE, REQUEST_TIMEOUT_MS2, TURN_TIMEOUT_MS, CODEX_PROBE_TIMEOUT, ACCOUNT_CHANGED, STALLED, DISABLED_CONNECTOR_FEATURES, CODEX_APPS_SERVER, CONNECTOR_SERVER_NAME, MCP_LIST_TIMEOUT_MS, PRIOR_EXIT_TIMEOUT_MS, PENDING_DRAIN_MS, CodexChatProvider;
237235
237536
  var init_chat_provider_codex = __esm({
237236
237537
  "chat-provider-codex.ts"() {
237237
237538
  "use strict";
@@ -237246,6 +237547,7 @@ var init_chat_provider_codex = __esm({
237246
237547
  init_chat_integration_tools();
237247
237548
  init_chat_evidence();
237248
237549
  init_chat_link_mcp();
237550
+ init_chat_connector_allowance();
237249
237551
  init_terminal_runtime();
237250
237552
  init_managed_runtime();
237251
237553
  init_chat_provider();
@@ -237257,27 +237559,46 @@ var init_chat_provider_codex = __esm({
237257
237559
  ACCOUNT_CHANGED = "Codex was restarted because the signed-in account changed. Send the message again.";
237258
237560
  STALLED = "Codex app-server stopped responding";
237259
237561
  DISABLED_CONNECTOR_FEATURES = ["apps", "enable_mcp_apps", "auth_elicitation", "remote_plugin", "plugin_sharing"];
237562
+ CODEX_APPS_SERVER = "codex_apps";
237563
+ CONNECTOR_SERVER_NAME = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/u;
237564
+ MCP_LIST_TIMEOUT_MS = 1e4;
237565
+ PRIOR_EXIT_TIMEOUT_MS = 5e3;
237566
+ PENDING_DRAIN_MS = 1e4;
237260
237567
  CodexChatProvider = class {
237261
237568
  constructor(spawnProcess = (file2, args, options2) => (0, import_node_child_process30.spawn)(file2, [...args], {
237262
237569
  ...options2,
237263
237570
  stdio: ["pipe", "pipe", "pipe"],
237264
237571
  windowsHide: true
237265
- }), runtimeProbe = probeCodexRuntime, capabilityProbeTimeoutMs = CAPABILITY_PROBE_TIMEOUT_MS, stopSettleMs = STOP_SETTLE_MS) {
237572
+ }), runtimeProbe = probeCodexRuntime, capabilityProbeTimeoutMs = CAPABILITY_PROBE_TIMEOUT_MS, stopSettleMs = STOP_SETTLE_MS, priorExitTimeoutMs = PRIOR_EXIT_TIMEOUT_MS, pendingDrainMs = PENDING_DRAIN_MS) {
237266
237573
  this.spawnProcess = spawnProcess;
237267
237574
  this.runtimeProbe = runtimeProbe;
237268
237575
  this.capabilityProbeTimeoutMs = capabilityProbeTimeoutMs;
237269
237576
  this.stopSettleMs = stopSettleMs;
237577
+ this.priorExitTimeoutMs = priorExitTimeoutMs;
237578
+ this.pendingDrainMs = pendingDrainMs;
237270
237579
  }
237271
237580
  spawnProcess;
237272
237581
  runtimeProbe;
237273
237582
  capabilityProbeTimeoutMs;
237274
237583
  stopSettleMs;
237584
+ priorExitTimeoutMs;
237585
+ pendingDrainMs;
237275
237586
  provider = "codex";
237276
237587
  child = null;
237277
237588
  sequence = 0;
237278
237589
  generation = 0;
237279
237590
  initialized = false;
237280
- connectorIsolation = null;
237591
+ connectorMode = null;
237592
+ processStarts = Promise.resolve();
237593
+ /** #1907: settles when the app-server last told to close has exited; null when none is closing. */
237594
+ closing = null;
237595
+ closed = false;
237596
+ /** #1907: the person's own MCP servers, as the latest connector listing named them: each must ask, or be switched off. */
237597
+ ownServers = /* @__PURE__ */ new Set();
237598
+ /** #1907: the servers the RUNNING app-server was started with; only a successful start changes it. */
237599
+ appliedServers = /* @__PURE__ */ new Set();
237600
+ /** #1907: every tool name each server listed, so an app identity is only trusted when Codex itself listed the tool. */
237601
+ listedTools = /* @__PURE__ */ new Map();
237281
237602
  pending = /* @__PURE__ */ new Map();
237282
237603
  activeByThread = /* @__PURE__ */ new Map();
237283
237604
  pendingApprovals = /* @__PURE__ */ new Map();
@@ -237298,30 +237619,83 @@ var init_chat_provider_codex = __esm({
237298
237619
  async version() {
237299
237620
  return this.runtimeProbe();
237300
237621
  }
237301
- async ensureProcess(cwd, isolateNativeConnectors = false) {
237622
+ /**
237623
+ * #1907: before a turn, every MCP server the person has must be one this process asks about (`asking`) or has
237624
+ * switched off (`off`, `isolated`). A server added since the process started restarts it (idle only —
237625
+ * ensureProcess refuses mid-turn) with the server included. Then the listing itself is the proof: a turn never runs
237626
+ * while one of the person's connectors has tools it should not.
237627
+ */
237628
+ async ensureConnectors(cwd, mode) {
237629
+ await this.ensureProcess(cwd, mode);
237630
+ for (let attempt2 = 0; attempt2 < 2 && await this.listOwnServers(); attempt2 += 1) {
237631
+ await this.ensureProcess(cwd, mode, { restart: true });
237632
+ }
237633
+ for (const [name, tools] of this.listedTools) {
237634
+ if (!tools.size || name === LINK_TOOL_MCP_SERVER) continue;
237635
+ if (mode === "asking" && (name === CODEX_APPS_SERVER || this.appliedServers.has(name))) continue;
237636
+ throw plainNotSent(mode === "asking" ? `FloLess could not make your Codex connector "${name.slice(0, 64)}" ask before it runs, so this message was not sent. Send it again.` : `FloLess could not keep your own Codex connector "${name.slice(0, 64)}" out of this chat, so this message was not sent. Send it again.`);
237637
+ }
237638
+ }
237639
+ /**
237640
+ * One start or restart at a time: a restart waits for the old app-server to exit, and a second caller arriving in that
237641
+ * wait (a capability check, another chat) must not find no process and start its own beside it (#1907).
237642
+ */
237643
+ ensureProcess(cwd, mode = "off", options2 = {}) {
237644
+ const run2 = this.processStarts.then(() => this.ensureProcessNow(cwd, mode, options2));
237645
+ this.processStarts = run2.catch(() => void 0);
237646
+ return run2;
237647
+ }
237648
+ /**
237649
+ * Every app-server FloLess stops goes through here, so the next start can wait for it: it holds the Codex state
237650
+ * database until it has exited (#1907).
237651
+ */
237652
+ stopProcess(prior) {
237653
+ const exited = typeof prior.exitCode === "number" || Boolean(prior.signalCode) ? Promise.resolve() : new Promise((resolve57) => {
237654
+ prior.once("exit", () => resolve57());
237655
+ });
237656
+ const closing = exited.then(() => {
237657
+ if (this.closing === closing) this.closing = null;
237658
+ });
237659
+ this.closing = closing;
237660
+ prior.stdin.end();
237661
+ prior.kill();
237662
+ return closing;
237663
+ }
237664
+ /** Never starts a second app-server beside one still closing: the message is not sent instead, and the next one waits again. */
237665
+ async awaitClosed(closing) {
237666
+ try {
237667
+ await withTimeout(closing, this.priorExitTimeoutMs);
237668
+ } catch {
237669
+ console.warn("[chat] the previous Codex app-server has not closed yet; this message was not sent");
237670
+ throw plainNotSent("Codex is still closing from an earlier step, so this message was not sent. Wait a moment, then send it again.");
237671
+ }
237672
+ }
237673
+ async ensureProcessNow(cwd, mode, options2) {
237674
+ if (this.closed) throw plainNotSent("FloLess is closing AI Chat, so this message was not sent.");
237302
237675
  this.drainPendingRelease({ force: true });
237303
- if (this.child && this.initialized && !this.child.killed && this.connectorIsolation === isolateNativeConnectors) return;
237676
+ if (this.child && this.initialized && !this.child.killed && this.connectorMode === mode && !options2.restart) return;
237677
+ if (this.closing) await this.awaitClosed(this.closing);
237304
237678
  if (this.child && !this.child.killed) {
237679
+ for (const until = Date.now() + this.pendingDrainMs; !this.activeByThread.size && this.pending.size && Date.now() < until; ) {
237680
+ await new Promise((resolve57) => setTimeout(resolve57, 25));
237681
+ }
237305
237682
  if (this.activeByThread.size || this.pending.size) {
237306
- throw new Error("Finish the active Codex chat before changing its integration routing.");
237683
+ throw plainNotSent("Another Codex chat is still working, and this chat uses your connectors differently. Wait for it to finish, then send this message again.");
237307
237684
  }
237308
237685
  const prior = this.child;
237309
237686
  this.child = null;
237310
237687
  this.initialized = false;
237311
- this.connectorIsolation = null;
237688
+ this.connectorMode = null;
237312
237689
  this.generation += 1;
237313
- prior.stdin.end();
237314
- prior.kill();
237690
+ await this.awaitClosed(this.stopProcess(prior));
237315
237691
  }
237316
237692
  const { binary, env: runtimeEnv } = await this.version();
237317
237693
  const args = ["app-server", "--stdio"];
237318
- if (isolateNativeConnectors) {
237319
- args.push("--strict-config", "-c", "mcp_servers={}");
237320
- for (const feature of DISABLED_CONNECTOR_FEATURES) args.push("--disable", feature);
237321
- }
237694
+ args.push(...connectorProcessArgs(mode, this.ownServers));
237695
+ const startedWith = new Set(this.ownServers);
237322
237696
  const child = this.spawnProcess(binary, args, { cwd, env: runtimeEnv ? runtimeEnv({ ...process.env }) : { ...process.env }, windowsHide: true });
237323
237697
  this.child = child;
237324
- this.connectorIsolation = isolateNativeConnectors;
237698
+ this.connectorMode = mode;
237325
237699
  this.generation += 1;
237326
237700
  const processGeneration = this.generation;
237327
237701
  this.initialized = false;
@@ -237337,9 +237711,51 @@ var init_chat_provider_codex = __esm({
237337
237711
  });
237338
237712
  this.notify("initialized");
237339
237713
  this.initialized = true;
237714
+ this.appliedServers = startedWith;
237715
+ }
237716
+ /**
237717
+ * #1907: adds every listed MCP server that this process was not started asking for, and says whether any was added
237718
+ * (the caller restarts the idle process). Servers a Codex plugin provides cannot take the setting (it defines an
237719
+ * invalid server) — their tools without a read-only label still ask through the elicitation below; a tool that labels
237720
+ * itself read-only can run unasked (carve-out, #1907). A listing that fails leaves the process as it is, logged: the
237721
+ * apps default still applies and nothing is hidden from the person.
237722
+ */
237723
+ async listOwnServers() {
237724
+ let servers = [];
237725
+ try {
237726
+ let cursor = null;
237727
+ for (let page = 0; page < 20; page += 1) {
237728
+ const listed = asObject(await withTimeout(this.request("mcpServerStatus/list", cursor ? { cursor } : {}), MCP_LIST_TIMEOUT_MS));
237729
+ servers = servers.concat(Array.isArray(listed.data) ? listed.data : []);
237730
+ cursor = typeof listed.nextCursor === "string" && listed.nextCursor ? listed.nextCursor : null;
237731
+ if (!cursor) break;
237732
+ }
237733
+ if (cursor) throw new Error("the connector listing did not end");
237734
+ } catch (error62) {
237735
+ console.warn("[chat] Codex did not list its connectors:", error62);
237736
+ throw plainNotSent("FloLess could not check your Codex connectors, so this message was not sent. Send it again.");
237737
+ }
237738
+ const next = /* @__PURE__ */ new Set();
237739
+ const tools = /* @__PURE__ */ new Map();
237740
+ for (const server of servers) {
237741
+ const listedName = typeof server.name === "string" ? server.name : "";
237742
+ const toolNames = Object.keys(asObject(server.tools));
237743
+ if (listedName) tools.set(listedName, new Set(toolNames));
237744
+ }
237745
+ this.listedTools = tools;
237746
+ for (const server of servers) {
237747
+ const name = typeof server.name === "string" ? server.name : "";
237748
+ if (!name || name === CODEX_APPS_SERVER || name === LINK_TOOL_MCP_SERVER || typeof server.pluginId === "string" && server.pluginId) continue;
237749
+ if (!CONNECTOR_SERVER_NAME.test(name)) {
237750
+ throw plainNotSent(`Codex has a connector named "${name.slice(0, 64)}" that FloLess cannot switch off or set to ask before it runs. Rename it in your Codex settings, then send your message again.`);
237751
+ }
237752
+ next.add(name);
237753
+ }
237754
+ this.ownServers = next;
237755
+ return next.size !== this.appliedServers.size || [...next].some((name) => !this.appliedServers.has(name));
237340
237756
  }
237341
237757
  async prepare({ chat, turn }) {
237342
- await this.ensureProcess(chat.cwd, chat.integrationBindings.length > 0);
237758
+ await this.ensureProcess(chat.cwd, codexConnectorMode(chat));
237343
237759
  const inputs = [];
237344
237760
  let promptText = turn.text;
237345
237761
  const slash = promptText.match(/^\/([A-Za-z0-9:_-]+)(?:\s+|$)/u);
@@ -237378,14 +237794,18 @@ Read this local project attachment when it is relevant to the request. To see a
237378
237794
  } else inputs.push({ type: "text", text: `Attached PDF: ${path}
237379
237795
  Read this local project attachment when it is relevant to the request.` });
237380
237796
  }
237797
+ const mode = codexConnectorMode(chat);
237798
+ if (mode !== "isolated") {
237799
+ inputs.push({ type: "text", text: mode === "asking" ? "FloLess note: the person turned on their own Codex connectors for this conversation; each call asks them first." : `FloLess note: ${OWN_CONNECTORS_OFF_ROUTING("Codex")}` });
237800
+ }
237381
237801
  const threadId = await this.ensureThread(chat, turn);
237382
- return { provider: "codex", threadId, inputs };
237802
+ return { provider: "codex", threadId, inputs, generation: this.generation, connectorMode: this.connectorMode };
237383
237803
  }
237384
237804
  failProcess(error62, generation) {
237385
237805
  if (generation !== this.generation) return;
237386
237806
  this.initialized = false;
237387
237807
  this.child = null;
237388
- this.connectorIsolation = null;
237808
+ this.connectorMode = null;
237389
237809
  for (const entry2 of this.pending.values()) {
237390
237810
  clearTimeout(entry2.timer);
237391
237811
  entry2.reject(error62);
@@ -237433,7 +237853,7 @@ Read this local project attachment when it is relevant to the request.` });
237433
237853
  }
237434
237854
  receiveLine(line2, generation) {
237435
237855
  if (generation !== this.generation || Buffer.byteLength(line2, "utf8") > MAX_PROTOCOL_LINE) {
237436
- if (generation === this.generation) this.child?.kill();
237856
+ if (generation === this.generation && this.child) void this.stopProcess(this.child);
237437
237857
  return;
237438
237858
  }
237439
237859
  let message2;
@@ -237475,7 +237895,7 @@ Read this local project attachment when it is relevant to the request.` });
237475
237895
  async handleServerRequest(id2, method, params2, generation) {
237476
237896
  const active2 = this.active(params2);
237477
237897
  if (!active2) {
237478
- this.write({ id: id2, result: { decision: "decline" } });
237898
+ this.write({ id: id2, result: method === "mcpServer/elicitation/request" ? { action: "decline", content: null, _meta: null } : { decision: "decline" } });
237479
237899
  return;
237480
237900
  }
237481
237901
  if (!active2.turnId) {
@@ -237511,6 +237931,37 @@ Read this local project attachment when it is relevant to the request.` });
237511
237931
  }
237512
237932
  return;
237513
237933
  }
237934
+ if (method === "mcpServer/elicitation/request" && codexConnectorMode(active2.chat) !== "asking") {
237935
+ this.write({ id: id2, result: { action: "decline", content: null, _meta: null } });
237936
+ await active2.callbacks.onEvent({ type: "tool", payload: {
237937
+ tool: "provider",
237938
+ status: "error",
237939
+ message: "A connector asked to run in this chat while your Codex connectors are off, so it was declined."
237940
+ } });
237941
+ return;
237942
+ }
237943
+ if (method === "mcpServer/elicitation/request") {
237944
+ const call = connectorApprovalCall(params2, this.listedTools.get(cleanText2(params2.serverName, 128)));
237945
+ if (!call) {
237946
+ this.write({ id: id2, result: { action: "decline", content: null, _meta: null } });
237947
+ const server = cleanText2(params2.serverName, 128) || "A connector";
237948
+ await active2.callbacks.onEvent({ type: "tool", payload: {
237949
+ tool: "provider",
237950
+ status: "error",
237951
+ message: `${server} asked for something FloLess can't show here, so it was declined.`
237952
+ } });
237953
+ return;
237954
+ }
237955
+ const nativeRequestId2 = `${generation}:connector:${String(id2)}`;
237956
+ this.pendingApprovals.set(nativeRequestId2, { kind: "connector", processGeneration: generation, id: id2 });
237957
+ try {
237958
+ await active2.callbacks.onApproval({ nativeRequestId: nativeRequestId2, summary: connectorApprovalSummary(call, params2), explicitOnly: true, connector: call });
237959
+ } catch {
237960
+ this.pendingApprovals.delete(nativeRequestId2);
237961
+ this.write({ id: id2, result: { action: "decline", content: null, _meta: null } });
237962
+ }
237963
+ return;
237964
+ }
237514
237965
  if (!["item/commandExecution/requestApproval", "item/fileChange/requestApproval"].includes(method)) {
237515
237966
  this.write({ id: id2, result: { decision: "decline" } });
237516
237967
  return;
@@ -237560,8 +238011,9 @@ Read this local project attachment when it is relevant to the request.` });
237560
238011
  }
237561
238012
  }
237562
238013
  async ensureThread(chat, turn) {
237563
- await this.ensureProcess(chat.cwd, chat.integrationBindings.length > 0);
237564
- const integrationRouting = chat.integrationBindings.length ? " This chat selected one or more FloLess integration accounts. Use only the floless_* dynamic tools for those services. If a FloLess integration call fails, report that failure; do not try another account, connector, browser, shell, or web route." : " No FloLess integration account is selected; the user\u2019s normal Codex connectors remain available.";
238014
+ const mode = codexConnectorMode(chat);
238015
+ await this.ensureConnectors(chat.cwd, mode);
238016
+ const integrationRouting = mode === "isolated" ? " This chat selected one or more FloLess integration accounts. Use only the floless_* dynamic tools for those services. If a FloLess integration call fails, report that failure; do not try another account, connector, browser, shell, or web route." : mode === "asking" ? " No FloLess integration account is selected; the user turned on their own Codex connectors for this chat, and each call asks them first." : ` No FloLess integration account is selected. ${OWN_CONNECTORS_OFF_ROUTING("Codex")}`;
237565
238017
  const teklaRoutingText = chat.teklaModelRead ? ` ${teklaRouting(chat.teklaModelRead)}` : "";
237566
238018
  const linkServers = this.linkTool?.configFor(chat) ?? null;
237567
238019
  const params2 = {
@@ -237595,6 +238047,9 @@ Read this local project attachment when it is relevant to the request.` });
237595
238047
  async send({ chat, turn, prepared, callbacks }) {
237596
238048
  const payload = prepared && typeof prepared === "object" && prepared.provider === "codex" ? prepared : await this.prepare({ chat, turn });
237597
238049
  const { threadId, inputs } = payload;
238050
+ if (payload.generation !== this.generation || payload.connectorMode !== codexConnectorMode(chat) || this.connectorMode !== payload.connectorMode) {
238051
+ throw plainNotSent("Codex was restarted for another chat just before this message went out, so it was not sent. Send it again.");
238052
+ }
237598
238053
  if (this.activeByThread.has(threadId)) throw new Error("Codex thread already has an active turn");
237599
238054
  let active2;
237600
238055
  let resolveProviderTurnStarted;
@@ -237710,7 +238165,7 @@ Read this local project attachment when it is relevant to the request.` });
237710
238165
  let threadId = chat.nativeSessionId ?? active2?.threadId;
237711
238166
  const providerTurnId = turn.providerTurnId ?? active2?.turnId ?? await active2?.providerTurnStarted;
237712
238167
  if (!threadId || !providerTurnId) throw new Error("Codex turn identity is unavailable");
237713
- await this.ensureProcess(chat.cwd, chat.integrationBindings.length > 0);
238168
+ await this.ensureProcess(chat.cwd, codexConnectorMode(chat));
237714
238169
  if (!active2) threadId = await this.ensureThread(chat, turn);
237715
238170
  try {
237716
238171
  await this.request("turn/interrupt", { threadId, turnId: providerTurnId });
@@ -237749,6 +238204,10 @@ Read this local project attachment when it is relevant to the request.` });
237749
238204
  this.write({ id: pending2.id, result: { contentItems: [{ type: "inputText", text: result2.text }], success: result2.success } });
237750
238205
  return;
237751
238206
  }
238207
+ if (pending2.kind === "connector") {
238208
+ this.write({ id: pending2.id, result: decision === "allow" ? { action: "accept", content: {}, _meta: null } : { action: "decline", content: null, _meta: null } });
238209
+ return;
238210
+ }
237752
238211
  this.write({ id: pending2.id, result: { decision: decision === "allow" ? "accept" : "decline" } });
237753
238212
  }
237754
238213
  async reconcile({ chat, turn }) {
@@ -237813,7 +238272,7 @@ Read this local project attachment when it is relevant to the request.` });
237813
238272
  const { version: version2, managed } = await this.version();
237814
238273
  probe.managed = managed === true;
237815
238274
  if (probe.abandoned) throw new Error(CODEX_PROBE_TIMEOUT);
237816
- await this.ensureProcess(cwd, this.connectorIsolation ?? false);
238275
+ await this.ensureProcess(cwd, this.connectorMode ?? "off");
237817
238276
  const [accountValue, modelsValue, skillsValue] = await Promise.all([
237818
238277
  this.request("account/read", { refreshToken: false }),
237819
238278
  this.request("model/list", {}),
@@ -237878,8 +238337,7 @@ Read this local project attachment when it is relevant to the request.` });
237878
238337
  this.pendingRelease = null;
237879
238338
  this.failProcess(new Error(reason), this.generation);
237880
238339
  this.generation += 1;
237881
- child.stdin.end();
237882
- child.kill();
238340
+ void this.stopProcess(child);
237883
238341
  }
237884
238342
  /**
237885
238343
  * Carries out a release `releaseIdle` could not do at the time. Called from every path where the
@@ -237930,7 +238388,7 @@ Read this local project attachment when it is relevant to the request.` });
237930
238388
  if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(limit) || limit < 1 || limit > 500) {
237931
238389
  throw new Error("invalid Codex history cursor");
237932
238390
  }
237933
- await this.ensureProcess(chat.cwd, chat.integrationBindings.length > 0);
238391
+ await this.ensureProcess(chat.cwd, codexConnectorMode(chat));
237934
238392
  const result2 = asObject(await this.request("thread/read", { threadId: chat.nativeSessionId, includeTurns: true }));
237935
238393
  const turns = asObject(result2.thread).turns;
237936
238394
  const all = [];
@@ -237957,16 +238415,15 @@ Read this local project attachment when it is relevant to the request.` });
237957
238415
  return { items, nextCursor: offset + items.length < all.length ? String(offset + items.length) : null };
237958
238416
  }
237959
238417
  async close() {
238418
+ this.closed = true;
237960
238419
  for (const active2 of this.activeByThread.values()) active2.abortController.abort();
238420
+ await this.processStarts;
237961
238421
  const child = this.child;
237962
238422
  this.child = null;
237963
238423
  this.initialized = false;
237964
- this.connectorIsolation = null;
238424
+ this.connectorMode = null;
237965
238425
  this.generation += 1;
237966
- if (child && !child.killed) {
237967
- child.stdin.end();
237968
- child.kill();
237969
- }
238426
+ if (child && !child.killed) void this.stopProcess(child);
237970
238427
  }
237971
238428
  };
237972
238429
  }
@@ -238474,7 +238931,7 @@ async function resolveChatIntegrationBinding(input2) {
238474
238931
  "chat-integration-not-runnable"
238475
238932
  );
238476
238933
  }
238477
- if (!UUID31.test(credential.binding_id) || !Number.isSafeInteger(credential.revision) || credential.revision < 1 || !UUID31.test(credential.credential_generation)) {
238934
+ if (!UUID32.test(credential.binding_id) || !Number.isSafeInteger(credential.revision) || credential.revision < 1 || !UUID32.test(credential.credential_generation)) {
238478
238935
  throw new ChatIntegrationPolicyError(
238479
238936
  "The selected account binding is incomplete.",
238480
238937
  409,
@@ -238519,11 +238976,11 @@ async function revalidateChatIntegrationBinding(input2) {
238519
238976
  }
238520
238977
  return capability;
238521
238978
  }
238522
- var UUID31, SHA25621, SUPPORTED_CHAT_INTEGRATIONS, ChatIntegrationPolicyError;
238979
+ var UUID32, SHA25621, SUPPORTED_CHAT_INTEGRATIONS, ChatIntegrationPolicyError;
238523
238980
  var init_chat_integration_policy = __esm({
238524
238981
  "chat-integration-policy.ts"() {
238525
238982
  "use strict";
238526
- UUID31 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
238983
+ UUID32 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
238527
238984
  SHA25621 = /^[0-9a-f]{64}$/;
238528
238985
  SUPPORTED_CHAT_INTEGRATIONS = Object.freeze([
238529
238986
  Object.freeze({
@@ -238559,7 +239016,7 @@ function intakeRoot() {
238559
239016
  return (0, import_node_path155.join)(process.env.FLOLESS_HOME ?? (0, import_node_path155.join)((0, import_node_os76.homedir)(), ".floless"), "project-chat-intakes");
238560
239017
  }
238561
239018
  function intakeDir(submissionId) {
238562
- if (!UUID32.test(submissionId)) throw new ProjectChatIntakeError("project intake submission identity is invalid");
239019
+ if (!UUID33.test(submissionId)) throw new ProjectChatIntakeError("project intake submission identity is invalid");
238563
239020
  return (0, import_node_path155.join)(intakeRoot(), submissionId);
238564
239021
  }
238565
239022
  function recordPath2(submissionId) {
@@ -238585,10 +239042,10 @@ function readProjectChatIntake(submissionId) {
238585
239042
  const root11 = destination?.root;
238586
239043
  const projectInput = value.projectInput;
238587
239044
  const snapshots = value.snapshots;
238588
- const idsValid = (value.projectId === void 0 || typeof value.projectId === "string" && isProjectId(value.projectId)) && [value.requestId, value.chatId, value.turnId].every((id2) => id2 === void 0 || typeof id2 === "string" && UUID32.test(id2));
239045
+ const idsValid = (value.projectId === void 0 || typeof value.projectId === "string" && isProjectId(value.projectId)) && [value.requestId, value.chatId, value.turnId].every((id2) => id2 === void 0 || typeof id2 === "string" && UUID33.test(id2));
238589
239046
  const stateValid = value.state === "staged" ? !value.projectId && !value.requestId && !value.chatId && !value.turnId : value.state === "project-created" ? !!value.projectId && !value.requestId && !value.chatId && !value.turnId : value.state === "request-created" ? !!value.projectId && !!value.requestId && !value.chatId && !value.turnId : value.state === "accepted" && !!value.projectId && !!value.requestId && !!value.chatId && !!value.turnId;
238590
239047
  const snapshotShape = Array.isArray(snapshots) && snapshots.length >= 1 && snapshots.length <= 8 && snapshots.every((snapshot2, index) => snapshot2 && typeof snapshot2 === "object" && typeof snapshot2.name === "string" && snapshot2.name.length > 0 && snapshot2.name.length <= 512 && typeof snapshot2.ext === "string" && SNAPSHOT_EXTENSIONS.has(snapshot2.ext) && (snapshot2.role === "reference" || snapshot2.role === "locator") && typeof snapshot2.sha256 === "string" && SHA25622.test(snapshot2.sha256) && snapshot2.file === `source-${index + 1}.${snapshot2.ext}`);
238591
- if (value.version !== 1 || value.submissionId !== submissionId || !UUID32.test(value.submissionId) || !["codex", "claude"].includes(value.provider) || !SHA25622.test(value.fingerprint) || typeof value.createdAt !== "string" || !Number.isFinite(Date.parse(value.createdAt)) || typeof value.updatedAt !== "string" || !Number.isFinite(Date.parse(value.updatedAt)) || !projectInput || typeof projectInput.name !== "string" || !projectInput.name.trim() || typeof projectInput.app !== "string" || !/^[a-z0-9][a-z0-9._-]*$/iu.test(projectInput.app) || !destination || typeof destination.selectionId !== "string" || !UUID32.test(destination.selectionId) || !root11 || typeof root11.rootId !== "string" || !UUID32.test(root11.rootId) || !Number.isSafeInteger(root11.generation) || root11.generation < 1 || typeof root11.path !== "string" || !(0, import_node_path155.isAbsolute)(root11.path) || typeof root11.filesystemId !== "string" || !root11.filesystemId || typeof destination.locator !== "string" || !isProjectLocator(destination.locator) || typeof destination.directory !== "string" || !(0, import_node_path155.isAbsolute)(destination.directory) || !Number.isSafeInteger(destination.existingItems) || (destination.existingItems ?? -1) < 0 || typeof destination.expiresAt !== "number" || !Number.isFinite(destination.expiresAt) || !identity4 || !["dev", "ino", "birthtimeNs", "ctimeNs"].every((key5) => /^\d+$/u.test(identity4[key5] ?? "")) || !snapshotShape || !idsValid || !stateValid) {
239048
+ if (value.version !== 1 || value.submissionId !== submissionId || !UUID33.test(value.submissionId) || !["codex", "claude"].includes(value.provider) || !SHA25622.test(value.fingerprint) || typeof value.createdAt !== "string" || !Number.isFinite(Date.parse(value.createdAt)) || typeof value.updatedAt !== "string" || !Number.isFinite(Date.parse(value.updatedAt)) || !projectInput || typeof projectInput.name !== "string" || !projectInput.name.trim() || typeof projectInput.app !== "string" || !/^[a-z0-9][a-z0-9._-]*$/iu.test(projectInput.app) || !destination || typeof destination.selectionId !== "string" || !UUID33.test(destination.selectionId) || !root11 || typeof root11.rootId !== "string" || !UUID33.test(root11.rootId) || !Number.isSafeInteger(root11.generation) || root11.generation < 1 || typeof root11.path !== "string" || !(0, import_node_path155.isAbsolute)(root11.path) || typeof root11.filesystemId !== "string" || !root11.filesystemId || typeof destination.locator !== "string" || !isProjectLocator(destination.locator) || typeof destination.directory !== "string" || !(0, import_node_path155.isAbsolute)(destination.directory) || !Number.isSafeInteger(destination.existingItems) || (destination.existingItems ?? -1) < 0 || typeof destination.expiresAt !== "number" || !Number.isFinite(destination.expiresAt) || !identity4 || !["dev", "ino", "birthtimeNs", "ctimeNs"].every((key5) => /^\d+$/u.test(identity4[key5] ?? "")) || !snapshotShape || !idsValid || !stateValid) {
238592
239049
  throw new ProjectChatIntakeError("the saved project intake has an invalid shape", 409, "project-intake-damaged");
238593
239050
  }
238594
239051
  return value;
@@ -238740,7 +239197,7 @@ function createInitialRequest(record7, project) {
238740
239197
  }
238741
239198
  }
238742
239199
  async function prepareProjectChatIntake(submissionId, input2, seams = {}) {
238743
- if (!UUID32.test(submissionId)) throw new ProjectChatIntakeError("project intake submission identity is invalid");
239200
+ if (!UUID33.test(submissionId)) throw new ProjectChatIntakeError("project intake submission identity is invalid");
238744
239201
  let record7 = readProjectChatIntake(submissionId);
238745
239202
  if (!record7) {
238746
239203
  if (!input2) throw new ProjectChatIntakeError("project intake was not found", 404, "project-intake-not-found");
@@ -238809,7 +239266,7 @@ function completeProjectChatIntake(submissionId, chatId, turnId) {
238809
239266
  }
238810
239267
  return completed;
238811
239268
  }
238812
- var import_node_crypto133, import_node_fs161, import_node_os76, import_node_path155, UUID32, SHA25622, SNAPSHOT_EXTENSIONS, ProjectChatIntakeError;
239269
+ var import_node_crypto133, import_node_fs161, import_node_os76, import_node_path155, UUID33, SHA25622, SNAPSHOT_EXTENSIONS, ProjectChatIntakeError;
238813
239270
  var init_project_chat_intake = __esm({
238814
239271
  "project-chat-intake.ts"() {
238815
239272
  "use strict";
@@ -238828,7 +239285,7 @@ var init_project_chat_intake = __esm({
238828
239285
  init_projects_store();
238829
239286
  init_project_sources_store();
238830
239287
  init_revision_agent_scratch();
238831
- UUID32 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
239288
+ UUID33 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
238832
239289
  SHA25622 = /^[0-9a-f]{64}$/u;
238833
239290
  SNAPSHOT_EXTENSIONS = /* @__PURE__ */ new Set(["png", "jpg", "webp", "pdf"]);
238834
239291
  ProjectChatIntakeError = class extends Error {
@@ -239700,10 +240157,15 @@ function registerChatRoutes(app, supplied) {
239700
240157
  if (body.effort !== null && (!chosenModel || !chosenModel.efforts.includes(body.effort))) {
239701
240158
  throw new ChatStoreError("chat effort is not offered for this model");
239702
240159
  }
240160
+ if (body.useOwnConnectors !== void 0 && typeof body.useOwnConnectors !== "boolean") {
240161
+ throw new ChatStoreError("FloLess could not tell whether to use your connectors in this chat. Choose the switch again.", 400, "chat-settings-invalid");
240162
+ }
239703
240163
  const updated = await updateChatSettings(owner3, chatId, {
239704
240164
  model: body.model,
239705
240165
  effort: body.effort,
239706
- permissionProfile: body.permissionProfile
240166
+ permissionProfile: body.permissionProfile,
240167
+ // #1907: a settings change that does not mention the switch keeps it as it was.
240168
+ useOwnConnectors: body.useOwnConnectors ?? chat.settings.useOwnConnectors === true
239707
240169
  });
239708
240170
  supplied.providers.closeConversation?.(chatId, "settings-changed");
239709
240171
  supplied.providers.warm?.(updated);
@@ -240146,6 +240608,21 @@ function registerChatRoutes(app, supplied) {
240146
240608
  routeError(error62, reply);
240147
240609
  }
240148
240610
  });
240611
+ app.post("/api/chat/conversations/:chatId/connector-allowance/revoke", { bodyLimit: 16 * 1024 }, async (request, reply) => {
240612
+ try {
240613
+ requireSession(request, token2, session, true);
240614
+ const body = request.body;
240615
+ const connector = body.connector === void 0 || body.connector === null ? null : parseConnectorIdentity(body.connector);
240616
+ if (body.connector !== void 0 && body.connector !== null && !connector) {
240617
+ throw new ChatStoreError("FloLess could not tell which connector to stop allowing. Refresh the conversation and choose Revoke again.", 400, "chat-connector-invalid");
240618
+ }
240619
+ const chat = await revokeChatConnectorAllowance(ownerFrom(body.owner), chatIdFrom(request), connector);
240620
+ app.log.info({ chatId: chat.chatId, revision: chat.connectorAllowance?.revision ?? 0 }, "chat connector allowance revoked");
240621
+ reply.send({ revoked: true, chat });
240622
+ } catch (error62) {
240623
+ routeError(error62, reply);
240624
+ }
240625
+ });
240149
240626
  return { sessionToken: token2, eventStream: stream };
240150
240627
  }
240151
240628
  var import_node_crypto134, import_node_fs162, MAX_JSON_BODY, PREFERRED_MODELS, FILTER_SNAPSHOT_BODY, TURN_BODY_LIMIT, ChatEventStream;
@@ -240153,6 +240630,7 @@ var init_chat_routes = __esm({
240153
240630
  "chat-routes.ts"() {
240154
240631
  "use strict";
240155
240632
  import_node_crypto134 = require("node:crypto");
240633
+ init_chat_connector_allowance();
240156
240634
  import_node_fs162 = require("node:fs");
240157
240635
  init_app_stop();
240158
240636
  init_chat_subjects();
@@ -240763,7 +241241,7 @@ function positiveBoundedInteger(value, fallback2, maximum) {
240763
241241
  }
240764
241242
  return result2;
240765
241243
  }
240766
- var import_node_crypto135, UUID33, INPUT_NAME, MAX_INPUTS, ChatIntegrationRelay;
241244
+ var import_node_crypto135, UUID34, INPUT_NAME, MAX_INPUTS, ChatIntegrationRelay;
240767
241245
  var init_chat_integration_relay = __esm({
240768
241246
  "chat-integration-relay.ts"() {
240769
241247
  "use strict";
@@ -240771,7 +241249,7 @@ var init_chat_integration_relay = __esm({
240771
241249
  init_aware_adapter();
240772
241250
  init_chat_store();
240773
241251
  init_chat_integration_policy();
240774
- UUID33 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
241252
+ UUID34 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
240775
241253
  INPUT_NAME = /^[A-Za-z][A-Za-z0-9_-]{0,127}$/u;
240776
241254
  MAX_INPUTS = 32;
240777
241255
  ChatIntegrationRelay = class {
@@ -240782,7 +241260,7 @@ var init_chat_integration_relay = __esm({
240782
241260
  providers;
240783
241261
  runtime;
240784
241262
  async invoke(input2) {
240785
- if (!UUID33.test(input2.chatId) || !UUID33.test(input2.turnId) || !UUID33.test(input2.invocationId) || !UUID33.test(input2.approvalReceiptId)) {
241263
+ if (!UUID34.test(input2.chatId) || !UUID34.test(input2.turnId) || !UUID34.test(input2.invocationId) || !UUID34.test(input2.approvalReceiptId)) {
240786
241264
  throw new ChatIntegrationPolicyError("Integration call identity is invalid.", 400, "chat-integration-identity-invalid");
240787
241265
  }
240788
241266
  const chat = readChat(input2.owner, input2.chatId);