glove-foundry 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -11,11 +11,13 @@ import {
11
11
  EMPTY_FOUNDRY_APPLICATION,
12
12
  FOUNDRY_APPROVAL_DIRECTORY_ENV,
13
13
  FOUNDRY_APPROVAL_POLICY_ENV,
14
+ FOUNDRY_BUILTINS_MOUNTED_EVENT,
14
15
  FOUNDRY_CORE_COMMAND_EVENT,
15
16
  FOUNDRY_MODEL_REQUESTS_ENV,
16
17
  MemoryFoundryDataAdapter,
17
18
  TERMINAL_OCCURRENCE_STATUSES,
18
19
  activationScheduleRevision,
20
+ builtinsForCommand,
19
21
  compareOccurrences,
20
22
  createAgentInstance,
21
23
  createConversation,
@@ -27,6 +29,7 @@ import {
27
29
  foundryApprovalSuspended,
28
30
  freezeGloveMessage,
29
31
  id,
32
+ isFoundryApprovalId,
30
33
  listFoundryApprovals,
31
34
  markFoundryApprovalSuspended,
32
35
  matchesOccurrenceFilter,
@@ -40,18 +43,21 @@ import {
40
43
  scheduleOccurrenceId,
41
44
  scheduleRevisionMatches,
42
45
  transmissionPredicate
43
- } from "./chunk-4WBQ7XVF.js";
46
+ } from "./chunk-UGYXSWPE.js";
44
47
  import {
48
+ DEFAULT_MESH_REFUSAL,
45
49
  FOUNDRY_CONVERSATION_LEASE_EVENT,
46
50
  FOUNDRY_CONVERSATION_LISTEN_EVENT,
47
51
  FOUNDRY_MAILBOX_DIRECTORY_ENV,
48
52
  delegationFromContext,
49
53
  deliveryEvent,
50
54
  drainMailbox,
55
+ isBindableThreadId,
51
56
  isDelegationId,
52
57
  isMeshCommand,
53
58
  isOpenDelegation,
54
59
  isOpenThread,
60
+ isTakenOverBy,
55
61
  isThreadId,
56
62
  meshIdentity,
57
63
  newMessageId,
@@ -64,7 +70,7 @@ import {
64
70
  workerAgentId,
65
71
  writeConversationLease,
66
72
  writeMailboxDelivery
67
- } from "./chunk-2JCISE2U.js";
73
+ } from "./chunk-WRGSTYBW.js";
68
74
  import {
69
75
  EMPTY_CAPABILITY_REGISTRY,
70
76
  EMPTY_NATIVE_REGISTRY,
@@ -96,8 +102,9 @@ import {
96
102
  installationKey,
97
103
  messageOptionsSchema,
98
104
  monitorFoundryCoreCommandRequest,
105
+ resolveResolvable,
99
106
  settleFoundryCoreCommandRequest
100
- } from "./chunk-NWFOY3L7.js";
107
+ } from "./chunk-WK2O4GIB.js";
101
108
 
102
109
  // src/codegen.ts
103
110
  import { mkdir, writeFile } from "node:fs/promises";
@@ -1664,6 +1671,13 @@ var FoundryRuntimeError = class extends Schema3.TaggedError(
1664
1671
  message: Schema3.String
1665
1672
  }) {
1666
1673
  };
