glove-foundry 0.10.1 → 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.
- package/dist/{chunk-L72FKI7P.js → chunk-DAYYZPVE.js} +620 -57
- package/dist/{chunk-X3HZYVZS.js → chunk-SEP6QFRK.js} +1 -1
- package/dist/{chunk-VLD3DKPI.js → chunk-UGYXSWPE.js} +131 -1
- package/dist/{chunk-CYOIHSUX.js → chunk-WK2O4GIB.js} +6 -0
- package/dist/{chunk-J6NHL4SM.js → chunk-WRGSTYBW.js} +121 -8
- package/dist/cli.js +4 -4
- package/dist/{client-HM2x2-Ut.d.ts → client-Dy6_aqsi.d.ts} +93 -5
- package/dist/client.d.ts +2 -2
- package/dist/{event-delivery-C7rYiNPs.d.ts → event-delivery-CWxarW6L.d.ts} +646 -293
- package/dist/execution-agent.js +1 -1
- package/dist/execution-daemon.js +1 -1
- package/dist/execution-loader.js +132 -14
- package/dist/index.d.ts +9 -5
- package/dist/index.js +50 -5
- package/dist/voice.d.ts +81 -3
- package/dist/voice.js +323 -21
- package/docs/architecture.md +8 -0
- package/docs/building-with-foundry.md +1 -0
- package/package.json +6 -6
|
@@ -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-
|
|
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-
|
|
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-
|
|
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;
|
|
@@ -1789,10 +1803,14 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
1789
1803
|
});
|
|
1790
1804
|
/** Pending inbound records each run is handling, so they are cleared when it settles. */
|
|
1791
1805
|
eventTimers = /* @__PURE__ */ new Map();
|
|
1806
|
+
/** Events a run withheld because preparing them failed: attempts so far and the pending retry. */
|
|
1807
|
+
eventRetries = /* @__PURE__ */ new Map();
|
|
1792
1808
|
completedEventRuns = /* @__PURE__ */ new Map();
|
|
1793
1809
|
pendingInboundByRun = /* @__PURE__ */ new Map();
|
|
1794
1810
|
/** Recently settled runs, for a record assigned to a run that already finished. */
|
|
1795
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();
|
|
1796
1814
|
/** How runs treat approvals; durable when the data adapter can keep them. */
|
|
1797
1815
|
approvalPolicy;
|
|
1798
1816
|
/** Approval records change one at a time. */
|
|
@@ -1893,7 +1911,27 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
1893
1911
|
void this.recordApprovalEvent(event.type, event.data).catch((cause) => this.reportApprovalFailure(event.run.id, cause));
|
|
1894
1912
|
return;
|
|
1895
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
|
+
}
|
|
1896
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
|
+
}
|
|
1897
1935
|
void this.executeCoreCommand(event.data, event.run.id).catch((cause) => {
|
|
1898
1936
|
this.observability.append({
|
|
1899
1937
|
type: "core.command.failed",
|
|
@@ -2077,6 +2115,8 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
2077
2115
|
this.stopping = true;
|
|
2078
2116
|
for (const timer of this.eventTimers.values()) clearTimeout(timer);
|
|
2079
2117
|
this.eventTimers.clear();
|
|
2118
|
+
for (const retry of this.eventRetries.values()) if (retry.timer) clearTimeout(retry.timer);
|
|
2119
|
+
this.eventRetries.clear();
|
|
2080
2120
|
for (const timer of this.activationTimers.values()) clearTimeout(timer);
|
|
2081
2121
|
this.activationTimers.clear();
|
|
2082
2122
|
this.activationDispatches.clear();
|
|
@@ -2770,6 +2810,10 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
2770
2810
|
return { decided: decided2, live: waiting };
|
|
2771
2811
|
});
|
|
2772
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
|
+
}
|
|
2773
2817
|
if (live) return decided;
|
|
2774
2818
|
return this.resumeApproval(decided).catch((cause) => {
|
|
2775
2819
|
this.reportApprovalFailure(decided.runId, cause);
|
|
@@ -4128,6 +4172,49 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
4128
4172
|
await Effect5.runPromise(this.data.putEvent({ ...record, runId, ...acknowledged ? { status: "acknowledged" } : {} }));
|
|
4129
4173
|
}
|
|
4130
4174
|
}
|
|
4175
|
+
/**
|
|
4176
|
+
* Deliver events again after a delay that doubles each time (1s up to 5
|
|
4177
|
+
* minutes), when a run withheld them because preparing them failed. They
|
|
4178
|
+
* stay pending meanwhile; a restart delivers them as usual.
|
|
4179
|
+
*/
|
|
4180
|
+
scheduleEventRetries(ids) {
|
|
4181
|
+
if (this.stopping) return;
|
|
4182
|
+
for (const id2 of ids) {
|
|
4183
|
+
const retry = this.eventRetries.get(id2) ?? { attempts: 0 };
|
|
4184
|
+
if (retry.timer) continue;
|
|
4185
|
+
retry.attempts++;
|
|
4186
|
+
const delay = Math.min(1e3 * 2 ** (retry.attempts - 1), 3e5);
|
|
4187
|
+
retry.timer = setTimeout(() => {
|
|
4188
|
+
retry.timer = void 0;
|
|
4189
|
+
void this.retryEvent(id2).catch((cause) => this.reportDeliveryFailure("event-retry", cause));
|
|
4190
|
+
}, delay);
|
|
4191
|
+
retry.timer.unref?.();
|
|
4192
|
+
this.eventRetries.set(id2, retry);
|
|
4193
|
+
}
|
|
4194
|
+
}
|
|
4195
|
+
async retryEvent(id2) {
|
|
4196
|
+
if (this.stopping || !this.data.listEvents) return;
|
|
4197
|
+
const record = (await Effect5.runPromise(this.data.listEvents())).find((item) => item.id === id2);
|
|
4198
|
+
if (!record || record.status !== "pending") {
|
|
4199
|
+
this.eventRetries.delete(id2);
|
|
4200
|
+
return;
|
|
4201
|
+
}
|
|
4202
|
+
const owner = await Effect5.runPromise(this.data.getAgent(record.target.agentId));
|
|
4203
|
+
if (!owner) {
|
|
4204
|
+
this.eventRetries.delete(id2);
|
|
4205
|
+
return;
|
|
4206
|
+
}
|
|
4207
|
+
try {
|
|
4208
|
+
await this.assertDurableActive(owner);
|
|
4209
|
+
} catch {
|
|
4210
|
+
return;
|
|
4211
|
+
}
|
|
4212
|
+
await this.deliver(
|
|
4213
|
+
{ ...record.target, definitionId: record.definitionId, workspaceId: record.workspaceId },
|
|
4214
|
+
[{ ...record.delivery, durable: { id: record.id, event: record.event, policy: record.policy } }],
|
|
4215
|
+
true
|
|
4216
|
+
);
|
|
4217
|
+
}
|
|
4131
4218
|
async finishEvents(runId, consumed) {
|
|
4132
4219
|
if (!this.data.listEvents || !this.data.putEvent || this.stopping) return;
|
|
4133
4220
|
const run = await this.getRun(runId);
|
|
@@ -4144,6 +4231,9 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
4144
4231
|
continue;
|
|
4145
4232
|
}
|
|
4146
4233
|
await Effect5.runPromise(this.data.putEvent({ ...record, status: record.event.expiresAt && Date.parse(record.event.expiresAt) <= Date.now() ? "expired" : "acknowledged", runId }));
|
|
4234
|
+
const retry = this.eventRetries.get(record.id);
|
|
4235
|
+
if (retry?.timer) clearTimeout(retry.timer);
|
|
4236
|
+
this.eventRetries.delete(record.id);
|
|
4147
4237
|
if ((record.delivery.kind === "transmission" || record.delivery.kind === "agent-message") && this.data.deletePendingInbound) {
|
|
4148
4238
|
await Effect5.runPromise(this.data.deletePendingInbound(record.delivery.pendingId));
|
|
4149
4239
|
}
|
|
@@ -4539,16 +4629,25 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
4539
4629
|
return found.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
|
|
4540
4630
|
}
|
|
4541
4631
|
/**
|
|
4542
|
-
*
|
|
4543
|
-
*
|
|
4544
|
-
*
|
|
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.
|
|
4545
4637
|
*/
|
|
4546
4638
|
async redeliverThreads() {
|
|
4547
4639
|
for (const thread of await this.listThreads()) {
|
|
4548
|
-
if (
|
|
4549
|
-
|
|
4550
|
-
|
|
4551
|
-
|
|
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
|
+
}
|
|
4552
4651
|
}
|
|
4553
4652
|
}
|
|
4554
4653
|
/** The open threads a conversation started, oldest first. */
|
|
@@ -4562,19 +4661,22 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
4562
4661
|
}
|
|
4563
4662
|
async loadThread(id2) {
|
|
4564
4663
|
const conversation = await Effect5.runPromise(this.data.getConversation(id2));
|
|
4565
|
-
|
|
4664
|
+
const thread = threadFromContext(conversation?.context);
|
|
4665
|
+
return thread && thread.id === id2 ? thread : null;
|
|
4566
4666
|
}
|
|
4567
4667
|
updateThread(id2, change) {
|
|
4568
4668
|
return this.inConversation(`record:${id2}`, async () => {
|
|
4569
4669
|
const conversation = await Effect5.runPromise(this.data.getConversation(id2));
|
|
4570
4670
|
const current = threadFromContext(conversation?.context);
|
|
4571
4671
|
if (!conversation || !current) return null;
|
|
4572
|
-
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;
|
|
4573
4674
|
if (Object.keys(patch).length === 0) return current;
|
|
4574
4675
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
4575
4676
|
const merged = { ...current, ...patch, updatedAt: now };
|
|
4576
4677
|
delete merged.undelivered;
|
|
4577
4678
|
delete merged.pending;
|
|
4679
|
+
for (const key of ["held", "outbox"]) if (Array.isArray(merged[key]) && merged[key].length === 0) delete merged[key];
|
|
4578
4680
|
for (const key of Object.keys(merged)) if (merged[key] === void 0) delete merged[key];
|
|
4579
4681
|
const next = Object.freeze(merged);
|
|
4580
4682
|
await Effect5.runPromise(this.data.putConversation(Object.freeze({
|
|
@@ -4590,7 +4692,7 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
4590
4692
|
definitionId: thread.from.definitionId,
|
|
4591
4693
|
agentId: thread.from.agentId,
|
|
4592
4694
|
conversationId: thread.from.conversationId,
|
|
4593
|
-
workspaceId: thread.workspaceId
|
|
4695
|
+
workspaceId: thread.from.workspaceId ?? thread.workspaceId
|
|
4594
4696
|
};
|
|
4595
4697
|
}
|
|
4596
4698
|
recipientTarget(thread) {
|
|
@@ -4598,16 +4700,25 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
4598
4700
|
definitionId: thread.to.definitionId,
|
|
4599
4701
|
agentId: thread.to.agentId,
|
|
4600
4702
|
conversationId: thread.id,
|
|
4601
|
-
workspaceId: thread.workspaceId
|
|
4703
|
+
workspaceId: thread.to.workspaceId ?? thread.workspaceId
|
|
4602
4704
|
};
|
|
4603
4705
|
}
|
|
4706
|
+
sideTarget(thread, side) {
|
|
4707
|
+
return side === "starter" ? this.starterTarget(thread) : this.recipientTarget(thread);
|
|
4708
|
+
}
|
|
4604
4709
|
/**
|
|
4605
4710
|
* Hand mesh messages to one side of a thread. Messages, replies and
|
|
4606
4711
|
* failures go through durable delivery. A read receipt only ever reaches a
|
|
4607
4712
|
* run that is listening, and is dropped otherwise.
|
|
4608
4713
|
*/
|
|
4609
|
-
async deliverMesh(target, side, messages) {
|
|
4610
|
-
const delivery = (message) => ({
|
|
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
|
+
});
|
|
4611
4722
|
const receipts = messages.filter((message) => message.kind === "ack");
|
|
4612
4723
|
if (receipts.length) {
|
|
4613
4724
|
await this.inConversation(target.conversationId, async () => {
|
|
@@ -4618,6 +4729,288 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
4618
4729
|
const durable = messages.filter((message) => message.kind !== "ack");
|
|
4619
4730
|
if (durable.length) await this.deliver(target, durable.map(delivery));
|
|
4620
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
|
+
}
|
|
4621
5014
|
/** A run's mesh call: answered through its request, so the tool hears the outcome. */
|
|
4622
5015
|
async runMeshCommand(command, parentRunId) {
|
|
4623
5016
|
const request = await getFoundryCoreCommandRequest(this.coreCommandDirectory, command.id);
|
|
@@ -4637,24 +5030,54 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
4637
5030
|
category: "system",
|
|
4638
5031
|
agent: command.definitionId,
|
|
4639
5032
|
runId: parentRunId,
|
|
4640
|
-
data: { type: command.type, error }
|
|
5033
|
+
data: { type: command.type, error, ...cause instanceof MeshRefusal ? { reason: cause.reason } : {} }
|
|
4641
5034
|
});
|
|
4642
5035
|
await settleFoundryCoreCommandRequest(this.coreCommandDirectory, command.id, { status: "error", error });
|
|
4643
5036
|
}
|
|
4644
5037
|
}
|
|
4645
|
-
/**
|
|
4646
|
-
|
|
4647
|
-
|
|
4648
|
-
|
|
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);
|
|
4649
5064
|
}
|
|
4650
5065
|
async executeMeshCommand(command, parentRunId) {
|
|
4651
5066
|
const sender = await Effect5.runPromise(this.data.getAgent(command.agentId));
|
|
4652
5067
|
if (!sender || sender.workspaceId !== command.workspaceId) {
|
|
4653
5068
|
throw new Error("A mesh call must come from an agent instance in its workspace.");
|
|
4654
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
|
+
};
|
|
4655
5078
|
if (command.type === "mesh.list") {
|
|
4656
5079
|
const filter = command.name?.toLowerCase();
|
|
4657
|
-
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));
|
|
4658
5081
|
}
|
|
4659
5082
|
const conversation = await Effect5.runPromise(this.data.getConversation(command.conversationId));
|
|
4660
5083
|
if (!conversation || conversation.agentId !== sender.id) {
|
|
@@ -4670,11 +5093,23 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
4670
5093
|
}
|
|
4671
5094
|
return threads;
|
|
4672
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
|
+
};
|
|
4673
5107
|
if (command.type === "mesh.ack") {
|
|
4674
5108
|
const thread2 = ownThread?.messageIds.includes(command.messageId) ? ownThread : (await startedThreads()).find((item) => item.messageIds.includes(command.messageId));
|
|
4675
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");
|
|
4676
5111
|
const toStarter = thread2.id === ownThread?.id;
|
|
4677
|
-
|
|
5112
|
+
const ack = {
|
|
4678
5113
|
kind: "ack",
|
|
4679
5114
|
id: newMessageId(),
|
|
4680
5115
|
threadId: thread2.id,
|
|
@@ -4683,14 +5118,28 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
4683
5118
|
content: command.note,
|
|
4684
5119
|
inReplyTo: command.messageId,
|
|
4685
5120
|
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
4686
|
-
}
|
|
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);
|
|
4687
5136
|
return { acknowledged: command.messageId };
|
|
4688
5137
|
}
|
|
4689
5138
|
const { message: input } = command;
|
|
4690
|
-
const message = (
|
|
5139
|
+
const message = (threadId2) => ({
|
|
4691
5140
|
kind: "message",
|
|
4692
5141
|
id: input.id,
|
|
4693
|
-
threadId,
|
|
5142
|
+
threadId: threadId2,
|
|
4694
5143
|
from: { agentId: sender.id, name: sender.name ?? sender.id },
|
|
4695
5144
|
to: input.to,
|
|
4696
5145
|
content: input.content,
|
|
@@ -4708,13 +5157,13 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
4708
5157
|
return { messageId: input.id, threadId: thread2.id, to: input.to, direction };
|
|
4709
5158
|
};
|
|
4710
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");
|
|
4711
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" };
|
|
4712
5163
|
await this.updateThread(ownThread.id, (current) => ({
|
|
4713
|
-
|
|
4714
|
-
question: outgoing2.content,
|
|
4715
|
-
messageIds: [...current.messageIds, outgoing2.id]
|
|
5164
|
+
messageIds: current.messageIds.includes(outgoing2.id) ? current.messageIds : [...current.messageIds, outgoing2.id]
|
|
4716
5165
|
}));
|
|
4717
|
-
await this.
|
|
5166
|
+
await this.dispatchMesh(ownThread, "starter", outgoing2, decision2, origin("message"), { status: "waiting", question: outgoing2.content });
|
|
4718
5167
|
return sent(ownThread, "to-starter");
|
|
4719
5168
|
}
|
|
4720
5169
|
if (input.inReplyTo) {
|
|
@@ -4722,70 +5171,119 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
4722
5171
|
if (!thread2) {
|
|
4723
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.`);
|
|
4724
5173
|
}
|
|
5174
|
+
if (isTakenOverBy(thread2, sender.id)) refuse("the sender was taken off this thread");
|
|
4725
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" };
|
|
4726
5177
|
await this.updateThread(thread2.id, (current) => ({
|
|
4727
5178
|
status: "working",
|
|
4728
5179
|
question: void 0,
|
|
4729
|
-
messageIds: [...current.messageIds, outgoing2.id]
|
|
5180
|
+
messageIds: current.messageIds.includes(outgoing2.id) ? current.messageIds : [...current.messageIds, outgoing2.id]
|
|
4730
5181
|
}));
|
|
4731
|
-
await this.
|
|
5182
|
+
await this.dispatchMesh(thread2, "recipient", outgoing2, decision2, origin("message"));
|
|
4732
5183
|
return sent(thread2, "to-recipient");
|
|
4733
5184
|
}
|
|
4734
5185
|
if (!isThreadId(input.threadId)) throw new Error(`"${input.threadId}" is not a thread id.`);
|
|
4735
5186
|
if (input.to === sender.id) throw new Error("That is you.");
|
|
4736
|
-
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);
|
|
4737
5188
|
if (!recipient) {
|
|
5189
|
+
if (hosted) refuse("not a peer");
|
|
4738
5190
|
throw new Error(`There is no agent "${input.to}" you can message. Use glove_mesh_list_agents to see who there is.`);
|
|
4739
5191
|
}
|
|
4740
|
-
const
|
|
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);
|
|
4741
5231
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
4742
5232
|
const thread = Object.freeze({
|
|
4743
|
-
id:
|
|
5233
|
+
id: threadId,
|
|
4744
5234
|
workspaceId: sender.workspaceId,
|
|
4745
5235
|
from: Object.freeze({
|
|
4746
5236
|
agentId: sender.id,
|
|
4747
5237
|
name: sender.name ?? sender.id,
|
|
4748
5238
|
definitionId: sender.definitionId,
|
|
5239
|
+
...recipient.workspaceId !== sender.workspaceId ? { workspaceId: sender.workspaceId } : {},
|
|
4749
5240
|
conversationId: conversation.id,
|
|
4750
5241
|
runId: parentRunId
|
|
4751
5242
|
}),
|
|
4752
5243
|
to: Object.freeze({
|
|
4753
5244
|
agentId: recipient.id,
|
|
4754
5245
|
name: recipient.name ?? recipient.id,
|
|
4755
|
-
definitionId: recipient.definitionId
|
|
5246
|
+
definitionId: recipient.definitionId,
|
|
5247
|
+
...recipient.workspaceId !== sender.workspaceId ? { workspaceId: recipient.workspaceId } : {}
|
|
4756
5248
|
}),
|
|
4757
5249
|
subject: threadSubject(outgoing.content),
|
|
4758
5250
|
status: "working",
|
|
4759
5251
|
messageIds: Object.freeze([outgoing.id]),
|
|
5252
|
+
...record ? { record } : {},
|
|
4760
5253
|
createdAt: now,
|
|
4761
5254
|
updatedAt: now
|
|
4762
5255
|
});
|
|
4763
5256
|
await this.createConversation(recipient.id, {
|
|
4764
5257
|
id: thread.id,
|
|
4765
|
-
workspaceId:
|
|
5258
|
+
workspaceId: recipient.workspaceId,
|
|
4766
5259
|
title: `${thread.from.name}: ${clipTitle(outgoing.content)}`,
|
|
4767
5260
|
context: { meshThread: thread }
|
|
4768
5261
|
});
|
|
4769
|
-
await this.
|
|
4770
|
-
|
|
4771
|
-
|
|
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;
|
|
4772
5271
|
await Effect5.runPromise(this.data.putConversation({
|
|
4773
5272
|
...current,
|
|
4774
5273
|
context: Object.freeze({
|
|
4775
5274
|
...current.context,
|
|
4776
|
-
meshThreads: [...startedThreadIds(current.context),
|
|
5275
|
+
meshThreads: [...startedThreadIds(current.context), threadId]
|
|
4777
5276
|
}),
|
|
4778
|
-
updatedAt:
|
|
5277
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
4779
5278
|
}));
|
|
4780
5279
|
});
|
|
4781
|
-
await this.deliverMesh(this.recipientTarget(thread), "recipient", [outgoing]);
|
|
4782
|
-
return sent(thread, "new");
|
|
4783
5280
|
}
|
|
4784
5281
|
/** When the recipient's run on a thread ends, its reply (or its failure) goes back. */
|
|
4785
5282
|
async settleThread(event, run, steered) {
|
|
4786
5283
|
const thread = await this.loadThread(run.conversationId);
|
|
4787
5284
|
if (!thread || run.agentId !== thread.to.agentId) return;
|
|
4788
5285
|
if (this.stopping && event.status !== "completed") return;
|
|
5286
|
+
if (isTakenOverBy(thread, thread.to.agentId)) return;
|
|
4789
5287
|
const reply = (kind, content) => ({
|
|
4790
5288
|
kind,
|
|
4791
5289
|
id: `msg_${kind}_${event.run.id}`,
|
|
@@ -4805,19 +5303,39 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
4805
5303
|
}
|
|
4806
5304
|
const message2 = reply("reply", text);
|
|
4807
5305
|
await this.updateThread(thread.id, (current) => ({
|
|
4808
|
-
status: "replied",
|
|
4809
|
-
reply: text,
|
|
4810
|
-
question: void 0,
|
|
4811
5306
|
messageIds: current.messageIds.includes(message2.id) ? current.messageIds : [...current.messageIds, message2.id]
|
|
4812
5307
|
}));
|
|
4813
|
-
|
|
4814
|
-
this.
|
|
4815
|
-
|
|
4816
|
-
|
|
4817
|
-
|
|
4818
|
-
|
|
4819
|
-
|
|
4820
|
-
|
|
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
|
+
}
|
|
4821
5339
|
return;
|
|
4822
5340
|
}
|
|
4823
5341
|
if (event.status === "cancelled" && steered) return;
|
|
@@ -4828,7 +5346,7 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
4828
5346
|
error,
|
|
4829
5347
|
messageIds: current.messageIds.includes(message.id) ? current.messageIds : [...current.messageIds, message.id]
|
|
4830
5348
|
}));
|
|
4831
|
-
await this.
|
|
5349
|
+
await this.sendToSide(thread, "starter", [message], event.run.id);
|
|
4832
5350
|
this.observability.append({
|
|
4833
5351
|
type: event.status === "cancelled" ? "mesh.thread.cancelled" : "mesh.thread.failed",
|
|
4834
5352
|
category: "system",
|
|
@@ -4837,8 +5355,52 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
4837
5355
|
data: { threadId: thread.id, error }
|
|
4838
5356
|
});
|
|
4839
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
|
+
}
|
|
4840
5401
|
async handleRunSettled(event) {
|
|
4841
5402
|
void this.settleApprovalsOf(event.run.id).catch((cause) => this.reportApprovalFailure(event.run.id, cause));
|
|
5403
|
+
this.runBuiltins.delete(event.run.id);
|
|
4842
5404
|
this.recentlySettledRuns.set(event.run.id, event.status);
|
|
4843
5405
|
if (this.recentlySettledRuns.size > 1e3) this.recentlySettledRuns.delete(this.recentlySettledRuns.keys().next().value);
|
|
4844
5406
|
void this.settleOccurrence(event.run.id, event.status).catch((cause) => {
|
|
@@ -4858,12 +5420,13 @@ var FoundryRuntime = class _FoundryRuntime {
|
|
|
4858
5420
|
if (event.status === "completed") {
|
|
4859
5421
|
const result = parseJson(event.output);
|
|
4860
5422
|
await this.finishEvents(event.run.id, result?.consumedEventIds ?? []);
|
|
5423
|
+
if (result?.retryEventIds?.length) this.scheduleEventRetries(result.retryEventIds);
|
|
4861
5424
|
}
|
|
4862
5425
|
await this.finishPendingInbound(event.run.id).catch((cause) => this.reportDeliveryFailure(this.toFoundryRun(event.run).conversationId ?? "settle", cause));
|
|
4863
5426
|
};
|
|
4864
5427
|
const steered = this.steeredRuns.delete(event.run.id);
|
|
4865
5428
|
const run = this.toFoundryRun(event.run);
|
|
4866
|
-
if (run.conversationId && isThreadId(run.conversationId)) {
|
|
5429
|
+
if (run.conversationId && (isThreadId(run.conversationId) || this.application.mesh?.bindThread && await this.loadThread(run.conversationId))) {
|
|
4867
5430
|
await finishDelivery();
|
|
4868
5431
|
await this.settleThread(event, run, steered);
|
|
4869
5432
|
return;
|