glove-foundry 0.6.0 → 0.7.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.
@@ -1,5 +1,5 @@
1
1
  // src/delegation.ts
2
- import { randomUUID } from "node:crypto";
2
+ import { createHash, randomUUID } from "node:crypto";
3
3
  import { mkdir, readdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
4
4
  import { join } from "node:path";
5
5
  import { defaultEventFormatter } from "glove-core";
@@ -47,7 +47,7 @@ function delegationFromContext(context) {
47
47
  return typeof item.id === "string" && typeof item.to === "string" && typeof item.workerAgentId === "string" && typeof item.task === "string" && typeof item.status === "string" && item.from && typeof item.from === "object" ? item : void 0;
48
48
  }
49
49
  function undeliveredUpdate(delegation) {
50
- const base = { delegationId: delegation.id, agent: delegation.to, task: delegation.task };
50
+ const base = { deliveryId: delegation.updateId, delegationId: delegation.id, agent: delegation.to, task: delegation.task };
51
51
  if (delegation.undelivered === "result") return { kind: "result", ...base, result: delegation.result ?? "" };
52
52
  if (delegation.undelivered === "question") return { kind: "question", ...base, question: delegation.question ?? "" };
53
53
  if (delegation.undelivered === "failed") return { kind: "failed", ...base, error: delegation.error ?? "" };
@@ -73,7 +73,7 @@ function renderDelegatedTask(input) {
73
73
  ].join("\n");
74
74
  }
75
75
  function renderDelivery(delivery) {
76
- if (delivery.kind === "transmission") return delivery.message;
76
+ if (delivery.kind === "transmission" || delivery.kind === "agent-message") return delivery.message;
77
77
  if (delivery.kind === "reply") {
78
78
  return [
79
79
  `<delegation-reply id="${escapeAttribute(delivery.delegationId)}" from="${escapeAttribute(delivery.from)}">`,
@@ -241,7 +241,8 @@ async function writeMailboxDelivery(directory, conversationId, delivery) {
241
241
  `, { encoding: "utf8", mode: 384 });
242
242
  await rename(temporary, join(target, name));
243
243
  }
244
- var DELIVERY_SCHEMA = z.union([
244
+ var DELIVERY_SCHEMA = z.intersection(z.object({ request: z.custom().optional(), deliveryId: z.string().optional(), durable: z.object({ id: z.string(), event: z.custom(), policy: z.custom() }).optional() }), z.union([
245
+ z.object({ kind: z.literal("agent-message"), pendingId: z.string(), message: z.string() }),
245
246
  z.object({
246
247
  kind: z.literal("reply"),
247
248
  delegationId: z.string(),
@@ -276,7 +277,7 @@ var DELIVERY_SCHEMA = z.union([
276
277
  eventId: z.string(),
277
278
  message: z.string()
278
279
  })
279
- ]);
280
+ ]));
280
281
  async function drainMailbox(directory, conversationId) {
281
282
  const target = conversationDirectory(directory, conversationId);
282
283
  let names;
@@ -356,6 +357,10 @@ function openRunMailbox(options) {
356
357
  const updates = [];
357
358
  const rest = [];
358
359
  for (const delivery of deliveries) {
360
+ if (delivery.durable?.event.expiresAt && Date.parse(delivery.durable.event.expiresAt) <= Date.now()) {
361
+ options.consumed?.([delivery]);
362
+ continue;
363
+ }
359
364
  if (delivery.kind === "reply" && waiters.has(delivery.delegationId)) {
360
365
  replies.set(delivery.delegationId, [...replies.get(delivery.delegationId) ?? [], delivery]);
361
366
  } else if (isDelegationUpdate(delivery) && handlers.size > 0) {
@@ -368,6 +373,7 @@ function openRunMailbox(options) {
368
373
  waiters.get(delegationId)?.({ ...batch[0], message: batch.map((reply) => reply.message).join("\n\n") });
369
374
  }
370
375
  if (updates.length > 0) await toHandlers(updates);
376
+ options.consumed?.([...[...replies.values()].flat(), ...updates]);
371
377
  if (rest.length > 0) await options.sink.forward(rest);
372
378
  }
373
379
  });
@@ -395,6 +401,7 @@ function openRunMailbox(options) {
395
401
  handlers.add(handler);
396
402
  const waiting = options.sink.reclaim(isDelegationUpdate).then(async (updates) => {
397
403
  if (updates.length > 0) await handler(updates);
404
+ options.consumed?.(updates);
398
405
  });
399
406
  return async () => {
400
407
  handlers.delete(handler);
@@ -415,9 +422,11 @@ function openRunMailbox(options) {
415
422
  }
416
423
  var DELIVERY_KEY = "foundry_delivery";
417
424
  function deliveryEvent(delivery) {
425
+ if (delivery.durable) return { ...delivery.durable.event, metadata: { ...delivery.durable.event.metadata, [DELIVERY_KEY]: delivery } };
426
+ if (delivery.kind === "agent-message") return { id: `agent-message:${delivery.pendingId}`, source: "foundry:agent", kind: "agent-message", content: delivery.message, metadata: { [DELIVERY_KEY]: delivery } };
418
427
  if (delivery.kind === "transmission") {
419
428
  return {
420
- id: `transmission:${delivery.pendingId}:${randomUUID()}`,
429
+ id: `transmission:${delivery.pendingId}`,
421
430
  source: `foundry:route:${delivery.routeId}`,
422
431
  kind: "transmission",
423
432
  content: delivery.message,
@@ -426,7 +435,7 @@ function deliveryEvent(delivery) {
426
435
  }
427
436
  const from = delivery.kind === "reply" ? delivery.from : delivery.agent;
428
437
  return {
429
- id: `${delivery.kind}:${delivery.delegationId}:${randomUUID()}`,
438
+ id: delivery.deliveryId ?? `${delivery.kind}:${delivery.delegationId}:${createHash("sha256").update(JSON.stringify(delivery)).digest("hex")}`,
430
439
  source: `foundry:${from}`,
431
440
  kind: `delegation.${delivery.kind}`,
432
441
  content: renderDelivery(delivery),
@@ -436,21 +445,7 @@ function deliveryEvent(delivery) {
436
445
  function deliveryOf(event) {
437
446
  return event.metadata?.[DELIVERY_KEY];
438
447
  }
439
- var formatRunEvents = (events, phase) => {
440
- const deliveries = events.map(deliveryOf).filter((delivery) => Boolean(delivery));
441
- const others = events.filter((event) => !deliveryOf(event));
442
- const text = renderDeliveries(deliveries);
443
- if (others.length === 0) return { sender: "user", framework_context: "event", text };
444
- const rest = defaultEventFormatter(others, phase);
445
- if (deliveries.length === 0) return rest;
446
- return {
447
- ...rest,
448
- text: `${text}
449
-
450
- ${rest.text}`,
451
- ...rest.content ? { content: [{ type: "text", text }, ...rest.content] } : {}
452
- };
453
- };
448
+ var formatRunEvents = defaultEventFormatter;
454
449
  var RunEventQueue = class {
455
450
  events = [];
456
451
  async push(event) {
@@ -111,6 +111,32 @@ var FoundryClient = class {
111
111
  body: JSON.stringify({ definitionId, ...options })
112
112
  }));
113
113
  }
114
+ async emitEvent(target, event, policy = {}) {
115
+ return readResponse(await this.fetcher(`${this.baseUrl}/api/events`, {
116
+ method: "POST",
117
+ headers: { "content-type": "application/json" },
118
+ body: JSON.stringify({ target, event, policy })
119
+ }));
120
+ }
121
+ async subagents(parentAgentId) {
122
+ return readResponse(await this.fetcher(`${this.baseUrl}/api/agent-instances/${encodeURIComponent(parentAgentId)}/subagents`));
123
+ }
124
+ subagent(parentAgentId, name) {
125
+ const base = `${this.baseUrl}/api/agent-instances/${encodeURIComponent(parentAgentId)}/subagents/${encodeURIComponent(name)}`;
126
+ const post = async (suffix, body = {}) => readResponse(await this.fetcher(`${base}${suffix}`, {
127
+ method: "POST",
128
+ headers: { "content-type": "application/json" },
129
+ body: JSON.stringify(body)
130
+ }));
131
+ return {
132
+ ensure: () => post(""),
133
+ send: (message, delivery = {}) => post("/messages", { message, delivery }),
134
+ data: async () => readResponse(await this.fetcher(`${base}/data`)),
135
+ archive: () => post("/archive"),
136
+ resume: () => post("/resume"),
137
+ purge: () => post("/purge")
138
+ };
139
+ }
114
140
  async agentInstances(definitionId) {
115
141
  const query = definitionId ? `?definition=${encodeURIComponent(definitionId)}` : "";
116
142
  return readResponse(await this.fetcher(`${this.baseUrl}/api/agent-instances${query}`));