1674
+ var MeshRefusal = class extends Error {
1675
+ constructor(message, reason) {
1676
+ super(message);
1677
+ this.reason = reason;
1678
+ }
1679
+ };
1680
+ var MESH_COMMIT_RETRY_MS = [1e3, 5e3, 3e4, 12e4, 6e5];
1667
1681
  function clipTitle(text) {
1668
1682
  const flat = text.replace(/\s+/g, " ").trim();
1669
1683
  return flat.length > 60 ? `${flat.slice(0, 59)}\u2026` : flat;
@@ -1795,6 +1809,8 @@ var FoundryRuntime = class _FoundryRuntime {
1795
1809
  pendingInboundByRun = /* @__PURE__ */ new Map();
1796
1810
  /** Recently settled runs, for a record assigned to a run that already finished. */
1797
1811
  settledRuns = /* @__PURE__ */ new Set();
1812
+ /** The built-ins each restricted run mounted, as it reported them. Runs without a policy are absent. */
1813
+ runBuiltins = /* @__PURE__ */ new Map();
1798
1814
  /** How runs treat approvals; durable when the data adapter can keep them. */
1799
1815
  approvalPolicy;
1800
1816
  /** Approval records change one at a time. */
@@ -1895,7 +1911,27 @@ var FoundryRuntime = class _FoundryRuntime {
1895
1911
  void this.recordApprovalEvent(event.type, event.data).catch((cause) => this.reportApprovalFailure(event.run.id, cause));
1896
1912
  return;
1897
1913
  }
1914
+ if (event.type === FOUNDRY_BUILTINS_MOUNTED_EVENT) {
1915
+ const data2 = event.data;
1916
+ this.runBuiltins.set(event.run.id, {
1917
+ tools: new Set(data2?.tools ?? []),
1918
+ transmissionTools: (data2?.transmissionTools ?? []).length > 0
1919
+ });
1920
+ this.observability.append({
1921
+ type: FOUNDRY_BUILTINS_MOUNTED_EVENT,
1922
+ category: "system",
1923
+ agent: event.route,
1924
+ runId: event.run.id,
1925
+ data: { tools: [...data2?.tools ?? []], transmissionTools: [...data2?.transmissionTools ?? []] }
1926
+ });
1927
+ return;
1928
+ }
1898
1929
  if (event.type === FOUNDRY_CORE_COMMAND_EVENT) {
1930
+ const refusal = this.withheldBuiltinRefusal(event.data, event.run.id);
1931
+ if (refusal) {
1932
+ void this.refuseCoreCommand(event.data, event.run.id, refusal, event.route);
1933
+ return;
1934
+ }
1899
1935
  void this.executeCoreCommand(event.data, event.run.id).catch((cause) => {
1900
1936
  this.observability.append({
1901
1937
  type: "core.command.failed",
@@ -2774,6 +2810,10 @@ var FoundryRuntime = class _FoundryRuntime {
2774
2810
  return { decided: decided2, live: waiting };
2775
2811
  });
2776
2812
  this.reportResolved(decided, decision);
2813
+ if (decided.mesh) {
2814
+ await this.settleMeshDraft(decided).catch((cause) => this.reportApprovalFailure(decided.runId, cause));
2815
+ return decided;
2816
+ }
2777
2817
  if (live) return decided;
2778
2818
  return this.resumeApproval(decided).catch((cause) => {
2779
2819
  this.reportApprovalFailure(decided.runId, cause);
@@ -4589,16 +4629,25 @@ var FoundryRuntime = class _FoundryRuntime {
4589
4629
  return found.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
4590
4630
  }
4591
4631
  /**
4592
- * Older thread records kept their own lists of messages not handed over yet.
4593
- * Move them to the event journal once; message ids keep a retry from
4594
- * delivering twice.
4632
+ * At start: older thread records kept their own lists of messages not
4633
+ * handed over yet; move them to the event journal once. Then finish what a
4634
+ * stop cut short: messages committed (or being committed) to the
4635
+ * application's record and not handed over, and drafts decided but not
4636
+ * delivered or dropped. Message ids keep a retry from delivering twice.
4595
4637
  */
4596
4638
  async redeliverThreads() {
4597
4639
  for (const thread of await this.listThreads()) {
4598
- if (!thread.undelivered?.length && !thread.pending?.length) continue;
4599
- if (thread.undelivered?.length) await this.deliverMesh(this.starterTarget(thread), "starter", thread.undelivered);
4600
- if (thread.pending?.length) await this.deliverMesh(this.recipientTarget(thread), "recipient", thread.pending);
4601
- await this.updateThread(thread.id, { status: thread.status });
4640
+ if (thread.undelivered?.length || thread.pending?.length) {
4641
+ if (thread.undelivered?.length) await this.deliverMesh(this.starterTarget(thread), "starter", thread.undelivered);
4642
+ if (thread.pending?.length) await this.deliverMesh(this.recipientTarget(thread), "recipient", thread.pending);
4643
+ await this.updateThread(thread.id, { status: thread.status });
4644
+ }
4645
+ if (thread.outbox?.length) await this.flushOutbox(thread.id).catch((cause) => this.reportMeshFailure(thread, cause));
4646
+ for (const held of thread.held ?? []) {
4647
+ if (held.decision !== "draft" || !held.approvalId) continue;
4648
+ const approval = await this.getApproval(held.approvalId).catch(() => null);
4649
+ if (approval && approval.status !== "pending") await this.settleMeshDraft(approval).catch((cause) => this.reportMeshFailure(thread, cause));
4650
+ }
4602
4651
  }
4603
4652
  }
4604
4653
  /** The open threads a conversation started, oldest first. */
@@ -4612,19 +4661,22 @@ var FoundryRuntime = class _FoundryRuntime {
4612
4661
  }
4613
4662
  async loadThread(id2) {
4614
4663
  const conversation = await Effect5.runPromise(this.data.getConversation(id2));
4615
- return threadFromContext(conversation?.context) ?? null;
4664
+ const thread = threadFromContext(conversation?.context);
4665
+ return thread && thread.id === id2 ? thread : null;
4616
4666
  }
4617
4667
  updateThread(id2, change) {
4618
4668
  return this.inConversation(`record:${id2}`, async () => {
4619
4669
  const conversation = await Effect5.runPromise(this.data.getConversation(id2));
4620
4670
  const current = threadFromContext(conversation?.context);
4621
4671
  if (!conversation || !current) return null;
4622
- const patch = typeof change === "function" ? change(current) : change;
4672
+ const patch = { ...typeof change === "function" ? change(current) : change };
4673
+ if (current.status === "taken-over" && patch.status !== "taken-over") delete patch.status;
4623
4674
  if (Object.keys(patch).length === 0) return current;
4624
4675
  const now = (/* @__PURE__ */ new Date()).toISOString();
4625
4676
  const merged = { ...current, ...patch, updatedAt: now };
4626
4677
  delete merged.undelivered;
4627
4678
  delete merged.pending;
4679
+ for (const key of ["held", "outbox"]) if (Array.isArray(merged[key]) && merged[key].length === 0) delete merged[key];
4628
4680
  for (const key of Object.keys(merged)) if (merged[key] === void 0) delete merged[key];
4629
4681
  const next = Object.freeze(merged);
4630
4682
  await Effect5.runPromise(this.data.putConversation(Object.freeze({
@@ -4640,7 +4692,7 @@ var FoundryRuntime = class _FoundryRuntime {
4640
4692
  definitionId: thread.from.definitionId,
4641
4693
  agentId: thread.from.agentId,
4642
4694
  conversationId: thread.from.conversationId,
4643
- workspaceId: thread.workspaceId
4695
+ workspaceId: thread.from.workspaceId ?? thread.workspaceId
4644
4696
  };
4645
4697
  }
4646
4698
  recipientTarget(thread) {
@@ -4648,16 +4700,25 @@ var FoundryRuntime = class _FoundryRuntime {
4648
4700
  definitionId: thread.to.definitionId,
4649
4701
  agentId: thread.to.agentId,
4650
4702
  conversationId: thread.id,
4651
- workspaceId: thread.workspaceId
4703
+ workspaceId: thread.to.workspaceId ?? thread.workspaceId
4652
4704
  };
4653
4705
  }
4706
+ sideTarget(thread, side) {
4707
+ return side === "starter" ? this.starterTarget(thread) : this.recipientTarget(thread);
4708
+ }
4654
4709
  /**
4655
4710
  * Hand mesh messages to one side of a thread. Messages, replies and
4656
4711
  * failures go through durable delivery. A read receipt only ever reaches a
4657
4712
  * run that is listening, and is dropped otherwise.
4658
4713
  */
4659
- async deliverMesh(target, side, messages) {
4660
- const delivery = (message) => ({ kind: "mesh", side, message, deliveryId: message.id });
4714
+ async deliverMesh(target, side, messages, peer) {
4715
+ const delivery = (message) => ({
4716
+ kind: "mesh",
4717
+ side,
4718
+ message,
4719
+ deliveryId: message.id,
4720
+ ...peer && message.from.kind === "human" ? { peer } : {}
4721
+ });
4661
4722
  const receipts = messages.filter((message) => message.kind === "ack");
4662
4723
  if (receipts.length) {
4663
4724
  await this.inConversation(target.conversationId, async () => {
@@ -4668,6 +4729,288 @@ var FoundryRuntime = class _FoundryRuntime {
4668
4729
  const durable = messages.filter((message) => message.kind !== "ack");
4669
4730
  if (durable.length) await this.deliver(target, durable.map(delivery));
4670
4731
  }
4732
+ /**
4733
+ * Send messages to one side of a thread. Under the application's mesh they
4734
+ * go through the thread's outbox: committed to the application's record
4735
+ * first, then handed over, so the record and the journal agree. A side
4736
+ * that was taken over gets nothing; the record still does.
4737
+ */
4738
+ async sendToSide(thread, side, messages, runId) {
4739
+ const target = this.sideTarget(thread, side);
4740
+ const away = isTakenOverBy(thread, target.agentId);
4741
+ const peer = side === "starter" ? thread.to.agentId : void 0;
4742
+ const receipts = messages.filter((message) => message.kind === "ack");
4743
+ if (receipts.length && !away) await this.deliverMesh(target, side, receipts, peer);
4744
+ const durable = messages.filter((message) => message.kind !== "ack");
4745
+ if (!durable.length) return;
4746
+ if (!this.application.mesh) {
4747
+ if (!away) await this.deliverMesh(target, side, durable, peer);
4748
+ return;
4749
+ }
4750
+ const ids = new Set(durable.map((message) => message.id));
4751
+ await this.updateThread(thread.id, (current) => ({
4752
+ outbox: [...(current.outbox ?? []).filter((entry2) => !ids.has(entry2.message.id)), ...durable.map((message) => ({ message, side }))]
4753
+ }));
4754
+ await this.flushOutbox(thread.id, runId).catch((cause) => {
4755
+ this.reportMeshFailure(thread, cause, runId);
4756
+ this.retryOutbox(thread.id, 0);
4757
+ });
4758
+ }
4759
+ /** Commit each outbox message to the application's record, then deliver it. */
4760
+ async flushOutbox(threadId, runId) {
4761
+ const commit = this.application.mesh?.commit;
4762
+ for (; ; ) {
4763
+ const thread = await this.loadThread(threadId);
4764
+ const entry2 = thread?.outbox?.[0];
4765
+ if (!thread || !entry2) return;
4766
+ if (commit) {
4767
+ const committed = await resolveResolvable(commit({ thread, message: entry2.message, side: entry2.side }, this.meshHookContext(runId)));
4768
+ this.observability.append({
4769
+ type: "mesh.committed",
4770
+ category: "system",
4771
+ agent: thread.to.definitionId,
4772
+ ...runId ? { runId } : {},
4773
+ data: { threadId, messageId: entry2.message.id, record: thread.record ?? thread.id, ...committed && committed.recordId ? { recordId: committed.recordId } : {} }
4774
+ });
4775
+ }
4776
+ const target = this.sideTarget(thread, entry2.side);
4777
+ if (!isTakenOverBy(thread, target.agentId)) {
4778
+ await this.deliverMesh(target, entry2.side, [entry2.message], entry2.side === "starter" ? thread.to.agentId : void 0);
4779
+ }
4780
+ await this.updateThread(threadId, (current) => ({
4781
+ outbox: (current.outbox ?? []).filter((item) => item.message.id !== entry2.message.id)
4782
+ }));
4783
+ }
4784
+ }
4785
+ retryOutbox(threadId, attempt) {
4786
+ const delay = MESH_COMMIT_RETRY_MS[attempt];
4787
+ if (delay === void 0 || this.stopping) return;
4788
+ const timer = setTimeout(() => {
4789
+ if (this.stopping) return;
4790
+ void this.flushOutbox(threadId).catch(async (cause) => {
4791
+ const thread = await this.loadThread(threadId).catch(() => null);
4792
+ if (thread) this.reportMeshFailure(thread, cause);
4793
+ this.retryOutbox(threadId, attempt + 1);
4794
+ });
4795
+ }, delay);
4796
+ timer.unref?.();
4797
+ }
4798
+ reportMeshFailure(thread, cause, runId) {
4799
+ this.observability.append({
4800
+ type: "mesh.commit.failed",
4801
+ category: "system",
4802
+ agent: thread.to.definitionId,
4803
+ ...runId ? { runId } : {},
4804
+ data: { threadId: thread.id, error: cause instanceof Error ? cause.message : String(cause) }
4805
+ });
4806
+ }
4807
+ meshHookContext(runId) {
4808
+ return { data: this.data, ...runId ? { runId } : {} };
4809
+ }
4810
+ meshRefusal() {
4811
+ return this.application.mesh?.refusal ?? DEFAULT_MESH_REFUSAL;
4812
+ }
4813
+ /** The application's gate. Without one, everything is delivered. */
4814
+ async gateMesh(send, runId) {
4815
+ const authorize = this.application.mesh?.authorize;
4816
+ if (!authorize) return { decision: "deliver" };
4817
+ const decided = await resolveResolvable(authorize(send, this.meshHookContext(runId)));
4818
+ switch (decided?.decision) {
4819
+ case "deliver":
4820
+ case "hold":
4821
+ return decided;
4822
+ case "draft":
4823
+ if (decided.approvalId !== void 0 && !isFoundryApprovalId(decided.approvalId)) {
4824
+ throw new Error(`mesh.authorize drafted with "${decided.approvalId}", which is not an approval id (approval_<uuid>).`);
4825
+ }
4826
+ return decided;
4827
+ case "refuse":
4828
+ return { decision: "refuse", message: typeof decided.message === "string" && decided.message.trim() ? decided.message : this.meshRefusal() };
4829
+ default:
4830
+ throw new Error("mesh.authorize must decide deliver, hold, draft or refuse.");
4831
+ }
4832
+ }
4833
+ /**
4834
+ * Act on the gate's decision for one message to one side. Held and drafted
4835
+ * messages are stored on the thread, not delivered; `onDeliver` is what
4836
+ * delivery changes on the thread, applied only when it happens, because
4837
+ * the side waiting for it must not see a message it has not been given.
4838
+ */
4839
+ async dispatchMesh(thread, side, message, decision, origin, onDeliver) {
4840
+ if (decision.decision === "deliver") {
4841
+ if (onDeliver) await this.updateThread(thread.id, onDeliver);
4842
+ await this.sendToSide(thread, side, [message], origin.runId);
4843
+ return;
4844
+ }
4845
+ if (decision.decision === "refuse") return;
4846
+ const approvalId = decision.decision === "draft" ? await this.draftApproval(thread, message, decision.approvalId, origin) : void 0;
4847
+ const held = {
4848
+ message,
4849
+ side,
4850
+ decision: decision.decision,
4851
+ ...approvalId ? { approvalId } : {},
4852
+ ...onDeliver ? { onDeliver } : {}
4853
+ };
4854
+ await this.updateThread(thread.id, (current) => ({
4855
+ held: [...(current.held ?? []).filter((item) => item.message.id !== message.id), held]
4856
+ }));
4857
+ this.observability.append({
4858
+ type: decision.decision === "draft" ? "mesh.drafted" : "mesh.held",
4859
+ category: "system",
4860
+ agent: origin.agent.definitionId,
4861
+ ...origin.runId ? { runId: origin.runId } : {},
4862
+ data: { threadId: thread.id, messageId: message.id, from: message.from.agentId, to: message.to, side, ...approvalId ? { approvalId } : {} }
4863
+ });
4864
+ }
4865
+ /** A drafted message waits on an approval nobody resumes a run for. */
4866
+ async draftApproval(thread, message, requestedId, origin) {
4867
+ if (!this.approvalPolicy.durable || !this.data.putApproval || !this.data.getApproval) {
4868
+ throw new Error("A drafted mesh message needs a data adapter that stores approvals.");
4869
+ }
4870
+ const id2 = requestedId ?? `approval_${randomUUID2()}`;
4871
+ const now = /* @__PURE__ */ new Date();
4872
+ const approval = this.withApprovalUrl({
4873
+ id: id2,
4874
+ runId: origin.runId ?? `mesh:${thread.id}`,
4875
+ definitionId: origin.agent.definitionId,
4876
+ agentId: origin.agent.id,
4877
+ conversationId: origin.conversationId,
4878
+ workspaceId: origin.agent.workspaceId,
4879
+ toolName: origin.kind === "reply" ? "glove_mesh_reply" : "glove_mesh_send_message",
4880
+ toolInput: { to: message.to, content: message.content, ...message.inReplyTo ? { in_reply_to: message.inReplyTo } : {} },
4881
+ status: "pending",
4882
+ requestedAt: now.toISOString(),
4883
+ expiresAt: new Date(now.getTime() + this.approvalPolicy.expiresAfterMs).toISOString(),
4884
+ // Nobody waits for it and nothing resumes: the decision delivers or drops the message.
4885
+ suspendedAt: now.toISOString(),
4886
+ settledInRun: true,
4887
+ mesh: { threadId: thread.id, messageId: message.id }
4888
+ });
4889
+ await this.withApprovals(async () => {
4890
+ const existing = await Effect5.runPromise(this.data.getApproval(id2));
4891
+ if (existing && existing.mesh?.messageId !== message.id) throw new Error(`Approval "${id2}" already exists.`);
4892
+ if (!existing) await Effect5.runPromise(this.data.putApproval(approval));
4893
+ });
4894
+ return id2;
4895
+ }
4896
+ /** A drafted message's approval was decided: deliver it, or drop it. */
4897
+ async settleMeshDraft(approval) {
4898
+ if (!approval.mesh || approval.status === "pending") return;
4899
+ await this.releaseHeld(approval.mesh.threadId, approval.mesh.messageId, approval.status === "approved" ? "deliver" : "discard", approval.id);
4900
+ }
4901
+ /**
4902
+ * Release a message the application's gate held: deliver it (committed to
4903
+ * your record first) or discard it. The sender is not told either way.
4904
+ * Drafts are decided through their approval instead.
4905
+ */
4906
+ async releaseMeshMessage(threadId, messageId, decision) {
4907
+ const thread = await this.loadThread(threadId);
4908
+ if (!thread) throw new Error(`There is no mesh thread "${threadId}".`);
4909
+ const held = thread.held?.find((item) => item.message.id === messageId);
4910
+ if (!held) throw new Error(`Thread "${threadId}" holds no message "${messageId}".`);
4911
+ if (held.decision === "draft") throw new Error(`Message "${messageId}" is a draft: decide approval "${held.approvalId}" instead.`);
4912
+ await this.releaseHeld(threadId, messageId, decision);
4913
+ return await this.loadThread(threadId) ?? thread;
4914
+ }
4915
+ async releaseHeld(threadId, messageId, decision, approvalId) {
4916
+ let released;
4917
+ const thread = await this.updateThread(threadId, (current) => {
4918
+ released = current.held?.find((item) => item.message.id === messageId && (!approvalId || item.approvalId === approvalId));
4919
+ if (!released) return {};
4920
+ const held = (current.held ?? []).filter((item) => item !== released);
4921
+ if (decision === "discard") return { held };
4922
+ return {
4923
+ held,
4924
+ ...released.onDeliver ?? {},
4925
+ ...released.onDeliver?.status === "replied" ? { question: void 0 } : {},
4926
+ outbox: [...(current.outbox ?? []).filter((entry2) => entry2.message.id !== messageId), { message: released.message, side: released.side }]
4927
+ };
4928
+ });
4929
+ if (!thread || !released) return;
4930
+ this.observability.append({
4931
+ type: decision === "deliver" ? "mesh.released" : "mesh.discarded",
4932
+ category: "system",
4933
+ agent: thread.to.definitionId,
4934
+ data: { threadId, messageId, ...approvalId ? { approvalId } : {} }
4935
+ });
4936
+ if (decision === "deliver") {
4937
+ await this.flushOutbox(threadId).catch((cause) => {
4938
+ this.reportMeshFailure(thread, cause);
4939
+ this.retryOutbox(threadId, 0);
4940
+ });
4941
+ }
4942
+ }
4943
+ /**
4944
+ * A person's message in a thread, entered by the application from its own
4945
+ * record (so it is not committed again). It reaches each agent still in
4946
+ * the thread as a message from a person, and starts the recipient working
4947
+ * again. Pass `id` (your record's message id) to make a retry a no-op.
4948
+ */
4949
+ async meshHumanMessage(threadId, input) {
4950
+ const thread = await this.loadThread(threadId);
4951
+ if (!thread) throw new Error(`There is no mesh thread "${threadId}".`);
4952
+ if (!input.authorId.trim() || !input.text.trim()) throw new Error("A person's message needs an authorId and text.");
4953
+ const id2 = input.id ?? newMessageId();
4954
+ const message = (to) => ({
4955
+ kind: "message",
4956
+ id: id2,
4957
+ threadId,
4958
+ from: { agentId: input.authorId, name: input.name ?? input.authorId, kind: "human" },
4959
+ to,
4960
+ content: input.text,
4961
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
4962
+ });
4963
+ const recipientIn = !isTakenOverBy(thread, thread.to.agentId);
4964
+ await this.updateThread(threadId, (current) => ({
4965
+ ...recipientIn ? { status: "working", question: void 0 } : {},
4966
+ messageIds: current.messageIds.includes(id2) ? current.messageIds : [...current.messageIds, id2]
4967
+ }));
4968
+ if (recipientIn) await this.deliverMesh(this.recipientTarget(thread), "recipient", [message(thread.to.agentId)]);
4969
+ if (!isTakenOverBy(thread, thread.from.agentId)) {
4970
+ await this.deliverMesh(this.starterTarget(thread), "starter", [message(thread.from.agentId)], thread.to.agentId);
4971
+ }
4972
+ this.observability.append({
4973
+ type: "mesh.human.message",
4974
+ category: "system",
4975
+ agent: thread.to.definitionId,
4976
+ data: { threadId, messageId: id2, authorId: input.authorId }
4977
+ });
4978
+ return message(recipientIn ? thread.to.agentId : thread.from.agentId);
4979
+ }
4980
+ /**
4981
+ * A person takes a thread over. The agents named (default: both) leave it:
4982
+ * nothing more is delivered to them in this thread, what they send to it
4983
+ * is refused, and a recipient run working on it is cancelled without a
4984
+ * reply. Messages to a side that left still reach your record.
4985
+ */
4986
+ async meshTakeOver(threadId, options) {
4987
+ const thread = await this.loadThread(threadId);
4988
+ if (!thread) throw new Error(`There is no mesh thread "${threadId}".`);
4989
+ const parties = [thread.from.agentId, thread.to.agentId];
4990
+ if (options.agentId && !parties.includes(options.agentId)) throw new Error(`Agent "${options.agentId}" is not in thread "${threadId}".`);
4991
+ const leaving = options.agentId ? [options.agentId] : parties;
4992
+ const updated = await this.updateThread(threadId, (current) => ({
4993
+ status: "taken-over",
4994
+ question: void 0,
4995
+ takenOver: {
4996
+ by: options.by,
4997
+ agentIds: [.../* @__PURE__ */ new Set([...current.takenOver?.agentIds ?? [], ...leaving])],
4998
+ at: (/* @__PURE__ */ new Date()).toISOString()
4999
+ }
5000
+ }));
5001
+ if (leaving.includes(thread.to.agentId)) {
5002
+ for (const run of await this.listRuns(thread.to.definitionId)) {
5003
+ if (run.conversationId === threadId && (run.status === "pending" || run.status === "running")) await this.cancel(run.id);
5004
+ }
5005
+ }
5006
+ this.observability.append({
5007
+ type: "mesh.taken_over",
5008
+ category: "system",
5009
+ agent: thread.to.definitionId,
5010
+ data: { threadId, by: options.by, agentIds: leaving }
5011
+ });
5012
+ return updated ?? thread;
5013
+ }
4671
5014
  /** A run's mesh call: answered through its request, so the tool hears the outcome. */
4672
5015
  async runMeshCommand(command, parentRunId) {
4673
5016
  const request = await getFoundryCoreCommandRequest(this.coreCommandDirectory, command.id);
@@ -4687,24 +5030,54 @@ var FoundryRuntime = class _FoundryRuntime {
4687
5030
  category: "system",
4688
5031
  agent: command.definitionId,
4689
5032
  runId: parentRunId,
4690
- data: { type: command.type, error }
5033
+ data: { type: command.type, error, ...cause instanceof MeshRefusal ? { reason: cause.reason } : {} }
4691
5034
  });
4692
5035
  await settleFoundryCoreCommandRequest(this.coreCommandDirectory, command.id, { status: "error", error });
4693
5036
  }
4694
5037
  }
4695
- /** The agents an agent may see and message: its workspace, narrowed by its definition's rule. */
4696
- async meshPeers(sender) {
4697
- const peers = hostedMeshOptions(this.byRoute.get(sender.definitionId)?.definition.mesh)?.peers;
4698
- return (await Effect5.runPromise(this.data.listAgents())).filter((agent) => agent.workspaceId === sender.workspaceId && agent.id !== sender.id && this.byRoute.has(agent.definitionId) && (peers?.(sender, agent) ?? true));
5038
+ /**
5039
+ * The agents an agent may see and message: its workspace, or whoever the
5040
+ * application's `mesh.peers` names; then narrowed by its definition's rule.
5041
+ */
5042
+ async meshPeers(sender, runId) {
5043
+ const own = hostedMeshOptions(this.byRoute.get(sender.definitionId)?.definition.mesh)?.peers;
5044
+ const named = this.application.mesh?.peers;
5045
+ let candidates;
5046
+ if (named) {
5047
+ candidates = [];
5048
+ const seen = /* @__PURE__ */ new Set([sender.id]);
5049
+ for (const peer of await resolveResolvable(named(sender, this.meshHookContext(runId)))) {
5050
+ if (!peer || typeof peer.agentId !== "string" || seen.has(peer.agentId)) continue;
5051
+ seen.add(peer.agentId);
5052
+ const agent = await Effect5.runPromise(this.data.getAgent(peer.agentId));
5053
+ if (!agent || !this.byRoute.has(agent.definitionId)) continue;
5054
+ candidates.push(Object.freeze({
5055
+ ...agent,
5056
+ ...peer.name ? { name: peer.name } : {},
5057
+ ...peer.description ? { description: peer.description } : {}
5058
+ }));
5059
+ }
5060
+ } else {
5061
+ candidates = (await Effect5.runPromise(this.data.listAgents())).filter((agent) => agent.workspaceId === sender.workspaceId && agent.id !== sender.id && this.byRoute.has(agent.definitionId));
5062
+ }
5063
+ return candidates.filter((agent) => own?.(sender, agent) ?? true);
4699
5064
  }
4700
5065
  async executeMeshCommand(command, parentRunId) {
4701
5066
  const sender = await Effect5.runPromise(this.data.getAgent(command.agentId));
4702
5067
  if (!sender || sender.workspaceId !== command.workspaceId) {
4703
5068
  throw new Error("A mesh call must come from an agent instance in its workspace.");
4704
5069
  }
5070
+ const run = await this.getRun(parentRunId).catch(() => null);
5071
+ if (run && (run.agentId && run.agentId !== sender.id || run.conversationId && run.conversationId !== command.conversationId)) {
5072
+ throw new Error("A mesh call must come from the run's own agent and conversation.");
5073
+ }
5074
+ const hosted = Boolean(this.application.mesh);
5075
+ const refuse = (reason, wording) => {
5076
+ throw hosted ? new MeshRefusal(wording ?? this.meshRefusal(), reason) : new Error(wording ?? reason);
5077
+ };
4705
5078
  if (command.type === "mesh.list") {
4706
5079
  const filter = command.name?.toLowerCase();
4707
- return (await this.meshPeers(sender)).map(meshIdentity).filter((identity) => !filter || identity.name.toLowerCase().includes(filter));
5080
+ return (await this.meshPeers(sender, parentRunId)).map(meshIdentity).filter((identity) => !filter || identity.name.toLowerCase().includes(filter));
4708
5081
  }
4709
5082
  const conversation = await Effect5.runPromise(this.data.getConversation(command.conversationId));
4710
5083
  if (!conversation || conversation.agentId !== sender.id) {
@@ -4720,11 +5093,23 @@ var FoundryRuntime = class _FoundryRuntime {
4720
5093
  }
4721
5094
  return threads;
4722
5095
  };
5096
+ const origin = (kind) => ({ runId: parentRunId, agent: sender, conversationId: conversation.id, kind });
5097
+ const otherSide = async (thread2, toStarter) => {
5098
+ const agent = await Effect5.runPromise(this.data.getAgent(toStarter ? thread2.from.agentId : thread2.to.agentId));
5099
+ if (!agent) refuse("the other agent is gone", `${toStarter ? thread2.from.name : thread2.to.name} is no longer on the mesh.`);
5100
+ return agent;
5101
+ };
5102
+ const decide = async (send) => {
5103
+ const decision2 = await this.gateMesh({ ...send, sender, senderConversationId: conversation.id }, parentRunId);
5104
+ if (decision2.decision === "refuse") refuse("refused by mesh.authorize", decision2.message);
5105
+ return decision2;
5106
+ };
4723
5107
  if (command.type === "mesh.ack") {
4724
5108
  const thread2 = ownThread?.messageIds.includes(command.messageId) ? ownThread : (await startedThreads()).find((item) => item.messageIds.includes(command.messageId));
4725
5109
  if (!thread2) throw new Error(`There is no message "${command.messageId}" in your threads.`);
5110
+ if (isTakenOverBy(thread2, sender.id)) refuse("the sender was taken off this thread");
4726
5111
  const toStarter = thread2.id === ownThread?.id;
4727
- await this.deliverMesh(toStarter ? this.starterTarget(thread2) : this.recipientTarget(thread2), toStarter ? "starter" : "recipient", [{
5112
+ const ack = {
4728
5113
  kind: "ack",
4729
5114
  id: newMessageId(),
4730
5115
  threadId: thread2.id,
@@ -4733,14 +5118,28 @@ var FoundryRuntime = class _FoundryRuntime {
4733
5118
  content: command.note,
4734
5119
  inReplyTo: command.messageId,
4735
5120
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
4736
- }]);
5121
+ };
5122
+ if (hosted) {
5123
+ const decision2 = await this.gateMesh({
5124
+ kind: "ack",
5125
+ messageId: ack.id,
5126
+ thread: thread2,
5127
+ sender,
5128
+ senderConversationId: conversation.id,
5129
+ recipient: await otherSide(thread2, toStarter),
5130
+ content: ack.content,
5131
+ inReplyTo: command.messageId
5132
+ }, parentRunId);
5133
+ if (decision2.decision !== "deliver") return { acknowledged: command.messageId };
5134
+ }
5135
+ await this.sendToSide(thread2, toStarter ? "starter" : "recipient", [ack], parentRunId);
4737
5136
  return { acknowledged: command.messageId };
4738
5137
  }
4739
5138
  const { message: input } = command;
4740
- const message = (threadId) => ({
5139
+ const message = (threadId2) => ({
4741
5140
  kind: "message",
4742
5141
  id: input.id,
4743
- threadId,
5142
+ threadId: threadId2,
4744
5143
  from: { agentId: sender.id, name: sender.name ?? sender.id },
4745
5144
  to: input.to,
4746
5145
  content: input.content,
@@ -4758,13 +5157,13 @@ var FoundryRuntime = class _FoundryRuntime {
4758
5157
  return { messageId: input.id, threadId: thread2.id, to: input.to, direction };
4759
5158
  };
4760
5159
  if (ownThread && input.to === ownThread.from.agentId && (!input.inReplyTo || ownThread.messageIds.includes(input.inReplyTo))) {
5160
+ if (isTakenOverBy(ownThread, sender.id)) refuse("the sender was taken off this thread");
4761
5161
  const outgoing2 = message(ownThread.id);
5162
+ const decision2 = hosted ? await decide({ kind: "message", messageId: outgoing2.id, thread: ownThread, recipient: await otherSide(ownThread, true), content: outgoing2.content, ...outgoing2.inReplyTo ? { inReplyTo: outgoing2.inReplyTo } : {} }) : { decision: "deliver" };
4762
5163
  await this.updateThread(ownThread.id, (current) => ({
4763
- status: "waiting",
4764
- question: outgoing2.content,
4765
- messageIds: [...current.messageIds, outgoing2.id]
5164
+ messageIds: current.messageIds.includes(outgoing2.id) ? current.messageIds : [...current.messageIds, outgoing2.id]
4766
5165
  }));
4767
- await this.deliverMesh(this.starterTarget(ownThread), "starter", [outgoing2]);
5166
+ await this.dispatchMesh(ownThread, "starter", outgoing2, decision2, origin("message"), { status: "waiting", question: outgoing2.content });
4768
5167
  return sent(ownThread, "to-starter");
4769
5168
  }
4770
5169
  if (input.inReplyTo) {
@@ -4772,70 +5171,119 @@ var FoundryRuntime = class _FoundryRuntime {
4772
5171
  if (!thread2) {
4773
5172
  throw new Error(`There is no message "${input.inReplyTo}" in your threads with "${input.to}". Leave in_reply_to out to start a new thread.`);
4774
5173
  }
5174
+ if (isTakenOverBy(thread2, sender.id)) refuse("the sender was taken off this thread");
4775
5175
  const outgoing2 = message(thread2.id);
5176
+ const decision2 = hosted ? await decide({ kind: "message", messageId: outgoing2.id, thread: thread2, recipient: await otherSide(thread2, false), content: outgoing2.content, inReplyTo: input.inReplyTo }) : { decision: "deliver" };
4776
5177
  await this.updateThread(thread2.id, (current) => ({
4777
5178
  status: "working",
4778
5179
  question: void 0,
4779
- messageIds: [...current.messageIds, outgoing2.id]
5180
+ messageIds: current.messageIds.includes(outgoing2.id) ? current.messageIds : [...current.messageIds, outgoing2.id]
4780
5181
  }));
4781
- await this.deliverMesh(this.recipientTarget(thread2), "recipient", [outgoing2]);
5182
+ await this.dispatchMesh(thread2, "recipient", outgoing2, decision2, origin("message"));
4782
5183
  return sent(thread2, "to-recipient");
4783
5184
  }
4784
5185
  if (!isThreadId(input.threadId)) throw new Error(`"${input.threadId}" is not a thread id.`);
4785
5186
  if (input.to === sender.id) throw new Error("That is you.");
4786
- const recipient = (await this.meshPeers(sender)).find((agent) => agent.id === input.to);
5187
+ const recipient = (await this.meshPeers(sender, parentRunId)).find((agent) => agent.id === input.to);
4787
5188
  if (!recipient) {
5189
+ if (hosted) refuse("not a peer");
4788
5190
  throw new Error(`There is no agent "${input.to}" you can message. Use glove_mesh_list_agents to see who there is.`);
4789
5191
  }
4790
- const outgoing = message(input.threadId);
5192
+ const decision = hosted ? await decide({ kind: "message", messageId: input.id, recipient, content: input.content }) : { decision: "deliver" };
5193
+ let threadId = input.threadId;
5194
+ let record;
5195
+ const bind = this.application.mesh?.bindThread;
5196
+ if (bind) {
5197
+ const bound = await resolveResolvable(bind({
5198
+ proposedId: input.threadId,
5199
+ sender,
5200
+ senderConversationId: conversation.id,
5201
+ recipient,
5202
+ messageId: input.id,
5203
+ content: input.content
5204
+ }, this.meshHookContext(parentRunId)));
5205
+ if (!bound || typeof bound.threadId !== "string" || !isBindableThreadId(bound.threadId)) {
5206
+ throw new Error("mesh.bindThread must return { threadId } with letters, digits, _ . : or -.");
5207
+ }
5208
+ threadId = bound.threadId;
5209
+ if (bound.record && bound.record !== threadId) record = bound.record;
5210
+ }
5211
+ const existing = threadId !== input.threadId ? await this.loadThread(threadId) : null;
5212
+ if (existing) {
5213
+ if (existing.from.agentId !== sender.id || existing.to.agentId !== recipient.id) {
5214
+ throw new Error(`mesh.bindThread returned "${threadId}", which is another pair's thread.`);
5215
+ }
5216
+ if (isTakenOverBy(existing, sender.id)) refuse("the sender was taken off this thread");
5217
+ const outgoing2 = message(existing.id);
5218
+ await this.updateThread(existing.id, (current) => ({
5219
+ status: "working",
5220
+ question: void 0,
5221
+ messageIds: current.messageIds.includes(outgoing2.id) ? current.messageIds : [...current.messageIds, outgoing2.id]
5222
+ }));
5223
+ if (existing.from.conversationId !== conversation.id) await this.noteStartedThread(conversation.id, existing.id);
5224
+ await this.dispatchMesh(existing, "recipient", outgoing2, decision, origin("message"));
5225
+ return sent(existing, "to-recipient");
5226
+ }
5227
+ if (await Effect5.runPromise(this.data.getConversation(threadId))) {
5228
+ throw new Error(`mesh.bindThread returned "${threadId}", which is already a conversation.`);
5229
+ }
5230
+ const outgoing = message(threadId);
4791
5231
  const now = (/* @__PURE__ */ new Date()).toISOString();
4792
5232
  const thread = Object.freeze({
4793
- id: input.threadId,
5233
+ id: threadId,
4794
5234
  workspaceId: sender.workspaceId,
4795
5235
  from: Object.freeze({
4796
5236
  agentId: sender.id,
4797
5237
  name: sender.name ?? sender.id,
4798
5238
  definitionId: sender.definitionId,
5239
+ ...recipient.workspaceId !== sender.workspaceId ? { workspaceId: sender.workspaceId } : {},
4799
5240
  conversationId: conversation.id,
4800
5241
  runId: parentRunId
4801
5242
  }),
4802
5243
  to: Object.freeze({
4803
5244
  agentId: recipient.id,
4804
5245
  name: recipient.name ?? recipient.id,
4805
- definitionId: recipient.definitionId
5246
+ definitionId: recipient.definitionId,
5247
+ ...recipient.workspaceId !== sender.workspaceId ? { workspaceId: recipient.workspaceId } : {}
4806
5248
  }),
4807
5249
  subject: threadSubject(outgoing.content),
4808
5250
  status: "working",
4809
5251
  messageIds: Object.freeze([outgoing.id]),
5252
+ ...record ? { record } : {},
4810
5253
  createdAt: now,
4811
5254
  updatedAt: now
4812
5255
  });
4813
5256
  await this.createConversation(recipient.id, {
4814
5257
  id: thread.id,
4815
- workspaceId: sender.workspaceId,
5258
+ workspaceId: recipient.workspaceId,
4816
5259
  title: `${thread.from.name}: ${clipTitle(outgoing.content)}`,
4817
5260
  context: { meshThread: thread }
4818
5261
  });
4819
- await this.inConversation(`record:${conversation.id}`, async () => {
4820
- const current = await Effect5.runPromise(this.data.getConversation(conversation.id));
4821
- if (!current) return;
5262
+ await this.noteStartedThread(conversation.id, thread.id);
5263
+ await this.dispatchMesh(thread, "recipient", outgoing, decision, origin("message"));
5264
+ return sent(thread, "new");
5265
+ }
5266
+ /** Remember on the starter's conversation that it started a thread. */
5267
+ async noteStartedThread(conversationId, threadId) {
5268
+ await this.inConversation(`record:${conversationId}`, async () => {
5269
+ const current = await Effect5.runPromise(this.data.getConversation(conversationId));
5270
+ if (!current || startedThreadIds(current.context).includes(threadId)) return;
4822
5271
  await Effect5.runPromise(this.data.putConversation({
4823
5272
  ...current,
4824
5273
  context: Object.freeze({
4825
5274
  ...current.context,
4826
- meshThreads: [...startedThreadIds(current.context), thread.id]
5275
+ meshThreads: [...startedThreadIds(current.context), threadId]
4827
5276
  }),
4828
- updatedAt: now
5277
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
4829
5278
  }));
4830
5279
  });
4831
- await this.deliverMesh(this.recipientTarget(thread), "recipient", [outgoing]);
4832
- return sent(thread, "new");
4833
5280
  }
4834
5281
  /** When the recipient's run on a thread ends, its reply (or its failure) goes back. */
4835
5282
  async settleThread(event, run, steered) {
4836
5283
  const thread = await this.loadThread(run.conversationId);
4837
5284
  if (!thread || run.agentId !== thread.to.agentId) return;
4838
5285
  if (this.stopping && event.status !== "completed") return;
5286
+ if (isTakenOverBy(thread, thread.to.agentId)) return;
4839
5287
  const reply = (kind, content) => ({
4840
5288
  kind,
4841
5289
  id: `msg_${kind}_${event.run.id}`,
@@ -4855,19 +5303,39 @@ var FoundryRuntime = class _FoundryRuntime {
4855
5303
  }
4856
5304
  const message2 = reply("reply", text);
4857
5305
  await this.updateThread(thread.id, (current) => ({
4858
- status: "replied",
4859
- reply: text,
4860
- question: void 0,
4861
5306
  messageIds: current.messageIds.includes(message2.id) ? current.messageIds : [...current.messageIds, message2.id]
4862
5307
  }));
4863
- await this.deliverMesh(this.starterTarget(thread), "starter", [message2]);
4864
- this.observability.append({
4865
- type: "mesh.thread.replied",
4866
- category: "system",
4867
- agent: thread.to.definitionId,
4868
- runId: event.run.id,
4869
- data: { threadId: thread.id }
4870
- });
5308
+ const replied = { status: "replied", reply: text, question: void 0 };
5309
+ const decision = await this.gateReply(thread, message2, event.run.id);
5310
+ if (decision.decision === "refuse") {
5311
+ await this.updateThread(thread.id, { status: "replied", question: void 0 });
5312
+ this.observability.append({
5313
+ type: "mesh.refused",
5314
+ category: "system",
5315
+ agent: thread.to.definitionId,
5316
+ runId: event.run.id,
5317
+ data: { type: "mesh.reply", threadId: thread.id, messageId: message2.id, error: decision.message }
5318
+ });
5319
+ return;
5320
+ }
5321
+ const recipient = await Effect5.runPromise(this.data.getAgent(thread.to.agentId));
5322
+ await this.dispatchMesh(
5323
+ thread,
5324
+ "starter",
5325
+ message2,
5326
+ decision,
5327
+ { runId: event.run.id, agent: recipient ?? { id: thread.to.agentId, definitionId: thread.to.definitionId, workspaceId: thread.to.workspaceId ?? thread.workspaceId }, conversationId: thread.id, kind: "reply" },
5328
+ replied
5329
+ );
5330
+ if (decision.decision === "deliver") {
5331
+ this.observability.append({
5332
+ type: "mesh.thread.replied",
5333
+ category: "system",
5334
+ agent: thread.to.definitionId,
5335
+ runId: event.run.id,
5336
+ data: { threadId: thread.id }
5337
+ });
5338
+ }
4871
5339
  return;
4872
5340
  }
4873
5341
  if (event.status === "cancelled" && steered) return;
@@ -4878,7 +5346,7 @@ var FoundryRuntime = class _FoundryRuntime {
4878
5346
  error,
4879
5347
  messageIds: current.messageIds.includes(message.id) ? current.messageIds : [...current.messageIds, message.id]
4880
5348
  }));
4881
- await this.deliverMesh(this.starterTarget(thread), "starter", [message]);
5349
+ await this.sendToSide(thread, "starter", [message], event.run.id);
4882
5350
  this.observability.append({
4883
5351
  type: event.status === "cancelled" ? "mesh.thread.cancelled" : "mesh.thread.failed",
4884
5352
  category: "system",
@@ -4887,8 +5355,52 @@ var FoundryRuntime = class _FoundryRuntime {
4887
5355
  data: { threadId: thread.id, error }
4888
5356
  });
4889
5357
  }
5358
+ /** The gate for a recipient's final answer, when the application has one. */
5359
+ async gateReply(thread, message, runId) {
5360
+ if (!this.application.mesh?.authorize) return { decision: "deliver" };
5361
+ const [sender, recipient] = await Promise.all([
5362
+ Effect5.runPromise(this.data.getAgent(thread.to.agentId)),
5363
+ Effect5.runPromise(this.data.getAgent(thread.from.agentId))
5364
+ ]);
5365
+ if (!sender || !recipient) return { decision: "refuse", message: this.meshRefusal() };
5366
+ return this.gateMesh({
5367
+ kind: "reply",
5368
+ messageId: message.id,
5369
+ thread,
5370
+ sender,
5371
+ senderConversationId: thread.id,
5372
+ recipient,
5373
+ content: message.content
5374
+ }, runId);
5375
+ }
5376
+ /**
5377
+ * A run whose definition restricts built-ins may only send the commands its
5378
+ * mounted tools send. Anything else is refused, however it was emitted.
5379
+ */
5380
+ withheldBuiltinRefusal(command, runId) {
5381
+ const mounted = this.runBuiltins.get(runId);
5382
+ if (!mounted) return null;
5383
+ const tools = builtinsForCommand(command.type);
5384
+ if (!tools) return null;
5385
+ if (tools.some((name) => mounted.tools.has(name))) return null;
5386
+ if (command.type === "transmit" && mounted.transmissionTools) return null;
5387
+ return `This run has no tool that can send "${command.type}".`;
5388
+ }
5389
+ async refuseCoreCommand(command, runId, error, route) {
5390
+ this.observability.append({
5391
+ type: "foundry.builtin.refused",
5392
+ category: "system",
5393
+ agent: route,
5394
+ runId,
5395
+ data: { type: command.type, error }
5396
+ });
5397
+ if (await getFoundryCoreCommandRequest(this.coreCommandDirectory, command.id).catch(() => null)) {
5398
+ await settleFoundryCoreCommandRequest(this.coreCommandDirectory, command.id, { status: "error", error }).catch(() => void 0);
5399
+ }
5400
+ }
4890
5401
  async handleRunSettled(event) {
4891
5402
  void this.settleApprovalsOf(event.run.id).catch((cause) => this.reportApprovalFailure(event.run.id, cause));
5403
+ this.runBuiltins.delete(event.run.id);
4892
5404
  this.recentlySettledRuns.set(event.run.id, event.status);
4893
5405
  if (this.recentlySettledRuns.size > 1e3) this.recentlySettledRuns.delete(this.recentlySettledRuns.keys().next().value);
4894
5406
  void this.settleOccurrence(event.run.id, event.status).catch((cause) => {
@@ -4914,7 +5426,7 @@ var FoundryRuntime = class _FoundryRuntime {
4914
5426
  };
4915
5427
  const steered = this.steeredRuns.delete(event.run.id);
4916
5428
  const run = this.toFoundryRun(event.run);
4917
- if (run.conversationId && isThreadId(run.conversationId)) {
5429
+ if (run.conversationId && (isThreadId(run.conversationId) || this.application.mesh?.bindThread && await this.loadThread(run.conversationId))) {
4918
5430
  await finishDelivery();
4919
5431
  await this.settleThread(event, run, steered);
4920
5432
  return;