@averyyy/pi-coding-agent 1.5.0-piclient.2 → 1.5.0-piclient.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.
@@ -37,8 +37,9 @@ interface ObserverTool {
37
37
  }
38
38
  export interface ObserverUpdate {
39
39
  sessionId: string;
40
- connectionId: string;
40
+ observerId: string;
41
41
  sequence: number;
42
+ create: boolean;
42
43
  cwd: string;
43
44
  title: string;
44
45
  subagents?: ObserverSubagent[];
@@ -57,15 +58,13 @@ export declare class PiServerObserver {
57
58
  private readonly unsubscribe;
58
59
  private controller?;
59
60
  private timer?;
60
- private reconnectTimer?;
61
61
  private disposed;
62
62
  private closing;
63
63
  private closePromise?;
64
- private connectionReady?;
65
64
  private deletedSessionId?;
66
- private connectionId?;
67
- private connectedSessionId?;
65
+ private observerId;
68
66
  private sequence;
67
+ private published;
69
68
  private sending;
70
69
  private flushPromise?;
71
70
  private dirty;
@@ -77,7 +76,7 @@ export declare class PiServerObserver {
77
76
  private liveMessage;
78
77
  private liveMessageId;
79
78
  private readonly tools;
80
- private disconnected;
79
+ private deliveryFailed;
81
80
  private observedSessionId?;
82
81
  private readonly subagents;
83
82
  private sentSubagentVersion;
@@ -88,7 +87,6 @@ export declare class PiServerObserver {
88
87
  private reportError;
89
88
  private stopDeletedSession;
90
89
  private request;
91
- private connect;
92
90
  private flush;
93
91
  private sendUpdate;
94
92
  close(): Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"pi-server-observer.d.ts","sourceRoot":"","sources":["../../src/core/pi-server-observer.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAA6B,eAAe,EAA6B,MAAM,uBAAuB,CAAC;AAEnH,OAAO,KAAK,EAAE,YAAY,EAAqB,MAAM,oBAAoB,CAAC;AAG1E,OAAO,EAAE,KAAK,gBAAgB,EAA+C,MAAM,0BAA0B,CAAC;AAC9G,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;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connectTimer;
89
88
  disposed = false;
90
89
  closing = false;
91
90
  closePromise;
92
- connectionReady;
93
91
  deletedSessionId;
94
- connectionId;
95
- connectedSessionId;
92
+ observerId = "";
96
93
  sequence = 0;
94
+ published = false;
97
95
  sending = false;
98
96
  flushPromise;
99
97
  dirty = true;
@@ -105,7 +103,7 @@ export class PiServerObserver {
105
103
  liveMessage = null;
106
104
  liveMessageId = "";
107
105
  tools = new Map();
108
- disconnected = false;
106
+ deliveryFailed = false;
109
107
  observedSessionId;
110
108
  subagents;
111
109
  sentSubagentVersion = -1;
@@ -126,7 +124,7 @@ export class PiServerObserver {
126
124
  this.reportError(error);
127
125
  }
128
126
  });
129
- void this.connect();
127
+ this.schedule(0);
130
128
  }
131
129
  handleEvent(event) {
132
130
  this.syncSession();
@@ -134,9 +132,9 @@ export class PiServerObserver {
134
132
  case "session_disposed":
135
133
  this.dispose();
136
134
  return;
137
- case "run_state_changed":
135
+ case "working_state_changed":
138
136
  resolvePiServerSubagents();
139
- if (!event.running) {
137
+ if (!event.working) {
140
138
  this.liveMessage = null;
141
139
  this.tools.clear();
142
140
  }
@@ -153,7 +151,7 @@ export class PiServerObserver {
153
151
  break;
154
152
  case "entry_appended":
155
153
  case "message_committed":
156
- if (this.connectionId && !this.historyDirty) {
154
+ if (!this.historyDirty) {
157
155
  this.pendingEntries.push(event.entry);
158
156
  if (this.pendingEntries.length > 64) {
159
157
  this.pendingEntries = [];
@@ -166,14 +164,6 @@ export class PiServerObserver {
166
164
  case "history_reconciled":
167
165
  case "session_tree_changed":
168
166
  this.subagents.restore();
169
- if (this.deletedSessionId && this.deletedSessionId !== this.session.sessionId) {
170
- this.deletedSessionId = undefined;
171
- void this.connect();
172
- }
173
- if (this.connectedSessionId && this.connectedSessionId !== this.session.sessionId) {
174
- this.connectionId = undefined;
175
- this.controller?.abort();
176
- }
177
167
  this.replace = true;
178
168
  this.historyDirty = true;
179
169
  break;
@@ -210,14 +200,23 @@ export class PiServerObserver {
210
200
  return;
211
201
  }
212
202
  this.dirty = true;
213
- this.schedule(event.type === "run_state_changed" || event.type === "compaction_start" || event.type === "compaction_end"
203
+ this.schedule(event.type === "working_state_changed" || event.type === "compaction_start" || event.type === "compaction_end"
214
204
  ? 0
215
205
  : 80);
216
206
  }
217
207
  syncSession() {
218
208
  if (this.observedSessionId === this.session.sessionId)
219
209
  return;
210
+ this.controller?.abort();
220
211
  this.observedSessionId = this.session.sessionId;
212
+ this.observerId = randomUUID();
213
+ this.sequence = 0;
214
+ this.published = false;
215
+ this.deletedSessionId = undefined;
216
+ this.deliveryFailed = false;
217
+ this.dirty = true;
218
+ this.historyDirty = true;
219
+ this.replace = true;
221
220
  this.subagents.syncSession();
222
221
  this.sentSubagentVersion = -1;
223
222
  this.sentEntryId = undefined;
@@ -231,7 +230,6 @@ export class PiServerObserver {
231
230
  this.closing ||
232
231
  this.deletedSessionId === this.session.sessionId ||
233
232
  !this.dirty ||
234
- !this.connectionId ||
235
233
  this.sending ||
236
234
  this.timer)
237
235
  return;
@@ -242,22 +240,20 @@ export class PiServerObserver {
242
240
  this.timer.unref();
243
241
  }
244
242
  reportError(error) {
245
- if (this.disposed || this.disconnected)
243
+ if (this.disposed || this.deliveryFailed)
246
244
  return;
247
- this.disconnected = true;
248
- console.error(`pi-server observer disconnected: ${error instanceof Error ? error.message : String(error)}`);
245
+ this.deliveryFailed = true;
246
+ console.error(`pi-server observer update failed: ${error instanceof Error ? error.message : String(error)}`);
249
247
  }
250
248
  stopDeletedSession(sessionId, controller) {
251
249
  if (sessionId === this.session.sessionId) {
252
250
  this.deletedSessionId = sessionId;
253
- this.connectionId = undefined;
251
+ this.dirty = false;
254
252
  this.pendingEntries = [];
255
253
  this.liveMessage = null;
256
254
  this.tools.clear();
257
255
  clearTimeout(this.timer);
258
256
  this.timer = undefined;
259
- clearTimeout(this.reconnectTimer);
260
- this.reconnectTimer = undefined;
261
257
  }
262
258
  controller.abort();
263
259
  }
@@ -268,95 +264,6 @@ export class PiServerObserver {
268
264
  signal,
269
265
  });
270
266
  }
271
- async connect() {
272
- if (this.disposed || this.deletedSessionId === this.session.sessionId)
273
- return;
274
- this.syncSession();
275
- const controller = new AbortController();
276
- this.controller = controller;
277
- const sessionId = this.session.sessionId;
278
- this.connectedSessionId = sessionId;
279
- let resolveConnection;
280
- this.connectionReady = new Promise((resolve) => {
281
- resolveConnection = resolve;
282
- });
283
- const timeout = setTimeout(() => controller.abort(new Error("connection timed out")), 10000);
284
- timeout.unref();
285
- try {
286
- const response = await this.request(controller.signal).getJson(`/api/observer/connect?sessionId=${encodeURIComponent(sessionId)}`);
287
- if (response.status === 410) {
288
- this.stopDeletedSession(sessionId, controller);
289
- return;
290
- }
291
- if (!response.ok || !response.headers.get("content-type")?.includes("text/event-stream") || !response.body) {
292
- throw new Error(`connection failed (HTTP ${response.status})`);
293
- }
294
- const reader = response.body.getReader();
295
- const decoder = new TextDecoder();
296
- let buffer = "";
297
- let event = "";
298
- try {
299
- while (!this.disposed) {
300
- const { done, value } = await reader.read();
301
- if (done)
302
- throw new Error("connection closed");
303
- buffer += decoder.decode(value, { stream: true });
304
- let newline = buffer.indexOf("\n");
305
- while (newline !== -1) {
306
- const line = buffer.slice(0, newline).replace(/\r$/, "");
307
- buffer = buffer.slice(newline + 1);
308
- if (line.startsWith("event:"))
309
- event = line.slice(6).trim();
310
- if (event === "deleted" && line.startsWith("data:")) {
311
- this.stopDeletedSession(sessionId, controller);
312
- return;
313
- }
314
- if (event === "connected" && !this.connectionId && line.startsWith("data:")) {
315
- const connected = JSON.parse(line.slice(5));
316
- this.connectionId = connected.connectionId;
317
- this.sequence = 0;
318
- this.sentSubagentVersion = -1;
319
- clearTimeout(timeout);
320
- this.replace = true;
321
- this.historyDirty = true;
322
- this.dirty = true;
323
- this.schedule(0);
324
- resolveConnection?.();
325
- }
326
- newline = buffer.indexOf("\n");
327
- }
328
- }
329
- }
330
- finally {
331
- await reader.cancel();
332
- reader.releaseLock();
333
- }
334
- }
335
- catch (error) {
336
- if (error instanceof TypeError &&
337
- error.message === "terminated" &&
338
- error.cause instanceof Error &&
339
- "code" in error.cause &&
340
- error.cause.code === "UND_ERR_SOCKET")
341
- return;
342
- if (sessionId === this.session.sessionId && this.deletedSessionId !== sessionId)
343
- this.reportError(error);
344
- }
345
- finally {
346
- resolveConnection?.();
347
- clearTimeout(timeout);
348
- controller.abort();
349
- if (this.controller === controller)
350
- this.connectionId = undefined;
351
- if (this.controller === controller && !this.disposed && !this.closing && this.deletedSessionId !== sessionId) {
352
- this.reconnectTimer = setTimeout(() => {
353
- this.reconnectTimer = undefined;
354
- void this.connect();
355
- }, sessionId === this.session.sessionId ? 2000 : 0);
356
- this.reconnectTimer.unref();
357
- }
358
- }
359
- }
360
267
  flush() {
361
268
  if (this.flushPromise)
362
269
  return this.flushPromise;
@@ -369,85 +276,111 @@ export class PiServerObserver {
369
276
  }
370
277
  async sendUpdate() {
371
278
  this.subagents.resolve();
372
- const connectionId = this.connectionId;
373
- const sessionId = this.connectedSessionId;
374
- const controller = this.controller;
375
- if (!connectionId ||
376
- !sessionId ||
377
- sessionId !== this.session.sessionId ||
378
- !controller ||
379
- this.disposed ||
380
- this.deletedSessionId === sessionId ||
381
- this.sending ||
382
- !this.dirty)
383
- return;
279
+ const sessionId = this.session.sessionId;
280
+ if (this.disposed || this.deletedSessionId === sessionId || this.sending || !this.dirty)
281
+ return true;
282
+ const observerId = this.observerId;
283
+ const controller = new AbortController();
284
+ this.controller = controller;
384
285
  this.sending = true;
385
- this.dirty = false;
286
+ let schedulePending = false;
386
287
  try {
387
- const branch = this.historyDirty ? this.session.sessionManager.getBranch() : undefined;
388
- const sentIndex = branch && this.sentEntryId ? branch.findIndex((entry) => entry.id === this.sentEntryId) : -1;
389
- const replace = this.replace || (branch !== undefined && this.sentEntryId !== undefined && sentIndex === -1);
390
- this.historyDirty = false;
391
- this.replace = false;
392
- const entries = branch ? (replace ? branch : branch.slice(sentIndex + 1)) : this.pendingEntries;
393
- this.pendingEntries = [];
394
- const messages = projectObserverEntries(entries);
395
- if (replace)
396
- this.firstUserTitle = "";
397
- if (!this.firstUserTitle) {
398
- const firstUserContent = messages.find((message) => message.role === "user")?.content;
399
- this.firstUserTitle = (typeof firstUserContent === "string"
400
- ? firstUserContent
401
- : (firstUserContent
402
- ?.filter((part) => part.type === "text")
403
- .map((part) => part.text)
404
- .join("") ?? "")).slice(0, 120);
405
- }
406
- const subagentVersion = this.subagents.version;
407
- const update = {
408
- sessionId,
409
- connectionId,
410
- sequence: ++this.sequence,
411
- cwd: this.session.sessionManager.getCwd(),
412
- title: this.session.sessionManager.getSessionName() ?? this.firstUserTitle,
413
- ...(subagentVersion !== this.sentSubagentVersion ? { subagents: this.subagents.snapshot() } : {}),
414
- ...(replace ? { replace: messages } : messages.length ? { append: messages } : {}),
415
- status: this.session.isIdle ? "idle" : "running",
416
- live: {
417
- message: this.liveMessage ? (projectMessage(this.liveMessageId, this.liveMessage) ?? null) : null,
418
- tools: [...this.tools.values()],
419
- },
420
- };
421
- const response = await this.request(controller.signal).postJson("/api/observer", update);
422
- if (response.status === 410) {
423
- this.stopDeletedSession(sessionId, controller);
424
- return;
425
- }
426
- if (!response.ok)
427
- throw new Error(`update failed (HTTP ${response.status})`);
428
- const result = (await response.json());
429
- if (!result.accepted)
430
- throw new Error("update was not accepted");
431
- if (sessionId !== this.session.sessionId)
432
- return;
433
- this.sentSubagentVersion = subagentVersion;
434
- if (entries.length > 0)
435
- this.sentEntryId = entries.at(-1)?.id;
436
- else if (replace)
437
- this.sentEntryId = undefined;
438
- if (this.disconnected) {
439
- this.disconnected = false;
440
- console.error("pi-server observer connected");
288
+ for (let attempt = 0; attempt < 2; attempt++) {
289
+ this.dirty = false;
290
+ const branch = this.historyDirty ? this.session.sessionManager.getBranch() : undefined;
291
+ const sentIndex = branch && this.sentEntryId ? branch.findIndex((entry) => entry.id === this.sentEntryId) : -1;
292
+ const replace = this.replace || (branch !== undefined && this.sentEntryId !== undefined && sentIndex === -1);
293
+ this.historyDirty = false;
294
+ this.replace = false;
295
+ const entries = branch ? (replace ? branch : branch.slice(sentIndex + 1)) : this.pendingEntries;
296
+ this.pendingEntries = [];
297
+ const messages = projectObserverEntries(entries);
298
+ if (replace)
299
+ this.firstUserTitle = "";
300
+ if (!this.firstUserTitle) {
301
+ const firstUserContent = messages.find((message) => message.role === "user")?.content;
302
+ this.firstUserTitle = (typeof firstUserContent === "string"
303
+ ? firstUserContent
304
+ : (firstUserContent
305
+ ?.filter((part) => part.type === "text")
306
+ .map((part) => part.text)
307
+ .join("") ?? "")).slice(0, 120);
308
+ }
309
+ const subagentVersion = this.subagents.version;
310
+ const update = {
311
+ sessionId,
312
+ observerId,
313
+ sequence: ++this.sequence,
314
+ create: !this.published,
315
+ cwd: this.session.sessionManager.getCwd(),
316
+ title: this.session.sessionManager.getSessionName() ?? this.firstUserTitle,
317
+ ...(subagentVersion !== this.sentSubagentVersion ? { subagents: this.subagents.snapshot() } : {}),
318
+ ...(replace ? { replace: messages } : messages.length ? { append: messages } : {}),
319
+ status: this.session.isWorking ? "running" : "idle",
320
+ live: {
321
+ message: this.liveMessage ? (projectMessage(this.liveMessageId, this.liveMessage) ?? null) : null,
322
+ tools: [...this.tools.values()],
323
+ },
324
+ };
325
+ const response = await this.request(controller.signal).postJson("/api/observer", update);
326
+ if (observerId !== this.observerId)
327
+ return false;
328
+ if (response.status === 410) {
329
+ this.stopDeletedSession(sessionId, controller);
330
+ return true;
331
+ }
332
+ if (response.status === 409 && attempt === 0) {
333
+ const result = (await response.json());
334
+ if (observerId !== this.observerId)
335
+ return false;
336
+ if (result.snapshotRequired) {
337
+ this.replace = true;
338
+ this.historyDirty = true;
339
+ this.sentSubagentVersion = -1;
340
+ continue;
341
+ }
342
+ }
343
+ if (!response.ok)
344
+ throw new Error(`update failed (HTTP ${response.status})`);
345
+ const result = (await response.json());
346
+ if (!result.accepted)
347
+ throw new Error("update was not accepted");
348
+ if (observerId !== this.observerId)
349
+ return false;
350
+ this.published = true;
351
+ this.sentSubagentVersion = subagentVersion;
352
+ if (entries.length > 0)
353
+ this.sentEntryId = entries.at(-1)?.id;
354
+ else if (replace)
355
+ this.sentEntryId = undefined;
356
+ if (this.deliveryFailed) {
357
+ this.deliveryFailed = false;
358
+ console.error("pi-server observer delivery resumed");
359
+ }
360
+ schedulePending = true;
361
+ return true;
441
362
  }
363
+ return false;
442
364
  }
443
365
  catch (error) {
444
- if (sessionId === this.session.sessionId && this.deletedSessionId !== sessionId)
366
+ schedulePending = this.dirty;
367
+ if (observerId === this.observerId && this.deletedSessionId !== sessionId) {
368
+ this.dirty = true;
369
+ this.historyDirty = true;
370
+ this.replace = true;
371
+ this.pendingEntries = [];
372
+ this.sentSubagentVersion = -1;
445
373
  this.reportError(error);
374
+ }
446
375
  controller.abort();
376
+ return false;
447
377
  }
448
378
  finally {
449
379
  this.sending = false;
450
- this.schedule(80);
380
+ if (this.controller === controller)
381
+ this.controller = undefined;
382
+ if (schedulePending || observerId !== this.observerId)
383
+ this.schedule(80);
451
384
  }
452
385
  }
453
386
  close() {
@@ -460,21 +393,15 @@ export class PiServerObserver {
460
393
  this.closing = true;
461
394
  clearTimeout(this.timer);
462
395
  this.timer = undefined;
463
- clearTimeout(this.reconnectTimer);
464
396
  try {
465
397
  await raceWithAbortSignal((async () => {
466
398
  if (this.deletedSessionId === this.session.sessionId)
467
399
  return;
468
- if (!this.connectionId && this.controller?.signal.aborted)
469
- void this.connect();
470
- await this.connectionReady;
471
400
  await this.flushPromise;
472
- if (!this.connectionId)
473
- throw new Error("final transcript was not delivered: observer is disconnected");
474
- while (this.dirty && this.connectionId && !this.disposed)
475
- await this.flush();
476
- if (this.controller?.signal.aborted && this.deletedSessionId !== this.session.sessionId)
477
- throw new Error("final transcript was not delivered: observer update failed");
401
+ while (this.dirty && !this.disposed) {
402
+ if (!(await this.flush()))
403
+ throw new Error("final transcript was not delivered: observer update failed");
404
+ }
478
405
  })(), AbortSignal.timeout(10000));
479
406
  }
480
407
  catch (error) {
@@ -489,7 +416,6 @@ export class PiServerObserver {
489
416
  this.unsubscribe();
490
417
  this.subagents.dispose();
491
418
  clearTimeout(this.timer);
492
- clearTimeout(this.reconnectTimer);
493
419
  this.controller?.abort();
494
420
  observers.delete(this.session);
495
421
  }