glove-foundry 0.11.0 → 0.13.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-RAZARYUH.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-5ZYOBBOK.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);
@@ -3161,6 +3201,8 @@ var FoundryRuntime = class _FoundryRuntime {
3161
3201
  const runs = [];
3162
3202
  const deliveries = [];
3163
3203
  const matchedByAgent = /* @__PURE__ */ new Map();
3204
+ const subscriptions = await this.listPlaybookSubscriptions();
3205
+ const subscribedPlaybooks = new Set(subscriptions.map((subscription) => subscription.playbook.id));
3164
3206
  for (const stored of instances) {
3165
3207
  let agent;
3166
3208
  try {
@@ -3180,6 +3222,7 @@ var FoundryRuntime = class _FoundryRuntime {
3180
3222
  if (!hasInstalledOwner) continue;
3181
3223
  const matched = [];
3182
3224
  for (const playbook of agent.playbooks) {
3225
+ if (subscribedPlaybooks.has(playbook.id)) continue;
3183
3226
  if (await this.playbookMatches(
3184
3227
  playbook,
3185
3228
  integration,
@@ -3192,7 +3235,7 @@ var FoundryRuntime = class _FoundryRuntime {
3192
3235
  if (matched.length === 0) continue;
3193
3236
  matchedByAgent.set(agent.id, { agent, playbooks: matched });
3194
3237
  }
3195
- for (const subscription of await this.listPlaybookSubscriptions()) {
3238
+ for (const subscription of subscriptions) {
3196
3239
  if (!subscription.enabled || subscription.workspaceId.length === 0) continue;
3197
3240
  if (!await this.playbookMatches(
3198
3241
  subscription.playbook,
@@ -4572,6 +4615,10 @@ var FoundryRuntime = class _FoundryRuntime {
4572
4615
  // travel as "mesh" deliveries on the same durable path as delegation
4573
4616
  // updates: into the run working on that conversation, or as one run once it
4574
4617
  // is free. The recipient's final reply goes back on its own.
4618
+ /** One mesh thread, by id. Null when there is none. */
4619
+ getThread(threadId) {
4620
+ return this.loadThread(threadId);
4621
+ }
4575
4622
  /** Every thread, newest first, optionally narrowed to who started it or who it went to. */
4576
4623
  async listThreads(filter = {}) {
4577
4624
  const found = [];
@@ -4589,16 +4636,25 @@ var FoundryRuntime = class _FoundryRuntime {
4589
4636
  return found.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
4590
4637
  }
4591
4638
  /**
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.
4639
+ * At start: older thread records kept their own lists of messages not
4640
+ * handed over yet; move them to the event journal once. Then finish what a
4641
+ * stop cut short: messages committed (or being committed) to the
4642
+ * application's record and not handed over, and drafts decided but not
4643
+ * delivered or dropped. Message ids keep a retry from delivering twice.
4595
4644
  */
4596
4645
  async redeliverThreads() {
4597
4646
  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 });
4647
+ if (thread.undelivered?.length || thread.pending?.length) {
4648
+ if (thread.undelivered?.length) await this.deliverMesh(this.starterTarget(thread), "starter", thread.undelivered);
4649
+ if (thread.pending?.length) await this.deliverMesh(this.recipientTarget(thread), "recipient", thread.pending);
4650
+ await this.updateThread(thread.id, { status: thread.status });
4651
+ }
4652
+ if (thread.outbox?.length) await this.flushOutbox(thread.id).catch((cause) => this.reportMeshFailure(thread, cause));
4653
+ for (const held of thread.held ?? []) {
4654
+ if (held.decision !== "draft" || !held.approvalId) continue;
4655
+ const approval = await this.getApproval(held.approvalId).catch(() => null);
4656
+ if (approval && approval.status !== "pending") await this.settleMeshDraft(approval).catch((cause) => this.reportMeshFailure(thread, cause));
4657
+ }
4602
4658
  }
4603
4659
  }
4604
4660
  /** The open threads a conversation started, oldest first. */
@@ -4612,19 +4668,22 @@ var FoundryRuntime = class _FoundryRuntime {
4612
4668
  }
4613
4669
  async loadThread(id2) {
4614
4670
  const conversation = await Effect5.runPromise(this.data.getConversation(id2));
4615
- return threadFromContext(conversation?.context) ?? null;
4671
+ const thread = threadFromContext(conversation?.context);
4672
+ return thread && thread.id === id2 ? thread : null;
4616
4673
  }
4617
4674
  updateThread(id2, change) {
4618
4675
  return this.inConversation(`record:${id2}`, async () => {
4619
4676
  const conversation = await Effect5.runPromise(this.data.getConversation(id2));
4620
4677
  const current = threadFromContext(conversation?.context);
4621
4678
  if (!conversation || !current) return null;
4622
- const patch = typeof change === "function" ? change(current) : change;
4679
+ const patch = { ...typeof change === "function" ? change(current) : change };
4680
+ if (current.status === "taken-over" && patch.status !== "taken-over") delete patch.status;
4623
4681
  if (Object.keys(patch).length === 0) return current;
4624
4682
  const now = (/* @__PURE__ */ new Date()).toISOString();
4625
4683
  const merged = { ...current, ...patch, updatedAt: now };
4626
4684
  delete merged.undelivered;
4627
4685
  delete merged.pending;
4686
+ for (const key of ["held", "outbox"]) if (Array.isArray(merged[key]) && merged[key].length === 0) delete merged[key];
4628
4687
  for (const key of Object.keys(merged)) if (merged[key] === void 0) delete merged[key];
4629
4688
  const next = Object.freeze(merged);
4630
4689
  await Effect5.runPromise(this.data.putConversation(Object.freeze({
@@ -4640,7 +4699,7 @@ var FoundryRuntime = class _FoundryRuntime {
4640
4699
  definitionId: thread.from.definitionId,
4641
4700
  agentId: thread.from.agentId,
4642
4701
  conversationId: thread.from.conversationId,
4643
- workspaceId: thread.workspaceId
4702
+ workspaceId: thread.from.workspaceId ?? thread.workspaceId
4644
4703
  };
4645
4704
  }
4646
4705
  recipientTarget(thread) {
@@ -4648,16 +4707,25 @@ var FoundryRuntime = class _FoundryRuntime {
4648
4707
  definitionId: thread.to.definitionId,
4649
4708
  agentId: thread.to.agentId,
4650
4709
  conversationId: thread.id,
4651
- workspaceId: thread.workspaceId
4710
+ workspaceId: thread.to.workspaceId ?? thread.workspaceId
4652
4711
  };
4653
4712
  }
4713
+ sideTarget(thread, side) {
4714
+ return side === "starter" ? this.starterTarget(thread) : this.recipientTarget(thread);
4715
+ }
4654
4716
  /**
4655
4717
  * Hand mesh messages to one side of a thread. Messages, replies and
4656
4718
  * failures go through durable delivery. A read receipt only ever reaches a
4657
4719
  * run that is listening, and is dropped otherwise.
4658
4720
  */
4659
- async deliverMesh(target, side, messages) {
4660
- const delivery = (message) => ({ kind: "mesh", side, message, deliveryId: message.id });
4721
+ async deliverMesh(target, side, messages, peer) {
4722
+ const delivery = (message) => ({
4723
+ kind: "mesh",
4724
+ side,
4725
+ message,
4726
+ deliveryId: message.id,
4727
+ ...peer && message.from.kind === "human" ? { peer } : {}
4728
+ });
4661
4729
  const receipts = messages.filter((message) => message.kind === "ack");
4662
4730
  if (receipts.length) {
4663
4731
  await this.inConversation(target.conversationId, async () => {
@@ -4668,6 +4736,288 @@ var FoundryRuntime = class _FoundryRuntime {
4668
4736
  const durable = messages.filter((message) => message.kind !== "ack");
4669
4737
  if (durable.length) await this.deliver(target, durable.map(delivery));
4670
4738
  }
4739
+ /**
4740
+ * Send messages to one side of a thread. Under the application's mesh they
4741
+ * go through the thread's outbox: committed to the application's record
4742
+ * first, then handed over, so the record and the journal agree. A side
4743
+ * that was taken over gets nothing; the record still does.
4744
+ */
4745
+ async sendToSide(thread, side, messages, runId) {
4746
+ const target = this.sideTarget(thread, side);
4747
+ const away = isTakenOverBy(thread, target.agentId);
4748
+ const peer = side === "starter" ? thread.to.agentId : void 0;
4749
+ const receipts = messages.filter((message) => message.kind === "ack");
4750
+ if (receipts.length && !away) await this.deliverMesh(target, side, receipts, peer);
4751
+ const durable = messages.filter((message) => message.kind !== "ack");
4752
+ if (!durable.length) return;
4753
+ if (!this.application.mesh) {
4754
+ if (!away) await this.deliverMesh(target, side, durable, peer);
4755
+ return;
4756
+ }
4757
+ const ids = new Set(durable.map((message) => message.id));
4758
+ await this.updateThread(thread.id, (current) => ({
4759
+ outbox: [...(current.outbox ?? []).filter((entry2) => !ids.has(entry2.message.id)), ...durable.map((message) => ({ message, side }))]
4760
+ }));
4761
+ await this.flushOutbox(thread.id, runId).catch((cause) => {
4762
+ this.reportMeshFailure(thread, cause, runId);
4763
+ this.retryOutbox(thread.id, 0);
4764
+ });
4765
+ }
4766
+ /** Commit each outbox message to the application's record, then deliver it. */
4767
+ async flushOutbox(threadId, runId) {
4768
+ const commit = this.application.mesh?.commit;
4769
+ for (; ; ) {
4770
+ const thread = await this.loadThread(threadId);
4771
+ const entry2 = thread?.outbox?.[0];
4772
+ if (!thread || !entry2) return;
4773
+ if (commit) {
4774
+ const committed = await resolveResolvable(commit({ thread, message: entry2.message, side: entry2.side }, this.meshHookContext(runId)));
4775
+ this.observability.append({
4776
+ type: "mesh.committed",
4777
+ category: "system",
4778
+ agent: thread.to.definitionId,
4779
+ ...runId ? { runId } : {},
4780
+ data: { threadId, messageId: entry2.message.id, record: thread.record ?? thread.id, ...committed && committed.recordId ? { recordId: committed.recordId } : {} }
4781
+ });
4782
+ }
4783
+ const target = this.sideTarget(thread, entry2.side);
4784
+ if (!isTakenOverBy(thread, target.agentId)) {
4785
+ await this.deliverMesh(target, entry2.side, [entry2.message], entry2.side === "starter" ? thread.to.agentId : void 0);
4786
+ }
4787
+ await this.updateThread(threadId, (current) => ({
4788
+ outbox: (current.outbox ?? []).filter((item) => item.message.id !== entry2.message.id)
4789
+ }));
4790
+ }
4791
+ }
4792
+ retryOutbox(threadId, attempt) {
4793
+ const delay = MESH_COMMIT_RETRY_MS[attempt];
4794
+ if (delay === void 0 || this.stopping) return;
4795
+ const timer = setTimeout(() => {
4796
+ if (this.stopping) return;
4797
+ void this.flushOutbox(threadId).catch(async (cause) => {
4798
+ const thread = await this.loadThread(threadId).catch(() => null);
4799
+ if (thread) this.reportMeshFailure(thread, cause);
4800
+ this.retryOutbox(threadId, attempt + 1);
4801
+ });
4802
+ }, delay);
4803
+ timer.unref?.();
4804
+ }
4805
+ reportMeshFailure(thread, cause, runId) {
4806
+ this.observability.append({
4807
+ type: "mesh.commit.failed",
4808
+ category: "system",
4809
+ agent: thread.to.definitionId,
4810
+ ...runId ? { runId } : {},
4811
+ data: { threadId: thread.id, error: cause instanceof Error ? cause.message : String(cause) }
4812
+ });
4813
+ }
4814
+ meshHookContext(runId) {
4815
+ return { data: this.data, ...runId ? { runId } : {} };
4816
+ }
4817
+ meshRefusal() {
4818
+ return this.application.mesh?.refusal ?? DEFAULT_MESH_REFUSAL;
4819
+ }
4820
+ /** The application's gate. Without one, everything is delivered. */
4821
+ async gateMesh(send, runId) {
4822
+ const authorize = this.application.mesh?.authorize;
4823
+ if (!authorize) return { decision: "deliver" };
4824
+ const decided = await resolveResolvable(authorize(send, this.meshHookContext(runId)));
4825
+ switch (decided?.decision) {
4826
+ case "deliver":
4827
+ case "hold":
4828
+ return decided;
4829
+ case "draft":
4830
+ if (decided.approvalId !== void 0 && !isFoundryApprovalId(decided.approvalId)) {
4831
+ throw new Error(`mesh.authorize drafted with "${decided.approvalId}", which is not an approval id (approval_<uuid>).`);
4832
+ }
4833
+ return decided;
4834
+ case "refuse":
4835
+ return { decision: "refuse", message: typeof decided.message === "string" && decided.message.trim() ? decided.message : this.meshRefusal() };
4836
+ default:
4837
+ throw new Error("mesh.authorize must decide deliver, hold, draft or refuse.");
4838
+ }
4839
+ }
4840
+ /**
4841
+ * Act on the gate's decision for one message to one side. Held and drafted
4842
+ * messages are stored on the thread, not delivered; `onDeliver` is what
4843
+ * delivery changes on the thread, applied only when it happens, because
4844
+ * the side waiting for it must not see a message it has not been given.
4845
+ */
4846
+ async dispatchMesh(thread, side, message, decision, origin, onDeliver) {
4847
+ if (decision.decision === "deliver") {
4848
+ if (onDeliver) await this.updateThread(thread.id, onDeliver);
4849
+ await this.sendToSide(thread, side, [message], origin.runId);
4850
+ return;
4851
+ }
4852
+ if (decision.decision === "refuse") return;
4853
+ const approvalId = decision.decision === "draft" ? await this.draftApproval(thread, message, decision.approvalId, origin) : void 0;
4854
+ const held = {
4855
+ message,
4856
+ side,
4857
+ decision: decision.decision,
4858
+ ...approvalId ? { approvalId } : {},
4859
+ ...onDeliver ? { onDeliver } : {}
4860
+ };
4861
+ await this.updateThread(thread.id, (current) => ({
4862
+ held: [...(current.held ?? []).filter((item) => item.message.id !== message.id), held]
4863
+ }));
4864
+ this.observability.append({
4865
+ type: decision.decision === "draft" ? "mesh.drafted" : "mesh.held",
4866
+ category: "system",
4867
+ agent: origin.agent.definitionId,
4868
+ ...origin.runId ? { runId: origin.runId } : {},
4869
+ data: { threadId: thread.id, messageId: message.id, from: message.from.agentId, to: message.to, side, ...approvalId ? { approvalId } : {} }
4870
+ });
4871
+ }
4872
+ /** A drafted message waits on an approval nobody resumes a run for. */
4873
+ async draftApproval(thread, message, requestedId, origin) {
4874
+ if (!this.approvalPolicy.durable || !this.data.putApproval || !this.data.getApproval) {
4875
+ throw new Error("A drafted mesh message needs a data adapter that stores approvals.");
4876
+ }
4877
+ const id2 = requestedId ?? `approval_${randomUUID2()}`;
4878
+ const now = /* @__PURE__ */ new Date();
4879
+ const approval = this.withApprovalUrl({
4880
+ id: id2,
4881
+ runId: origin.runId ?? `mesh:${thread.id}`,
4882
+ definitionId: origin.agent.definitionId,
4883
+ agentId: origin.agent.id,
4884
+ conversationId: origin.conversationId,
4885
+ workspaceId: origin.agent.workspaceId,
4886
+ toolName: origin.kind === "reply" ? "glove_mesh_reply" : "glove_mesh_send_message",
4887
+ toolInput: { to: message.to, content: message.content, ...message.inReplyTo ? { in_reply_to: message.inReplyTo } : {} },
4888
+ status: "pending",
4889
+ requestedAt: now.toISOString(),
4890
+ expiresAt: new Date(now.getTime() + this.approvalPolicy.expiresAfterMs).toISOString(),
4891
+ // Nobody waits for it and nothing resumes: the decision delivers or drops the message.
4892
+ suspendedAt: now.toISOString(),
4893
+ settledInRun: true,
4894
+ mesh: { threadId: thread.id, messageId: message.id }
4895
+ });
4896
+ await this.withApprovals(async () => {
4897
+ const existing = await Effect5.runPromise(this.data.getApproval(id2));
4898
+ if (existing && existing.mesh?.messageId !== message.id) throw new Error(`Approval "${id2}" already exists.`);
4899
+ if (!existing) await Effect5.runPromise(this.data.putApproval(approval));
4900
+ });
4901
+ return id2;
4902
+ }
4903
+ /** A drafted message's approval was decided: deliver it, or drop it. */
4904
+ async settleMeshDraft(approval) {
4905
+ if (!approval.mesh || approval.status === "pending") return;
4906
+ await this.releaseHeld(approval.mesh.threadId, approval.mesh.messageId, approval.status === "approved" ? "deliver" : "discard", approval.id);
4907
+ }
4908
+ /**
4909
+ * Release a message the application's gate held: deliver it (committed to
4910
+ * your record first) or discard it. The sender is not told either way.
4911
+ * Drafts are decided through their approval instead.
4912
+ */
4913
+ async releaseMeshMessage(threadId, messageId, decision) {
4914
+ const thread = await this.loadThread(threadId);
4915
+ if (!thread) throw new Error(`There is no mesh thread "${threadId}".`);
4916
+ const held = thread.held?.find((item) => item.message.id === messageId);
4917
+ if (!held) throw new Error(`Thread "${threadId}" holds no message "${messageId}".`);
4918
+ if (held.decision === "draft") throw new Error(`Message "${messageId}" is a draft: decide approval "${held.approvalId}" instead.`);
4919
+ await this.releaseHeld(threadId, messageId, decision);
4920
+ return await this.loadThread(threadId) ?? thread;
4921
+ }
4922
+ async releaseHeld(threadId, messageId, decision, approvalId) {
4923
+ let released;
4924
+ const thread = await this.updateThread(threadId, (current) => {
4925
+ released = current.held?.find((item) => item.message.id === messageId && (!approvalId || item.approvalId === approvalId));
4926
+ if (!released) return {};
4927
+ const held = (current.held ?? []).filter((item) => item !== released);
4928
+ if (decision === "discard") return { held };
4929
+ return {
4930
+ held,
4931
+ ...released.onDeliver ?? {},
4932
+ ...released.onDeliver?.status === "replied" ? { question: void 0 } : {},
4933
+ outbox: [...(current.outbox ?? []).filter((entry2) => entry2.message.id !== messageId), { message: released.message, side: released.side }]
4934
+ };
4935
+ });
4936
+ if (!thread || !released) return;
4937
+ this.observability.append({
4938
+ type: decision === "deliver" ? "mesh.released" : "mesh.discarded",
4939
+ category: "system",
4940
+ agent: thread.to.definitionId,
4941
+ data: { threadId, messageId, ...approvalId ? { approvalId } : {} }
4942
+ });
4943
+ if (decision === "deliver") {
4944
+ await this.flushOutbox(threadId).catch((cause) => {
4945
+ this.reportMeshFailure(thread, cause);
4946
+ this.retryOutbox(threadId, 0);
4947
+ });
4948
+ }
4949
+ }
4950
+ /**
4951
+ * A person's message in a thread, entered by the application from its own
4952
+ * record (so it is not committed again). It reaches each agent still in
4953
+ * the thread as a message from a person, and starts the recipient working
4954
+ * again. Pass `id` (your record's message id) to make a retry a no-op.
4955
+ */
4956
+ async meshHumanMessage(threadId, input) {
4957
+ const thread = await this.loadThread(threadId);
4958
+ if (!thread) throw new Error(`There is no mesh thread "${threadId}".`);
4959
+ if (!input.authorId.trim() || !input.text.trim()) throw new Error("A person's message needs an authorId and text.");
4960
+ const id2 = input.id ?? newMessageId();
4961
+ const message = (to) => ({
4962
+ kind: "message",
4963
+ id: id2,
4964
+ threadId,
4965
+ from: { agentId: input.authorId, name: input.name ?? input.authorId, kind: "human" },
4966
+ to,
4967
+ content: input.text,
4968
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
4969
+ });
4970
+ const recipientIn = !isTakenOverBy(thread, thread.to.agentId);
4971
+ await this.updateThread(threadId, (current) => ({
4972
+ ...recipientIn ? { status: "working", question: void 0 } : {},
4973
+ messageIds: current.messageIds.includes(id2) ? current.messageIds : [...current.messageIds, id2]
4974
+ }));
4975
+ if (recipientIn) await this.deliverMesh(this.recipientTarget(thread), "recipient", [message(thread.to.agentId)]);
4976
+ if (!isTakenOverBy(thread, thread.from.agentId)) {
4977
+ await this.deliverMesh(this.starterTarget(thread), "starter", [message(thread.from.agentId)], thread.to.agentId);
4978
+ }
4979
+ this.observability.append({
4980
+ type: "mesh.human.message",
4981
+ category: "system",
4982
+ agent: thread.to.definitionId,
4983
+ data: { threadId, messageId: id2, authorId: input.authorId }
4984
+ });
4985
+ return message(recipientIn ? thread.to.agentId : thread.from.agentId);
4986
+ }
4987
+ /**
4988
+ * A person takes a thread over. The agents named (default: both) leave it:
4989
+ * nothing more is delivered to them in this thread, what they send to it
4990
+ * is refused, and a recipient run working on it is cancelled without a
4991
+ * reply. Messages to a side that left still reach your record.
4992
+ */
4993
+ async meshTakeOver(threadId, options) {
4994
+ const thread = await this.loadThread(threadId);
4995
+ if (!thread) throw new Error(`There is no mesh thread "${threadId}".`);
4996
+ const parties = [thread.from.agentId, thread.to.agentId];
4997
+ if (options.agentId && !parties.includes(options.agentId)) throw new Error(`Agent "${options.agentId}" is not in thread "${threadId}".`);
4998
+ const leaving = options.agentId ? [options.agentId] : parties;
4999
+ const updated = await this.updateThread(threadId, (current) => ({
5000
+ status: "taken-over",
5001
+ question: void 0,
5002
+ takenOver: {
5003
+ by: options.by,
5004
+ agentIds: [.../* @__PURE__ */ new Set([...current.takenOver?.agentIds ?? [], ...leaving])],
5005
+ at: (/* @__PURE__ */ new Date()).toISOString()
5006
+ }
5007
+ }));
5008
+ if (leaving.includes(thread.to.agentId)) {
5009
+ for (const run of await this.listRuns(thread.to.definitionId)) {
5010
+ if (run.conversationId === threadId && (run.status === "pending" || run.status === "running")) await this.cancel(run.id);
5011
+ }
5012
+ }
5013
+ this.observability.append({
5014
+ type: "mesh.taken_over",
5015
+ category: "system",
5016
+ agent: thread.to.definitionId,
5017
+ data: { threadId, by: options.by, agentIds: leaving }
5018
+ });
5019
+ return updated ?? thread;
5020
+ }
4671
5021
  /** A run's mesh call: answered through its request, so the tool hears the outcome. */
4672
5022
  async runMeshCommand(command, parentRunId) {
4673
5023
  const request = await getFoundryCoreCommandRequest(this.coreCommandDirectory, command.id);
@@ -4687,24 +5037,54 @@ var FoundryRuntime = class _FoundryRuntime {
4687
5037
  category: "system",
4688
5038
  agent: command.definitionId,
4689
5039
  runId: parentRunId,
4690
- data: { type: command.type, error }
5040
+ data: { type: command.type, error, ...cause instanceof MeshRefusal ? { reason: cause.reason } : {} }
4691
5041
  });
4692
5042
  await settleFoundryCoreCommandRequest(this.coreCommandDirectory, command.id, { status: "error", error });
4693
5043
  }
4694
5044
  }
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));
5045
+ /**
5046
+ * The agents an agent may see and message: its workspace, or whoever the
5047
+ * application's `mesh.peers` names; then narrowed by its definition's rule.
5048
+ */
5049
+ async meshPeers(sender, runId) {
5050
+ const own = hostedMeshOptions(this.byRoute.get(sender.definitionId)?.definition.mesh)?.peers;
5051
+ const named = this.application.mesh?.peers;
5052
+ let candidates;
5053
+ if (named) {
5054
+ candidates = [];
5055
+ const seen = /* @__PURE__ */ new Set([sender.id]);
5056
+ for (const peer of await resolveResolvable(named(sender, this.meshHookContext(runId)))) {
5057
+ if (!peer || typeof peer.agentId !== "string" || seen.has(peer.agentId)) continue;
5058
+ seen.add(peer.agentId);
5059
+ const agent = await Effect5.runPromise(this.data.getAgent(peer.agentId));
5060
+ if (!agent || !this.byRoute.has(agent.definitionId)) continue;
5061
+ candidates.push(Object.freeze({
5062
+ ...agent,
5063
+ ...peer.name ? { name: peer.name } : {},
5064
+ ...peer.description ? { description: peer.description } : {}
5065
+ }));
5066
+ }
5067
+ } else {
5068
+ candidates = (await Effect5.runPromise(this.data.listAgents())).filter((agent) => agent.workspaceId === sender.workspaceId && agent.id !== sender.id && this.byRoute.has(agent.definitionId));
5069
+ }
5070
+ return candidates.filter((agent) => own?.(sender, agent) ?? true);
4699
5071
  }
4700
5072
  async executeMeshCommand(command, parentRunId) {
4701
5073
  const sender = await Effect5.runPromise(this.data.getAgent(command.agentId));
4702
5074
  if (!sender || sender.workspaceId !== command.workspaceId) {
4703
5075
  throw new Error("A mesh call must come from an agent instance in its workspace.");
4704
5076
  }
5077
+ const run = await this.getRun(parentRunId).catch(() => null);
5078
+ if (run && (run.agentId && run.agentId !== sender.id || run.conversationId && run.conversationId !== command.conversationId)) {
5079
+ throw new Error("A mesh call must come from the run's own agent and conversation.");
5080
+ }
5081
+ const hosted = Boolean(this.application.mesh);
5082
+ const refuse = (reason, wording) => {
5083
+ throw hosted ? new MeshRefusal(wording ?? this.meshRefusal(), reason) : new Error(wording ?? reason);
5084
+ };
4705
5085
  if (command.type === "mesh.list") {
4706
5086
  const filter = command.name?.toLowerCase();
4707
- return (await this.meshPeers(sender)).map(meshIdentity).filter((identity) => !filter || identity.name.toLowerCase().includes(filter));
5087
+ return (await this.meshPeers(sender, parentRunId)).map(meshIdentity).filter((identity) => !filter || identity.name.toLowerCase().includes(filter));
4708
5088
  }
4709
5089
  const conversation = await Effect5.runPromise(this.data.getConversation(command.conversationId));
4710
5090
  if (!conversation || conversation.agentId !== sender.id) {
@@ -4720,11 +5100,23 @@ var FoundryRuntime = class _FoundryRuntime {
4720
5100
  }
4721
5101
  return threads;
4722
5102
  };
5103
+ const origin = (kind) => ({ runId: parentRunId, agent: sender, conversationId: conversation.id, kind });
5104
+ const otherSide = async (thread2, toStarter) => {
5105
+ const agent = await Effect5.runPromise(this.data.getAgent(toStarter ? thread2.from.agentId : thread2.to.agentId));
5106
+ if (!agent) refuse("the other agent is gone", `${toStarter ? thread2.from.name : thread2.to.name} is no longer on the mesh.`);
5107
+ return agent;
5108
+ };
5109
+ const decide = async (send) => {
5110
+ const decision2 = await this.gateMesh({ ...send, sender, senderConversationId: conversation.id }, parentRunId);
5111
+ if (decision2.decision === "refuse") refuse("refused by mesh.authorize", decision2.message);
5112
+ return decision2;
5113
+ };
4723
5114
  if (command.type === "mesh.ack") {
4724
5115
  const thread2 = ownThread?.messageIds.includes(command.messageId) ? ownThread : (await startedThreads()).find((item) => item.messageIds.includes(command.messageId));
4725
5116
  if (!thread2) throw new Error(`There is no message "${command.messageId}" in your threads.`);
5117
+ if (isTakenOverBy(thread2, sender.id)) refuse("the sender was taken off this thread");
4726
5118
  const toStarter = thread2.id === ownThread?.id;
4727
- await this.deliverMesh(toStarter ? this.starterTarget(thread2) : this.recipientTarget(thread2), toStarter ? "starter" : "recipient", [{
5119
+ const ack = {
4728
5120
  kind: "ack",
4729
5121
  id: newMessageId(),
4730
5122
  threadId: thread2.id,
@@ -4733,14 +5125,28 @@ var FoundryRuntime = class _FoundryRuntime {
4733
5125
  content: command.note,
4734
5126
  inReplyTo: command.messageId,
4735
5127
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
4736
- }]);
5128
+ };
5129
+ if (hosted) {
5130
+ const decision2 = await this.gateMesh({
5131
+ kind: "ack",
5132
+ messageId: ack.id,
5133
+ thread: thread2,
5134
+ sender,
5135
+ senderConversationId: conversation.id,
5136
+ recipient: await otherSide(thread2, toStarter),
5137
+ content: ack.content,
5138
+ inReplyTo: command.messageId
5139
+ }, parentRunId);
5140
+ if (decision2.decision !== "deliver") return { acknowledged: command.messageId };
5141
+ }
5142
+ await this.sendToSide(thread2, toStarter ? "starter" : "recipient", [ack], parentRunId);
4737
5143
  return { acknowledged: command.messageId };
4738
5144
  }
4739
5145
  const { message: input } = command;
4740
- const message = (threadId) => ({
5146
+ const message = (threadId2) => ({
4741
5147
  kind: "message",
4742
5148
  id: input.id,
4743
- threadId,
5149
+ threadId: threadId2,
4744
5150
  from: { agentId: sender.id, name: sender.name ?? sender.id },
4745
5151
  to: input.to,
4746
5152
  content: input.content,
@@ -4758,13 +5164,13 @@ var FoundryRuntime = class _FoundryRuntime {
4758
5164
  return { messageId: input.id, threadId: thread2.id, to: input.to, direction };
4759
5165
  };
4760
5166
  if (ownThread && input.to === ownThread.from.agentId && (!input.inReplyTo || ownThread.messageIds.includes(input.inReplyTo))) {
5167
+ if (isTakenOverBy(ownThread, sender.id)) refuse("the sender was taken off this thread");
4761
5168
  const outgoing2 = message(ownThread.id);
5169
+ 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
5170
  await this.updateThread(ownThread.id, (current) => ({
4763
- status: "waiting",
4764
- question: outgoing2.content,
4765
- messageIds: [...current.messageIds, outgoing2.id]
5171
+ messageIds: current.messageIds.includes(outgoing2.id) ? current.messageIds : [...current.messageIds, outgoing2.id]
4766
5172
  }));
4767
- await this.deliverMesh(this.starterTarget(ownThread), "starter", [outgoing2]);
5173
+ await this.dispatchMesh(ownThread, "starter", outgoing2, decision2, origin("message"), { status: "waiting", question: outgoing2.content });
4768
5174
  return sent(ownThread, "to-starter");
4769
5175
  }
4770
5176
  if (input.inReplyTo) {
@@ -4772,70 +5178,119 @@ var FoundryRuntime = class _FoundryRuntime {
4772
5178
  if (!thread2) {
4773
5179
  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
5180
  }
5181
+ if (isTakenOverBy(thread2, sender.id)) refuse("the sender was taken off this thread");
4775
5182
  const outgoing2 = message(thread2.id);
5183
+ 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
5184
  await this.updateThread(thread2.id, (current) => ({
4777
5185
  status: "working",
4778
5186
  question: void 0,
4779
- messageIds: [...current.messageIds, outgoing2.id]
5187
+ messageIds: current.messageIds.includes(outgoing2.id) ? current.messageIds : [...current.messageIds, outgoing2.id]
4780
5188
  }));
4781
- await this.deliverMesh(this.recipientTarget(thread2), "recipient", [outgoing2]);
5189
+ await this.dispatchMesh(thread2, "recipient", outgoing2, decision2, origin("message"));
4782
5190
  return sent(thread2, "to-recipient");
4783
5191
  }
4784
5192
  if (!isThreadId(input.threadId)) throw new Error(`"${input.threadId}" is not a thread id.`);
4785
5193
  if (input.to === sender.id) throw new Error("That is you.");
4786
- const recipient = (await this.meshPeers(sender)).find((agent) => agent.id === input.to);
5194
+ const recipient = (await this.meshPeers(sender, parentRunId)).find((agent) => agent.id === input.to);
4787
5195
  if (!recipient) {
5196
+ if (hosted) refuse("not a peer");
4788
5197
  throw new Error(`There is no agent "${input.to}" you can message. Use glove_mesh_list_agents to see who there is.`);
4789
5198
  }
4790
- const outgoing = message(input.threadId);
5199
+ const decision = hosted ? await decide({ kind: "message", messageId: input.id, recipient, content: input.content }) : { decision: "deliver" };
5200
+ let threadId = input.threadId;
5201
+ let record;
5202
+ const bind = this.application.mesh?.bindThread;
5203
+ if (bind) {
5204
+ const bound = await resolveResolvable(bind({
5205
+ proposedId: input.threadId,
5206
+ sender,
5207
+ senderConversationId: conversation.id,
5208
+ recipient,
5209
+ messageId: input.id,
5210
+ content: input.content
5211
+ }, this.meshHookContext(parentRunId)));
5212
+ if (!bound || typeof bound.threadId !== "string" || !isBindableThreadId(bound.threadId)) {
5213
+ throw new Error("mesh.bindThread must return { threadId } with letters, digits, _ . : or -.");
5214
+ }
5215
+ threadId = bound.threadId;
5216
+ if (bound.record && bound.record !== threadId) record = bound.record;
5217
+ }
5218
+ const existing = threadId !== input.threadId ? await this.loadThread(threadId) : null;
5219
+ if (existing) {
5220
+ if (existing.from.agentId !== sender.id || existing.to.agentId !== recipient.id) {
5221
+ throw new Error(`mesh.bindThread returned "${threadId}", which is another pair's thread.`);
5222
+ }
5223
+ if (isTakenOverBy(existing, sender.id)) refuse("the sender was taken off this thread");
5224
+ const outgoing2 = message(existing.id);
5225
+ await this.updateThread(existing.id, (current) => ({
5226
+ status: "working",
5227
+ question: void 0,
5228
+ messageIds: current.messageIds.includes(outgoing2.id) ? current.messageIds : [...current.messageIds, outgoing2.id]
5229
+ }));
5230
+ if (existing.from.conversationId !== conversation.id) await this.noteStartedThread(conversation.id, existing.id);
5231
+ await this.dispatchMesh(existing, "recipient", outgoing2, decision, origin("message"));
5232
+ return sent(existing, "to-recipient");
5233
+ }
5234
+ if (await Effect5.runPromise(this.data.getConversation(threadId))) {
5235
+ throw new Error(`mesh.bindThread returned "${threadId}", which is already a conversation.`);
5236
+ }
5237
+ const outgoing = message(threadId);
4791
5238
  const now = (/* @__PURE__ */ new Date()).toISOString();
4792
5239
  const thread = Object.freeze({
4793
- id: input.threadId,
5240
+ id: threadId,
4794
5241
  workspaceId: sender.workspaceId,
4795
5242
  from: Object.freeze({
4796
5243
  agentId: sender.id,
4797
5244
  name: sender.name ?? sender.id,
4798
5245
  definitionId: sender.definitionId,
5246
+ ...recipient.workspaceId !== sender.workspaceId ? { workspaceId: sender.workspaceId } : {},
4799
5247
  conversationId: conversation.id,
4800
5248
  runId: parentRunId
4801
5249
  }),
4802
5250
  to: Object.freeze({
4803
5251
  agentId: recipient.id,
4804
5252
  name: recipient.name ?? recipient.id,
4805
- definitionId: recipient.definitionId
5253
+ definitionId: recipient.definitionId,
5254
+ ...recipient.workspaceId !== sender.workspaceId ? { workspaceId: recipient.workspaceId } : {}
4806
5255
  }),
4807
5256
  subject: threadSubject(outgoing.content),
4808
5257
  status: "working",
4809
5258
  messageIds: Object.freeze([outgoing.id]),
5259
+ ...record ? { record } : {},
4810
5260
  createdAt: now,
4811
5261
  updatedAt: now
4812
5262
  });
4813
5263
  await this.createConversation(recipient.id, {
4814
5264
  id: thread.id,
4815
- workspaceId: sender.workspaceId,
5265
+ workspaceId: recipient.workspaceId,
4816
5266
  title: `${thread.from.name}: ${clipTitle(outgoing.content)}`,
4817
5267
  context: { meshThread: thread }
4818
5268
  });
4819
- await this.inConversation(`record:${conversation.id}`, async () => {
4820
- const current = await Effect5.runPromise(this.data.getConversation(conversation.id));
4821
- if (!current) return;
5269
+ await this.noteStartedThread(conversation.id, thread.id);
5270
+ await this.dispatchMesh(thread, "recipient", outgoing, decision, origin("message"));
5271
+ return sent(thread, "new");
5272
+ }
5273
+ /** Remember on the starter's conversation that it started a thread. */
5274
+ async noteStartedThread(conversationId, threadId) {
5275
+ await this.inConversation(`record:${conversationId}`, async () => {
5276
+ const current = await Effect5.runPromise(this.data.getConversation(conversationId));
5277
+ if (!current || startedThreadIds(current.context).includes(threadId)) return;
4822
5278
  await Effect5.runPromise(this.data.putConversation({
4823
5279
  ...current,
4824
5280
  context: Object.freeze({
4825
5281
  ...current.context,
4826
- meshThreads: [...startedThreadIds(current.context), thread.id]
5282
+ meshThreads: [...startedThreadIds(current.context), threadId]
4827
5283
  }),
4828
- updatedAt: now
5284
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
4829
5285
  }));
4830
5286
  });
4831
- await this.deliverMesh(this.recipientTarget(thread), "recipient", [outgoing]);
4832
- return sent(thread, "new");
4833
5287
  }
4834
5288
  /** When the recipient's run on a thread ends, its reply (or its failure) goes back. */
4835
5289
  async settleThread(event, run, steered) {
4836
5290
  const thread = await this.loadThread(run.conversationId);
4837
5291
  if (!thread || run.agentId !== thread.to.agentId) return;
4838
5292
  if (this.stopping && event.status !== "completed") return;
5293
+ if (isTakenOverBy(thread, thread.to.agentId)) return;
4839
5294
  const reply = (kind, content) => ({
4840
5295
  kind,
4841
5296
  id: `msg_${kind}_${event.run.id}`,
@@ -4855,19 +5310,39 @@ var FoundryRuntime = class _FoundryRuntime {
4855
5310
  }
4856
5311
  const message2 = reply("reply", text);
4857
5312
  await this.updateThread(thread.id, (current) => ({
4858
- status: "replied",
4859
- reply: text,
4860
- question: void 0,
4861
5313
  messageIds: current.messageIds.includes(message2.id) ? current.messageIds : [...current.messageIds, message2.id]
4862
5314
  }));
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
- });
5315
+ const replied = { status: "replied", reply: text, question: void 0 };
5316
+ const decision = await this.gateReply(thread, message2, event.run.id);
5317
+ if (decision.decision === "refuse") {
5318
+ await this.updateThread(thread.id, { status: "replied", question: void 0 });
5319
+ this.observability.append({
5320
+ type: "mesh.refused",
5321
+ category: "system",
5322
+ agent: thread.to.definitionId,
5323
+ runId: event.run.id,
5324
+ data: { type: "mesh.reply", threadId: thread.id, messageId: message2.id, error: decision.message }
5325
+ });
5326
+ return;
5327
+ }
5328
+ const recipient = await Effect5.runPromise(this.data.getAgent(thread.to.agentId));
5329
+ await this.dispatchMesh(
5330
+ thread,
5331
+ "starter",
5332
+ message2,
5333
+ decision,
5334
+ { 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" },
5335
+ replied
5336
+ );
5337
+ if (decision.decision === "deliver") {
5338
+ this.observability.append({
5339
+ type: "mesh.thread.replied",
5340
+ category: "system",
5341
+ agent: thread.to.definitionId,
5342
+ runId: event.run.id,
5343
+ data: { threadId: thread.id }
5344
+ });
5345
+ }
4871
5346
  return;
4872
5347
  }
4873
5348
  if (event.status === "cancelled" && steered) return;
@@ -4878,7 +5353,7 @@ var FoundryRuntime = class _FoundryRuntime {
4878
5353
  error,
4879
5354
  messageIds: current.messageIds.includes(message.id) ? current.messageIds : [...current.messageIds, message.id]
4880
5355
  }));
4881
- await this.deliverMesh(this.starterTarget(thread), "starter", [message]);
5356
+ await this.sendToSide(thread, "starter", [message], event.run.id);
4882
5357
  this.observability.append({
4883
5358
  type: event.status === "cancelled" ? "mesh.thread.cancelled" : "mesh.thread.failed",
4884
5359
  category: "system",
@@ -4887,8 +5362,52 @@ var FoundryRuntime = class _FoundryRuntime {
4887
5362
  data: { threadId: thread.id, error }
4888
5363
  });
4889
5364
  }
5365
+ /** The gate for a recipient's final answer, when the application has one. */
5366
+ async gateReply(thread, message, runId) {
5367
+ if (!this.application.mesh?.authorize) return { decision: "deliver" };
5368
+ const [sender, recipient] = await Promise.all([
5369
+ Effect5.runPromise(this.data.getAgent(thread.to.agentId)),
5370
+ Effect5.runPromise(this.data.getAgent(thread.from.agentId))
5371
+ ]);
5372
+ if (!sender || !recipient) return { decision: "refuse", message: this.meshRefusal() };
5373
+ return this.gateMesh({
5374
+ kind: "reply",
5375
+ messageId: message.id,
5376
+ thread,
5377
+ sender,
5378
+ senderConversationId: thread.id,
5379
+ recipient,
5380
+ content: message.content
5381
+ }, runId);
5382
+ }
5383
+ /**
5384
+ * A run whose definition restricts built-ins may only send the commands its
5385
+ * mounted tools send. Anything else is refused, however it was emitted.
5386
+ */
5387
+ withheldBuiltinRefusal(command, runId) {
5388
+ const mounted = this.runBuiltins.get(runId);
5389
+ if (!mounted) return null;
5390
+ const tools = builtinsForCommand(command.type);
5391
+ if (!tools) return null;
5392
+ if (tools.some((name) => mounted.tools.has(name))) return null;
5393
+ if (command.type === "transmit" && mounted.transmissionTools) return null;
5394
+ return `This run has no tool that can send "${command.type}".`;
5395
+ }
5396
+ async refuseCoreCommand(command, runId, error, route) {
5397
+ this.observability.append({
5398
+ type: "foundry.builtin.refused",
5399
+ category: "system",
5400
+ agent: route,
5401
+ runId,
5402
+ data: { type: command.type, error }
5403
+ });
5404
+ if (await getFoundryCoreCommandRequest(this.coreCommandDirectory, command.id).catch(() => null)) {
5405
+ await settleFoundryCoreCommandRequest(this.coreCommandDirectory, command.id, { status: "error", error }).catch(() => void 0);
5406
+ }
5407
+ }
4890
5408
  async handleRunSettled(event) {
4891
5409
  void this.settleApprovalsOf(event.run.id).catch((cause) => this.reportApprovalFailure(event.run.id, cause));
5410
+ this.runBuiltins.delete(event.run.id);
4892
5411
  this.recentlySettledRuns.set(event.run.id, event.status);
4893
5412
  if (this.recentlySettledRuns.size > 1e3) this.recentlySettledRuns.delete(this.recentlySettledRuns.keys().next().value);
4894
5413
  void this.settleOccurrence(event.run.id, event.status).catch((cause) => {
@@ -4914,7 +5433,7 @@ var FoundryRuntime = class _FoundryRuntime {
4914
5433
  };
4915
5434
  const steered = this.steeredRuns.delete(event.run.id);
4916
5435
  const run = this.toFoundryRun(event.run);
4917
- if (run.conversationId && isThreadId(run.conversationId)) {
5436
+ if (run.conversationId && (isThreadId(run.conversationId) || this.application.mesh?.bindThread && await this.loadThread(run.conversationId))) {
4918
5437
  await finishDelivery();
4919
5438
  await this.settleThread(event, run, steered);
4920
5439
  return;
@@ -9070,6 +9589,63 @@ var FoundryServer = class {
9070
9589
  ));
9071
9590
  return;
9072
9591
  }
9592
+ if (url.pathname === "/api/threads" && method === "GET") {
9593
+ const status = url.searchParams.get("status");
9594
+ json(response, 200, await this.runtime.listThreads({
9595
+ ...url.searchParams.get("agentId") ? { agentId: url.searchParams.get("agentId") } : {},
9596
+ ...url.searchParams.get("conversationId") ? { conversationId: url.searchParams.get("conversationId") } : {},
9597
+ ...url.searchParams.get("to") ? { to: url.searchParams.get("to") } : {},
9598
+ ...status ? { status } : {}
9599
+ }));
9600
+ return;
9601
+ }
9602
+ const threadMatch = url.pathname.match(/^\/api\/threads\/([^/]+)(?:\/(messages|take-over|held\/([^/]+)))?$/);
9603
+ if (threadMatch) {
9604
+ const threadId = decodeURIComponent(threadMatch[1]);
9605
+ const thread = await this.runtime.getThread(threadId);
9606
+ if (!thread) throw new RequestError(404, "Foundry mesh thread was not found.");
9607
+ const action = threadMatch[2];
9608
+ if (!action && method === "GET") {
9609
+ json(response, 200, thread);
9610
+ return;
9611
+ }
9612
+ if (method === "POST") {
9613
+ const body = await readJson(request);
9614
+ if (action === "messages") {
9615
+ if (typeof body.authorId !== "string" || !body.authorId.trim() || typeof body.text !== "string" || !body.text.trim()) {
9616
+ throw new RequestError(400, "authorId and text are required.");
9617
+ }
9618
+ json(response, 201, await this.runtime.meshHumanMessage(threadId, {
9619
+ authorId: body.authorId,
9620
+ text: body.text,
9621
+ ...typeof body.name === "string" ? { name: body.name } : {},
9622
+ ...typeof body.id === "string" ? { id: body.id } : {}
9623
+ }));
9624
+ return;
9625
+ }
9626
+ if (action === "take-over") {
9627
+ if (typeof body.by !== "string" || !body.by.trim()) throw new RequestError(400, "by is required.");
9628
+ if (body.agentId !== void 0 && typeof body.agentId !== "string") throw new RequestError(400, "agentId must be a string.");
9629
+ if (typeof body.agentId === "string" && body.agentId !== thread.from.agentId && body.agentId !== thread.to.agentId) {
9630
+ throw new RequestError(400, "agentId is not in this thread.");
9631
+ }
9632
+ json(response, 200, await this.runtime.meshTakeOver(threadId, {
9633
+ by: body.by,
9634
+ ...typeof body.agentId === "string" ? { agentId: body.agentId } : {}
9635
+ }));
9636
+ return;
9637
+ }
9638
+ if (action?.startsWith("held/")) {
9639
+ const messageId = decodeURIComponent(threadMatch[3]);
9640
+ if (body.decision !== "deliver" && body.decision !== "discard") throw new RequestError(400, 'decision must be "deliver" or "discard".');
9641
+ const held = thread.held?.find((item) => item.message.id === messageId);
9642
+ if (!held) throw new RequestError(404, "The thread holds no such message.");
9643
+ if (held.decision === "draft") throw new RequestError(409, `This message is a draft: decide approval "${held.approvalId}" instead.`);
9644
+ json(response, 200, await this.runtime.releaseMeshMessage(threadId, messageId, body.decision));
9645
+ return;
9646
+ }
9647
+ }
9648
+ }
9073
9649
  const transmissionFire = url.pathname.match(/^\/api\/transmissions\/([^/]+)\/fire$/);
9074
9650
  if (transmissionFire && method === "POST") {
9075
9651
  const body = await readJson(request);