@lightblues/jig 0.0.3 → 0.0.4

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.
@@ -136,6 +136,10 @@ export declare class PaseoThreadRunner<TResult = unknown> {
136
136
  * the held events the tail did not have. An ended turn is finished instead.
137
137
  */
138
138
  private regap;
139
+ /** Reads the agent and its tail and rebuilds the run; a full page without our message is read again, deeper. With `keep`, a tail without our message is an error rather than "not found". */
140
+ private retail;
141
+ /** Finishes a turn the re-tail found ended, with the end event held meanwhile when there is one. */
142
+ private finishHeld;
139
143
  /** Replaces the run's folder with the turn in `entries` (after our message); null when our message is not there. */
140
144
  private rebuild;
141
145
  /** Folds the held events; with `resync`, first sends every follower `READY` and the replay of the rebuilt turn. */
@@ -64,7 +64,14 @@ export class PaseoThreadRunner {
64
64
  const r = this.runs.get(threadId);
65
65
  if (!r?.agentId)
66
66
  return { stopping: false };
67
- await this.o.daemon.cancel(r.agentId);
67
+ r.stopping = true;
68
+ try {
69
+ await this.o.daemon.cancel(r.agentId);
70
+ }
71
+ catch (e) {
72
+ r.stopping = false;
73
+ throw e;
74
+ }
68
75
  return { stopping: true };
69
76
  }
70
77
  /**
@@ -78,12 +85,11 @@ export class PaseoThreadRunner {
78
85
  const run = this.newRun(req.threadId, req.runId, req.agentId, req.metadata, true);
79
86
  this.runs.set(run.threadId, run);
80
87
  try {
81
- run.unsub = await this.o.daemon.subscribe(req.agentId, (e) => this.onEvent(run, e));
88
+ // Hold events from the first one: the turn may end while we subscribe.
82
89
  run.buffer = [];
83
- const a = await this.o.daemon.agent(req.agentId);
84
- const tail = await this.o.daemon.tail(req.agentId, this.tailLimit);
85
- const after = this.rebuild(run, tail.entries, tail.epoch, tail.seq);
86
- if (!after) {
90
+ run.unsub = await this.o.daemon.subscribe(req.agentId, (e) => this.onEvent(run, e));
91
+ const t = await this.retail(run);
92
+ if (!t.found) {
87
93
  this.cleanup(run);
88
94
  const sent = req.sentAt == null ? 0 : new Date(req.sentAt).getTime();
89
95
  if (Date.now() - sent < (req.graceMs ?? 60_000))
@@ -91,16 +97,12 @@ export class PaseoThreadRunner {
91
97
  await this.o.store.saveError(req.threadId, { runId: req.runId, agentId: req.agentId, error: "the agent never got the message" });
92
98
  return "failed";
93
99
  }
94
- if (a?.status === "running") {
95
- this.drain(run);
96
- for (const e of this.resync(run.threadId, run))
97
- this.emit(run.threadId, e);
100
+ if (t.running) {
98
101
  this.watch(run);
102
+ this.drain(run, true);
99
103
  return "following";
100
104
  }
101
- run.buffer = null;
102
- const ok = await this.finish(run, "done");
103
- return ok ? "finished" : "failed";
105
+ return (await this.finishHeld(run)) ? "finished" : "failed";
104
106
  }
105
107
  catch (e) {
106
108
  this.cleanup(run);
@@ -113,7 +115,7 @@ export class PaseoThreadRunner {
113
115
  }
114
116
  // ---- internals
115
117
  newRun(threadId, runId, agentId, metadata, ours) {
116
- return { threadId, runId, agentId, metadata, turn: new TurnFolder(), ours, turnId: null, epoch: null, seq: -1, buffer: null, unsub: null, last: Date.now(), watch: null, done: false };
118
+ return { threadId, runId, agentId, metadata, turn: new TurnFolder(), ours, turnId: null, epoch: null, seq: -1, buffer: null, again: null, sentAt: null, stopping: false, unsub: null, last: Date.now(), watch: null, done: false };
117
119
  }
118
120
  started(run) {
119
121
  return { type: EventType.RUN_STARTED, threadId: run.threadId, runId: run.runId, ...(run.metadata ? { metadata: run.metadata } : {}) };
@@ -159,15 +161,18 @@ export class PaseoThreadRunner {
159
161
  return run.unsub();
160
162
  this.watch(run);
161
163
  await d.send(agent, text, run.runId);
164
+ run.sentAt = Date.now();
162
165
  }
163
166
  onEvent(run, e) {
164
167
  if (run.done)
165
168
  return;
166
169
  run.last = Date.now();
167
- if (e.type === "lost")
168
- return void this.check(run, e.error);
169
- if (e.type === "replacement" || e.type === "subscription_restored")
170
- return void this.regap(run, e.type);
170
+ if (e.type === "lost" || e.type === "replacement" || e.type === "subscription_restored") {
171
+ const resubscribe = e.type === "lost";
172
+ if (run.buffer)
173
+ return void (run.again = { resubscribe: resubscribe || Boolean(run.again?.resubscribe) });
174
+ return void this.regap(run, e.type === "lost" ? e.error : e.type, resubscribe);
175
+ }
171
176
  if (run.buffer)
172
177
  return void run.buffer.push(e);
173
178
  this.apply(run, e);
@@ -198,14 +203,7 @@ export class PaseoThreadRunner {
198
203
  this.emit(run.threadId, x);
199
204
  return;
200
205
  }
201
- if (e.type === "turn_started") {
202
- // Our message started this turn once it was sent (the runner subscribes before it sends).
203
- if (run.agentId && !run.turnId) {
204
- run.ours = true;
205
- run.turnId = e.turnId ?? null;
206
- }
207
- return;
208
- }
206
+ // `turn_started` claims nothing: it may be someone else's turn. The daemon shows our message right after ours starts.
209
207
  if (e.type !== "turn_completed" && e.type !== "turn_canceled" && e.type !== "turn_failed")
210
208
  return;
211
209
  if (!run.ours)
@@ -232,24 +230,47 @@ export class PaseoThreadRunner {
232
230
  if (resubscribe) {
233
231
  run.unsub?.();
234
232
  run.unsub = await this.o.daemon.subscribe(run.agentId, (e) => this.onEvent(run, e));
233
+ if (run.done)
234
+ return run.unsub();
235
235
  }
236
- const a = await this.o.daemon.agent(run.agentId);
237
- const tail = await this.o.daemon.tail(run.agentId, this.tailLimit);
236
+ const t = await this.retail(run, true);
238
237
  if (run.done)
239
238
  return;
240
- const after = this.rebuild(run, tail.entries, tail.epoch, tail.seq);
241
- if (after && a?.status !== "running") {
242
- run.buffer = null;
243
- return void (await this.finish(run, "done"));
244
- }
245
- this.drain(run, true);
239
+ if (t.found && !t.running)
240
+ return void (await this.finishHeld(run));
241
+ if (!t.found && !t.running && run.sentAt != null && Date.now() - run.sentAt >= this.quietMs)
242
+ return this.fail(run, "the agent never got the message");
246
243
  run.last = Date.now();
244
+ this.drain(run, true);
247
245
  }
248
246
  catch (e) {
249
247
  run.buffer = null;
250
248
  this.fail(run, `${why}: ${e.message}`);
251
249
  }
252
250
  }
251
+ /** Reads the agent and its tail and rebuilds the run; a full page without our message is read again, deeper. With `keep`, a tail without our message is an error rather than "not found". */
252
+ async retail(run, keep = false) {
253
+ const a = await this.o.daemon.agent(run.agentId);
254
+ let tail = await this.o.daemon.tail(run.agentId, this.tailLimit);
255
+ const has = () => tail.entries.some((x) => x.item.type === "user_message" && (x.item.clientMessageId === run.runId || x.item.messageId === run.runId));
256
+ if (!has() && tail.entries.length >= this.tailLimit)
257
+ tail = await this.o.daemon.tail(run.agentId, this.tailLimit * 10);
258
+ // A read that failed to reach our message must not replace what a claimed run already folded.
259
+ if (keep && run.ours && !has())
260
+ throw new Error("the turn is no longer in the timeline's tail");
261
+ const after = this.rebuild(run, tail.entries, tail.epoch, tail.seq);
262
+ // A later message in another turn means ours has ended, whatever the agent is doing now.
263
+ const next = Boolean(run.turnId && after?.some((x) => x.item.type === "user_message" && x.turnId && x.turnId !== run.turnId));
264
+ return { found: Boolean(after), running: a?.status === "running" && !next };
265
+ }
266
+ /** Finishes a turn the re-tail found ended, with the end event held meanwhile when there is one. */
267
+ finishHeld(run) {
268
+ const end = run.buffer?.find((e) => (e.type === "turn_completed" || e.type === "turn_canceled" || e.type === "turn_failed") && !(run.turnId && e.turnId && e.turnId !== run.turnId));
269
+ run.buffer = null;
270
+ if (end?.type === "turn_failed")
271
+ return this.finish(run, "error", end.error);
272
+ return this.finish(run, end?.type === "turn_canceled" || (!end && run.stopping) ? "stopped" : "done");
273
+ }
253
274
  /** Replaces the run's folder with the turn in `entries` (after our message); null when our message is not there. */
254
275
  rebuild(run, entries, epoch, seq) {
255
276
  const i = entries.findIndex((x) => x.item.type === "user_message" && (x.item.clientMessageId === run.runId || x.item.messageId === run.runId));
@@ -270,7 +291,11 @@ export class PaseoThreadRunner {
270
291
  /** Folds the held events; with `resync`, first sends every follower `READY` and the replay of the rebuilt turn. */
271
292
  drain(run, resync = false) {
272
293
  const held = run.buffer ?? [];
294
+ const again = run.again;
273
295
  run.buffer = null;
296
+ run.again = null;
297
+ if (again)
298
+ return void this.regap(run, "another gap", again.resubscribe);
274
299
  if (resync)
275
300
  for (const e of this.resync(run.threadId, run))
276
301
  this.emit(run.threadId, e);
@@ -281,11 +306,9 @@ export class PaseoThreadRunner {
281
306
  }
282
307
  }
283
308
  /** A quiet or broken stream: the daemon says whether the turn ended while no event came. */
284
- async check(run, lost) {
309
+ async check(run) {
285
310
  if (run.done || !run.agentId || run.buffer)
286
311
  return;
287
- if (lost)
288
- return void this.regap(run, lost, true);
289
312
  if (Date.now() - run.last < this.quietMs)
290
313
  return;
291
314
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lightblues/jig",
3
- "version": "0.0.3",
3
+ "version": "0.0.4",
4
4
  "description": "Reusable parts for my apps: agent runtimes (Paseo, pi) that speak AG-UI, a thin thread-following client, and more as they prove reusable.",
5
5
  "type": "module",
6
6
  "license": "MIT",