@narumitw/pi-herdr 0.3.1 → 0.3.3
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/README.md +17 -9
- package/dist/index.ts +243 -277
- package/dist/index.ts.map +3 -3
- package/package.json +5 -5
- package/src/herdr-agent-state.ts +38 -21
- package/src/herdr-client.ts +44 -53
- package/src/herdr-observer.ts +170 -150
- package/src/herdr-protocol.ts +21 -32
- package/src/herdr-widget.ts +1 -55
package/dist/index.ts
CHANGED
|
@@ -31,6 +31,9 @@ var NdjsonFrames = class {
|
|
|
31
31
|
throw new Error("Herdr returned invalid JSON");
|
|
32
32
|
}
|
|
33
33
|
}
|
|
34
|
+
if (this.buffer.length > MAX_HERDR_FRAME_BYTES) {
|
|
35
|
+
throw new Error("Herdr response frame exceeded the size limit");
|
|
36
|
+
}
|
|
34
37
|
return frames;
|
|
35
38
|
}
|
|
36
39
|
};
|
|
@@ -40,47 +43,36 @@ function isRecord(value) {
|
|
|
40
43
|
function abortReason(signal) {
|
|
41
44
|
return signal.reason instanceof Error ? signal.reason : new DOMException("Herdr request aborted", "AbortError");
|
|
42
45
|
}
|
|
46
|
+
var HerdrApiError = class extends Error {
|
|
47
|
+
code;
|
|
48
|
+
constructor(error) {
|
|
49
|
+
super(`Herdr ${typeof error.message === "string" ? error.message : "request failed"}`);
|
|
50
|
+
this.code = typeof error.code === "string" ? error.code : void 0;
|
|
51
|
+
}
|
|
52
|
+
};
|
|
43
53
|
function responseError(frame) {
|
|
44
|
-
if (!
|
|
45
|
-
|
|
46
|
-
return new
|
|
47
|
-
}
|
|
48
|
-
function sendRequestAttempt(socketEndpoint, request, timeoutMs, signal) {
|
|
49
|
-
if (signal.aborted) return Promise.resolve(false);
|
|
50
|
-
return new Promise((resolve) => {
|
|
51
|
-
let finished = false;
|
|
52
|
-
let timeout;
|
|
53
|
-
const socket = net.createConnection(socketEndpoint);
|
|
54
|
-
const finish = (delivered) => {
|
|
55
|
-
if (finished) return;
|
|
56
|
-
finished = true;
|
|
57
|
-
if (timeout) clearTimeout(timeout);
|
|
58
|
-
signal.removeEventListener("abort", abort);
|
|
59
|
-
socket.destroy();
|
|
60
|
-
resolve(delivered);
|
|
61
|
-
};
|
|
62
|
-
const abort = () => finish(false);
|
|
63
|
-
signal.addEventListener("abort", abort, { once: true });
|
|
64
|
-
socket.on("error", () => finish(false));
|
|
65
|
-
socket.on("connect", () => socket.write(`${JSON.stringify(request)}
|
|
66
|
-
`));
|
|
67
|
-
socket.on("data", () => finish(true));
|
|
68
|
-
socket.on("end", () => finish(false));
|
|
69
|
-
socket.on("close", () => finish(false));
|
|
70
|
-
timeout = setTimeout(() => finish(false), timeoutMs);
|
|
71
|
-
timeout.unref?.();
|
|
72
|
-
});
|
|
54
|
+
if (!("error" in frame)) return void 0;
|
|
55
|
+
if (!isRecord(frame.error)) return new Error("Herdr returned an invalid error response");
|
|
56
|
+
return new HerdrApiError(frame.error);
|
|
73
57
|
}
|
|
74
58
|
function createBestEffortSender(socketEndpoint) {
|
|
75
59
|
return async (request, signal) => {
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
60
|
+
for (const timeoutMs of [500, 1500]) {
|
|
61
|
+
if (signal.aborted) return;
|
|
62
|
+
try {
|
|
63
|
+
const result = await requestHerdr(socketEndpoint, request, signal, timeoutMs);
|
|
64
|
+
if (isRecord(result) && result.type === "ok") return;
|
|
65
|
+
} catch (error) {
|
|
66
|
+
if (signal.aborted || error instanceof HerdrApiError) return;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
79
69
|
};
|
|
80
70
|
}
|
|
81
71
|
function requestHerdr(socketEndpoint, request, signal, timeoutMs = 1500) {
|
|
82
72
|
if (signal.aborted) return Promise.reject(abortReason(signal));
|
|
83
73
|
return new Promise((resolve, reject) => {
|
|
74
|
+
const payload = `${JSON.stringify(request)}
|
|
75
|
+
`;
|
|
84
76
|
const socket = net.createConnection(socketEndpoint);
|
|
85
77
|
const parser = new NdjsonFrames();
|
|
86
78
|
let finished = false;
|
|
@@ -100,12 +92,14 @@ function requestHerdr(socketEndpoint, request, signal, timeoutMs = 1500) {
|
|
|
100
92
|
};
|
|
101
93
|
const abort = () => finish(abortReason(signal));
|
|
102
94
|
signal.addEventListener("abort", abort, { once: true });
|
|
103
|
-
socket.on("connect", () =>
|
|
104
|
-
|
|
95
|
+
socket.on("connect", () => {
|
|
96
|
+
if (!finished) socket.write(payload);
|
|
97
|
+
});
|
|
105
98
|
socket.on("error", (error) => finish(error));
|
|
106
99
|
socket.on("end", () => finish(new Error("Herdr closed the request before responding")));
|
|
107
100
|
socket.on("close", () => finish(new Error("Herdr request socket closed")));
|
|
108
101
|
socket.on("data", (chunk) => {
|
|
102
|
+
if (finished) return;
|
|
109
103
|
try {
|
|
110
104
|
for (const value of parser.push(chunk)) {
|
|
111
105
|
if (!isRecord(value)) continue;
|
|
@@ -135,6 +129,8 @@ function requestHerdr(socketEndpoint, request, signal, timeoutMs = 1500) {
|
|
|
135
129
|
}
|
|
136
130
|
async function openHerdrSubscription(socketEndpoint, request, signal, onEvent, timeoutMs = 1500) {
|
|
137
131
|
if (signal.aborted) throw abortReason(signal);
|
|
132
|
+
const payload = `${JSON.stringify(request)}
|
|
133
|
+
`;
|
|
138
134
|
const socket = net.createConnection(socketEndpoint);
|
|
139
135
|
const parser = new NdjsonFrames();
|
|
140
136
|
const pendingEvents = [];
|
|
@@ -175,6 +171,7 @@ async function openHerdrSubscription(socketEndpoint, request, signal, onEvent, t
|
|
|
175
171
|
else resolveClosed();
|
|
176
172
|
};
|
|
177
173
|
const deliver = (frame) => {
|
|
174
|
+
if (finished) return;
|
|
178
175
|
try {
|
|
179
176
|
onEvent(frame);
|
|
180
177
|
} catch (error) {
|
|
@@ -186,28 +183,27 @@ async function openHerdrSubscription(socketEndpoint, request, signal, onEvent, t
|
|
|
186
183
|
finish();
|
|
187
184
|
};
|
|
188
185
|
signal.addEventListener("abort", abort, { once: true });
|
|
189
|
-
socket.on("connect", () =>
|
|
190
|
-
|
|
186
|
+
socket.on("connect", () => {
|
|
187
|
+
if (!finished) socket.write(payload);
|
|
188
|
+
});
|
|
191
189
|
socket.on("error", (error) => finish(error));
|
|
192
190
|
socket.on("end", () => finish(new Error("Herdr subscription closed")));
|
|
193
191
|
socket.on("close", () => finish(new Error("Herdr subscription socket closed")));
|
|
194
192
|
socket.on("data", (chunk) => {
|
|
193
|
+
if (finished) return;
|
|
195
194
|
try {
|
|
196
195
|
for (const value of parser.push(chunk)) {
|
|
197
|
-
if (
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
}
|
|
196
|
+
if (finished) return;
|
|
197
|
+
if (isRecord(value)) {
|
|
198
|
+
const error = responseError(value);
|
|
199
|
+
if (error && (value.id === request.id || value.id === "" || value.id === void 0)) {
|
|
200
|
+
finish(error);
|
|
201
|
+
return;
|
|
204
202
|
}
|
|
203
|
+
if ("id" in value && value.id !== request.id) continue;
|
|
204
|
+
}
|
|
205
|
+
if (!ready) {
|
|
205
206
|
if (isRecord(value) && value.id === request.id) {
|
|
206
|
-
const error = responseError(value);
|
|
207
|
-
if (error) {
|
|
208
|
-
finish(error);
|
|
209
|
-
return;
|
|
210
|
-
}
|
|
211
207
|
if (!isRecord(value.result) || value.result.type !== "subscription_started") {
|
|
212
208
|
finish(new Error("Herdr returned an invalid subscription acknowledgement"));
|
|
213
209
|
return;
|
|
@@ -297,10 +293,15 @@ function createHerdrMetadataRequest(options) {
|
|
|
297
293
|
};
|
|
298
294
|
}
|
|
299
295
|
|
|
296
|
+
// src/herdr-observer.ts
|
|
297
|
+
import { createEditorStatusPublisher } from "@narumitw/pi-tui-kit/editor-status-publisher";
|
|
298
|
+
|
|
300
299
|
// src/herdr-protocol.ts
|
|
301
300
|
var HERDR_AGENT_STATUSES = ["idle", "working", "blocked", "done", "unknown"];
|
|
302
301
|
var HERDR_WIDGET_TOPOLOGY_SUBSCRIPTIONS = [
|
|
303
302
|
{ type: "pane.created" },
|
|
303
|
+
{ type: "pane.updated" },
|
|
304
|
+
{ type: "workspace.renamed" },
|
|
304
305
|
{ type: "pane.closed" },
|
|
305
306
|
{ type: "pane.moved" },
|
|
306
307
|
{ type: "pane.exited" },
|
|
@@ -398,7 +399,12 @@ function parseHerdrPaneEvent(value) {
|
|
|
398
399
|
return void 0;
|
|
399
400
|
}
|
|
400
401
|
const data = value.data;
|
|
401
|
-
if (value.event === "
|
|
402
|
+
if (value.event === "workspace_renamed") {
|
|
403
|
+
const workspaceId = requiredString(data.workspace_id);
|
|
404
|
+
if (!workspaceId || typeof data.label !== "string") return void 0;
|
|
405
|
+
return { type: "workspace_renamed", workspaceId };
|
|
406
|
+
}
|
|
407
|
+
if (value.event === "pane.agent_status_changed" || value.event === "pane_agent_status_changed") {
|
|
402
408
|
const paneId = requiredString(data.pane_id);
|
|
403
409
|
const workspaceId = requiredString(data.workspace_id);
|
|
404
410
|
const status = agentStatus(data.agent_status);
|
|
@@ -406,17 +412,12 @@ function parseHerdrPaneEvent(value) {
|
|
|
406
412
|
return {
|
|
407
413
|
type: "agent_status_changed",
|
|
408
414
|
paneId,
|
|
409
|
-
workspaceId
|
|
410
|
-
agent: optionalString(data.agent),
|
|
411
|
-
agentStatus: status,
|
|
412
|
-
displayAgent: optionalString(data.display_agent),
|
|
413
|
-
stateLabels: stringRecord(data.state_labels),
|
|
414
|
-
title: optionalString(data.title)
|
|
415
|
+
workspaceId
|
|
415
416
|
};
|
|
416
417
|
}
|
|
417
|
-
if (value.event === "pane_created") {
|
|
418
|
+
if (value.event === "pane_created" || value.event === "pane_updated") {
|
|
418
419
|
const pane = parseHerdrPane(data.pane);
|
|
419
|
-
return pane ? { type: "created", pane } : void 0;
|
|
420
|
+
return pane ? { type: value.event === "pane_created" ? "created" : "updated", pane } : void 0;
|
|
420
421
|
}
|
|
421
422
|
if (value.event === "pane_closed" || value.event === "pane_exited") {
|
|
422
423
|
const paneId = requiredString(data.pane_id);
|
|
@@ -438,16 +439,15 @@ function parseHerdrPaneEvent(value) {
|
|
|
438
439
|
if (value.event === "pane_agent_detected") {
|
|
439
440
|
const paneId = requiredString(data.pane_id);
|
|
440
441
|
const workspaceId = requiredString(data.workspace_id);
|
|
441
|
-
if (!paneId || !workspaceId || typeof data.released !== "boolean")
|
|
442
|
+
if (!paneId || !workspaceId || data.released !== void 0 && typeof data.released !== "boolean") {
|
|
443
|
+
return void 0;
|
|
444
|
+
}
|
|
442
445
|
const finalStatus = data.final_status === null ? void 0 : agentStatus(data.final_status);
|
|
443
446
|
if (data.final_status !== void 0 && data.final_status !== null && !finalStatus) return void 0;
|
|
444
447
|
return {
|
|
445
448
|
type: "agent_detected",
|
|
446
449
|
paneId,
|
|
447
|
-
workspaceId
|
|
448
|
-
agent: optionalString(data.agent),
|
|
449
|
-
finalStatus,
|
|
450
|
-
released: data.released
|
|
450
|
+
workspaceId
|
|
451
451
|
};
|
|
452
452
|
}
|
|
453
453
|
return void 0;
|
|
@@ -543,57 +543,6 @@ var HerdrWidgetModel = class {
|
|
|
543
543
|
isCurrentWorkspace(workspaceId) {
|
|
544
544
|
return this.currentWorkspaceId === workspaceId;
|
|
545
545
|
}
|
|
546
|
-
apply(event) {
|
|
547
|
-
if (event.type === "created") {
|
|
548
|
-
this.panes.set(event.pane.paneId, observedPane(event.pane));
|
|
549
|
-
return;
|
|
550
|
-
}
|
|
551
|
-
if (event.type === "closed" || event.type === "exited") {
|
|
552
|
-
this.panes.delete(event.paneId);
|
|
553
|
-
return;
|
|
554
|
-
}
|
|
555
|
-
if (event.type === "moved") {
|
|
556
|
-
this.panes.delete(event.previousPaneId);
|
|
557
|
-
this.panes.set(event.pane.paneId, observedPane(event.pane));
|
|
558
|
-
if (this.currentPaneId === event.previousPaneId) {
|
|
559
|
-
this.currentPaneId = event.pane.paneId;
|
|
560
|
-
this.currentWorkspaceId = event.pane.workspaceId;
|
|
561
|
-
this.workspace = { workspaceId: event.pane.workspaceId };
|
|
562
|
-
}
|
|
563
|
-
return;
|
|
564
|
-
}
|
|
565
|
-
const existing = this.panes.get(event.paneId);
|
|
566
|
-
if (event.type === "agent_detected") {
|
|
567
|
-
if (event.released || !event.agent) {
|
|
568
|
-
if (existing) this.panes.set(event.paneId, { ...existing, agent: void 0 });
|
|
569
|
-
return;
|
|
570
|
-
}
|
|
571
|
-
this.panes.set(event.paneId, {
|
|
572
|
-
...existing ?? {
|
|
573
|
-
paneId: event.paneId,
|
|
574
|
-
workspaceId: event.workspaceId,
|
|
575
|
-
agentStatus: event.finalStatus ?? "unknown",
|
|
576
|
-
stateLabels: {}
|
|
577
|
-
},
|
|
578
|
-
agent: event.agent,
|
|
579
|
-
agentStatus: event.finalStatus ?? existing?.agentStatus ?? "unknown"
|
|
580
|
-
});
|
|
581
|
-
return;
|
|
582
|
-
}
|
|
583
|
-
if (event.type !== "agent_status_changed") return;
|
|
584
|
-
this.panes.set(event.paneId, {
|
|
585
|
-
...existing ?? {
|
|
586
|
-
paneId: event.paneId,
|
|
587
|
-
workspaceId: event.workspaceId,
|
|
588
|
-
stateLabels: {}
|
|
589
|
-
},
|
|
590
|
-
agent: event.agent ?? existing?.agent,
|
|
591
|
-
agentStatus: event.agentStatus,
|
|
592
|
-
displayAgent: event.displayAgent ?? existing?.displayAgent,
|
|
593
|
-
stateLabels: event.stateLabels ?? existing?.stateLabels ?? {},
|
|
594
|
-
title: event.title ?? existing?.title
|
|
595
|
-
});
|
|
596
|
-
}
|
|
597
546
|
snapshot() {
|
|
598
547
|
if (!this.currentPaneId || !this.currentWorkspaceId || !this.workspace) return void 0;
|
|
599
548
|
const rows = [...this.panes.values()].filter(
|
|
@@ -659,18 +608,21 @@ function herdrWidgetFingerprint(snapshot) {
|
|
|
659
608
|
}
|
|
660
609
|
|
|
661
610
|
// src/herdr-observer.ts
|
|
662
|
-
var MAX_PENDING_EVENTS = 1024;
|
|
663
611
|
var HerdrTopologyChangedError = class extends Error {
|
|
664
612
|
};
|
|
665
|
-
|
|
666
|
-
|
|
613
|
+
var HerdrCleanupError = class extends AggregateError {
|
|
614
|
+
};
|
|
615
|
+
function renderHerdrWidget(snapshot, theme, width) {
|
|
616
|
+
return createHerdrWidget(snapshot, theme).render(width);
|
|
667
617
|
}
|
|
668
618
|
function isRelevantEvent(model, event) {
|
|
669
|
-
if (event.type === "created"
|
|
619
|
+
if (event.type === "created" || event.type === "updated") {
|
|
620
|
+
return model.isCurrentWorkspace(event.pane.workspaceId);
|
|
621
|
+
}
|
|
670
622
|
if (event.type === "moved") {
|
|
671
623
|
return model.isCurrentPane(event.previousPaneId) || model.isCurrentWorkspace(event.previousWorkspaceId) || model.isCurrentWorkspace(event.pane.workspaceId);
|
|
672
624
|
}
|
|
673
|
-
return model.isCurrentWorkspace(event.workspaceId);
|
|
625
|
+
return "workspaceId" in event && model.isCurrentWorkspace(event.workspaceId);
|
|
674
626
|
}
|
|
675
627
|
function subscriptionFingerprint(currentPane, panes) {
|
|
676
628
|
const agentPaneIds = panes.filter((pane) => pane.agent !== void 0).map((pane) => pane.paneId).sort();
|
|
@@ -699,16 +651,17 @@ function createHerdrWidgetObserver(options) {
|
|
|
699
651
|
const subscribe = options.subscribe ?? openHerdrSubscription;
|
|
700
652
|
const retryDelayMs = options.retryDelayMs ?? 200;
|
|
701
653
|
let generation = 0;
|
|
702
|
-
let
|
|
654
|
+
let publisher;
|
|
703
655
|
let activeSession;
|
|
704
656
|
let controller;
|
|
705
657
|
const ownedTasks = /* @__PURE__ */ new Set();
|
|
658
|
+
const taskErrors = /* @__PURE__ */ new Set();
|
|
706
659
|
let publishedFingerprint;
|
|
707
660
|
let hasPublished = false;
|
|
708
|
-
const owns = (ctx, expectedGeneration = generation) =>
|
|
661
|
+
const owns = (ctx, expectedGeneration = generation) => expectedGeneration === generation && ctx.sessionManager === activeSession;
|
|
709
662
|
const requestId = (kind) => `herdr:pi:widget:${kind}:${now()}:${random().toString(36).slice(2)}`;
|
|
710
|
-
const clearWidget = (
|
|
711
|
-
|
|
663
|
+
const clearWidget = () => {
|
|
664
|
+
publisher?.publish(void 0);
|
|
712
665
|
publishedFingerprint = void 0;
|
|
713
666
|
hasPublished = false;
|
|
714
667
|
};
|
|
@@ -717,13 +670,7 @@ function createHerdrWidgetObserver(options) {
|
|
|
717
670
|
const snapshot = model.snapshot();
|
|
718
671
|
const fingerprint = herdrWidgetFingerprint(snapshot);
|
|
719
672
|
if (hasPublished && fingerprint === publishedFingerprint) return;
|
|
720
|
-
|
|
721
|
-
ctx.ui.setWidget(HERDR_WIDGET_KEY, void 0);
|
|
722
|
-
} else {
|
|
723
|
-
ctx.ui.setWidget(HERDR_WIDGET_KEY, (_tui, theme) => createHerdrWidget(snapshot, theme), {
|
|
724
|
-
placement: "aboveEditor"
|
|
725
|
-
});
|
|
726
|
-
}
|
|
673
|
+
publisher?.publish(snapshot);
|
|
727
674
|
publishedFingerprint = fingerprint;
|
|
728
675
|
hasPublished = true;
|
|
729
676
|
};
|
|
@@ -765,7 +712,11 @@ function createHerdrWidgetObserver(options) {
|
|
|
765
712
|
)
|
|
766
713
|
]);
|
|
767
714
|
if (!owns(ctx, expectedGeneration) || signal.aborted) return void 0;
|
|
768
|
-
const
|
|
715
|
+
const panes = parsePaneListResult(listResult);
|
|
716
|
+
const paneIds = new Set(panes.map((pane) => pane.paneId));
|
|
717
|
+
const namesByPane = new Map(
|
|
718
|
+
parseAgentListResult(agentResult).filter((pane) => pane.workspaceId === currentPane.workspaceId && paneIds.has(pane.paneId)).map((pane) => [pane.paneId, pane.agentName])
|
|
719
|
+
);
|
|
769
720
|
const withAgentName = (pane) => ({
|
|
770
721
|
...pane,
|
|
771
722
|
agentName: namesByPane.get(pane.paneId) ?? pane.agentName
|
|
@@ -776,7 +727,7 @@ function createHerdrWidgetObserver(options) {
|
|
|
776
727
|
}
|
|
777
728
|
return {
|
|
778
729
|
currentPane: withAgentName(currentPane),
|
|
779
|
-
panes:
|
|
730
|
+
panes: panes.map(withAgentName),
|
|
780
731
|
workspace
|
|
781
732
|
};
|
|
782
733
|
};
|
|
@@ -788,126 +739,99 @@ function createHerdrWidgetObserver(options) {
|
|
|
788
739
|
const signal = attemptController.signal;
|
|
789
740
|
let attemptActive = true;
|
|
790
741
|
let subscription;
|
|
791
|
-
let
|
|
742
|
+
let failure;
|
|
743
|
+
let attemptError;
|
|
744
|
+
let cleanupFailure;
|
|
745
|
+
let wake;
|
|
746
|
+
const wakeRefresh = () => {
|
|
747
|
+
const resolve = wake;
|
|
748
|
+
wake = void 0;
|
|
749
|
+
resolve?.();
|
|
750
|
+
};
|
|
751
|
+
signal.addEventListener("abort", wakeRefresh);
|
|
752
|
+
const failAttempt = (error) => {
|
|
753
|
+
if (!attemptActive || signal.aborted) return;
|
|
754
|
+
failure = error;
|
|
755
|
+
try {
|
|
756
|
+
if (owns(ctx, expectedGeneration)) clearWidget();
|
|
757
|
+
} catch (cleanupError) {
|
|
758
|
+
failure = new AggregateError([error, cleanupError], "Herdr subscription and widget cleanup failed");
|
|
759
|
+
} finally {
|
|
760
|
+
attemptController.abort(failure);
|
|
761
|
+
}
|
|
762
|
+
};
|
|
792
763
|
try {
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
if (reconfigureSettled) return;
|
|
812
|
-
reconfigureSettled = true;
|
|
813
|
-
rejectReconfigure(error);
|
|
814
|
-
};
|
|
815
|
-
const scheduleTopologyRefresh = () => {
|
|
816
|
-
if (!initialized || !attemptActive || signal.aborted) return;
|
|
817
|
-
if (refreshTask) {
|
|
818
|
-
refreshAgain = true;
|
|
819
|
-
return;
|
|
820
|
-
}
|
|
821
|
-
refreshTask = (async () => {
|
|
822
|
-
do {
|
|
823
|
-
refreshAgain = false;
|
|
824
|
-
refreshingTopology = true;
|
|
825
|
-
const refreshed = await loadPaneSet(ctx, expectedGeneration, signal);
|
|
826
|
-
if (!refreshed || !attemptActive || signal.aborted) return;
|
|
827
|
-
model.reset(refreshed.currentPane, refreshed.panes, refreshed.workspace);
|
|
828
|
-
for (const event of pendingStatusEvents.splice(0)) {
|
|
829
|
-
if (isRelevantEvent(model, event)) model.apply(event);
|
|
830
|
-
}
|
|
831
|
-
refreshingTopology = false;
|
|
832
|
-
publish(ctx, model, expectedGeneration);
|
|
833
|
-
if (subscriptionFingerprint(refreshed.currentPane, refreshed.panes) !== subscribedFingerprint) {
|
|
834
|
-
failAttempt(new HerdrTopologyChangedError());
|
|
835
|
-
return;
|
|
836
|
-
}
|
|
837
|
-
} while (refreshAgain && attemptActive && !signal.aborted);
|
|
838
|
-
})().catch((error) => {
|
|
839
|
-
failAttempt(error instanceof Error ? error : new Error(String(error)));
|
|
840
|
-
}).finally(() => {
|
|
841
|
-
refreshingTopology = false;
|
|
842
|
-
refreshTask = void 0;
|
|
843
|
-
});
|
|
844
|
-
};
|
|
845
|
-
subscription = await subscribe(
|
|
846
|
-
options.environment.socketEndpoint,
|
|
847
|
-
{
|
|
848
|
-
id: requestId("subscribe"),
|
|
849
|
-
method: "events.subscribe",
|
|
850
|
-
params: { subscriptions: herdrWidgetSubscriptions(discovered.panes) }
|
|
851
|
-
},
|
|
852
|
-
signal,
|
|
853
|
-
(frame) => {
|
|
854
|
-
const event = parseHerdrPaneEvent(frame);
|
|
855
|
-
if (!initialized) {
|
|
764
|
+
await (async () => {
|
|
765
|
+
const discovered = await loadPaneSet(ctx, expectedGeneration, signal);
|
|
766
|
+
if (!discovered) return;
|
|
767
|
+
const subscribedFingerprint = subscriptionFingerprint(discovered.currentPane, discovered.panes);
|
|
768
|
+
const model = new HerdrWidgetModel();
|
|
769
|
+
model.reset(discovered.currentPane, discovered.panes, discovered.workspace);
|
|
770
|
+
let dirty = true;
|
|
771
|
+
subscription = await subscribe(
|
|
772
|
+
options.environment.socketEndpoint,
|
|
773
|
+
{
|
|
774
|
+
id: requestId("subscribe"),
|
|
775
|
+
method: "events.subscribe",
|
|
776
|
+
params: { subscriptions: herdrWidgetSubscriptions(discovered.panes) }
|
|
777
|
+
},
|
|
778
|
+
signal,
|
|
779
|
+
(frame) => {
|
|
780
|
+
if (!attemptActive || !owns(ctx, expectedGeneration) || signal.aborted) return;
|
|
781
|
+
const event = parseHerdrPaneEvent(frame);
|
|
856
782
|
if (!event || !isRelevantEvent(model, event)) return;
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
return;
|
|
860
|
-
}
|
|
861
|
-
if (pendingEvents.length >= MAX_PENDING_EVENTS) {
|
|
862
|
-
throw new Error("Too many Herdr events arrived during initialization");
|
|
863
|
-
}
|
|
864
|
-
pendingEvents.push(event);
|
|
865
|
-
return;
|
|
783
|
+
dirty = true;
|
|
784
|
+
wakeRefresh();
|
|
866
785
|
}
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
if (
|
|
871
|
-
|
|
872
|
-
return;
|
|
786
|
+
).catch(async (error) => {
|
|
787
|
+
if (!owns(ctx, expectedGeneration) || signal.aborted) throw error;
|
|
788
|
+
const latest = await loadPaneSet(ctx, expectedGeneration, signal);
|
|
789
|
+
if (latest && subscriptionFingerprint(latest.currentPane, latest.panes) !== subscribedFingerprint) {
|
|
790
|
+
throw new HerdrTopologyChangedError();
|
|
873
791
|
}
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
792
|
+
throw error;
|
|
793
|
+
});
|
|
794
|
+
void subscription.closed.then(
|
|
795
|
+
() => failAttempt(new Error("Herdr subscription ended")),
|
|
796
|
+
(error) => failAttempt(error instanceof Error ? error : new Error(String(error)))
|
|
797
|
+
);
|
|
798
|
+
while (owns(ctx, expectedGeneration) && !signal.aborted) {
|
|
799
|
+
dirty = false;
|
|
800
|
+
const refreshed = await loadPaneSet(ctx, expectedGeneration, signal);
|
|
801
|
+
if (!refreshed || signal.aborted) break;
|
|
802
|
+
if (dirty) continue;
|
|
803
|
+
if (subscriptionFingerprint(refreshed.currentPane, refreshed.panes) !== subscribedFingerprint) {
|
|
804
|
+
throw new HerdrTopologyChangedError();
|
|
880
805
|
}
|
|
881
|
-
model.
|
|
806
|
+
model.reset(refreshed.currentPane, refreshed.panes, refreshed.workspace);
|
|
882
807
|
publish(ctx, model, expectedGeneration);
|
|
808
|
+
await new Promise((resolve) => {
|
|
809
|
+
wake = resolve;
|
|
810
|
+
if (dirty || signal.aborted) wakeRefresh();
|
|
811
|
+
});
|
|
883
812
|
}
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
model.reset(reconciled.currentPane, reconciled.panes, reconciled.workspace);
|
|
889
|
-
for (const event of pendingEvents.splice(0)) {
|
|
890
|
-
if (isRelevantEvent(model, event)) model.apply(event);
|
|
891
|
-
}
|
|
892
|
-
if (subscriptionFingerprint(reconciled.currentPane, reconciled.panes) !== subscribedFingerprint) {
|
|
893
|
-
throw new HerdrTopologyChangedError();
|
|
894
|
-
}
|
|
895
|
-
initialized = true;
|
|
896
|
-
publish(ctx, model, expectedGeneration);
|
|
897
|
-
if (topologyPending) scheduleTopologyRefresh();
|
|
898
|
-
await Promise.race([
|
|
899
|
-
subscription.closed.then(() => {
|
|
900
|
-
if (!signal.aborted) throw new Error("Herdr subscription ended");
|
|
901
|
-
}),
|
|
902
|
-
reconfigure
|
|
903
|
-
]);
|
|
813
|
+
if (failure) throw failure;
|
|
814
|
+
})();
|
|
815
|
+
} catch (error) {
|
|
816
|
+
attemptError = { error };
|
|
904
817
|
} finally {
|
|
905
818
|
attemptActive = false;
|
|
906
819
|
attemptController.abort(new DOMException("Herdr widget attempt ended", "AbortError"));
|
|
820
|
+
signal.removeEventListener("abort", wakeRefresh);
|
|
907
821
|
sessionSignal.removeEventListener("abort", abortAttempt);
|
|
908
|
-
|
|
909
|
-
|
|
822
|
+
try {
|
|
823
|
+
subscription?.close();
|
|
824
|
+
} catch (cleanupError) {
|
|
825
|
+
cleanupFailure = { error: cleanupError };
|
|
826
|
+
}
|
|
910
827
|
}
|
|
828
|
+
if (cleanupFailure) {
|
|
829
|
+
throw new HerdrCleanupError(
|
|
830
|
+
attemptError ? [attemptError.error, cleanupFailure.error] : [cleanupFailure.error],
|
|
831
|
+
"Herdr subscription cleanup failed"
|
|
832
|
+
);
|
|
833
|
+
}
|
|
834
|
+
if (attemptError) throw attemptError.error;
|
|
911
835
|
};
|
|
912
836
|
const run = async (ctx, expectedGeneration, signal) => {
|
|
913
837
|
let failures = 0;
|
|
@@ -916,8 +840,13 @@ function createHerdrWidgetObserver(options) {
|
|
|
916
840
|
await runAttempt(ctx, expectedGeneration, signal);
|
|
917
841
|
return;
|
|
918
842
|
} catch (error) {
|
|
843
|
+
if (error instanceof HerdrCleanupError) throw error;
|
|
919
844
|
if (!owns(ctx, expectedGeneration) || signal.aborted) return;
|
|
920
|
-
|
|
845
|
+
try {
|
|
846
|
+
clearWidget();
|
|
847
|
+
} catch (cleanupError) {
|
|
848
|
+
throw new AggregateError([error, cleanupError], "Herdr observation and widget cleanup failed");
|
|
849
|
+
}
|
|
921
850
|
if (error instanceof HerdrTopologyChangedError) continue;
|
|
922
851
|
failures += 1;
|
|
923
852
|
if (failures >= 2) return;
|
|
@@ -932,33 +861,61 @@ function createHerdrWidgetObserver(options) {
|
|
|
932
861
|
};
|
|
933
862
|
return {
|
|
934
863
|
start(ctx) {
|
|
935
|
-
generation += 1;
|
|
936
864
|
controller?.abort(new DOMException("Herdr widget session replaced", "AbortError"));
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
865
|
+
try {
|
|
866
|
+
publisher?.dispose();
|
|
867
|
+
} finally {
|
|
868
|
+
publisher = void 0;
|
|
869
|
+
generation += 1;
|
|
870
|
+
activeSession = void 0;
|
|
871
|
+
controller = void 0;
|
|
872
|
+
publishedFingerprint = void 0;
|
|
873
|
+
hasPublished = false;
|
|
874
|
+
}
|
|
941
875
|
if (ctx.mode !== "tui") return;
|
|
942
|
-
activeContext = ctx;
|
|
943
876
|
activeSession = ctx.sessionManager;
|
|
944
877
|
controller = new AbortController();
|
|
945
878
|
const expectedGeneration = generation;
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
879
|
+
publisher = createEditorStatusPublisher({
|
|
880
|
+
key: HERDR_WIDGET_KEY,
|
|
881
|
+
context: ctx,
|
|
882
|
+
isCurrent: () => expectedGeneration === generation,
|
|
883
|
+
render: renderHerdrWidget
|
|
949
884
|
});
|
|
885
|
+
const task = run(ctx, expectedGeneration, controller.signal);
|
|
950
886
|
ownedTasks.add(task);
|
|
887
|
+
void task.then(
|
|
888
|
+
() => ownedTasks.delete(task),
|
|
889
|
+
(error) => {
|
|
890
|
+
taskErrors.add(error);
|
|
891
|
+
ownedTasks.delete(task);
|
|
892
|
+
}
|
|
893
|
+
);
|
|
951
894
|
},
|
|
952
895
|
async shutdown(ctx) {
|
|
953
|
-
if (!owns(ctx)) return;
|
|
954
|
-
const shutdownGeneration = ++generation;
|
|
896
|
+
if (activeSession !== void 0 && !owns(ctx)) return;
|
|
955
897
|
controller?.abort(new DOMException("Herdr widget session shut down", "AbortError"));
|
|
956
|
-
|
|
898
|
+
const errors = [];
|
|
899
|
+
try {
|
|
900
|
+
publisher?.dispose();
|
|
901
|
+
} catch (error) {
|
|
902
|
+
errors.push(error);
|
|
903
|
+
} finally {
|
|
904
|
+
publisher = void 0;
|
|
905
|
+
generation += 1;
|
|
906
|
+
publishedFingerprint = void 0;
|
|
907
|
+
hasPublished = false;
|
|
908
|
+
}
|
|
909
|
+
const shutdownGeneration = generation;
|
|
957
910
|
await Promise.allSettled([...ownedTasks]);
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
911
|
+
errors.push(...taskErrors);
|
|
912
|
+
taskErrors.clear();
|
|
913
|
+
if (generation === shutdownGeneration) {
|
|
914
|
+
activeSession = void 0;
|
|
915
|
+
controller = void 0;
|
|
916
|
+
}
|
|
917
|
+
if (errors.length === 1) throw errors[0];
|
|
918
|
+
if (errors.length > 1) throw new AggregateError(errors, "Herdr widget cleanup failed");
|
|
962
919
|
}
|
|
963
920
|
};
|
|
964
921
|
}
|
|
@@ -1285,7 +1242,8 @@ function createHerdrAgentStateExtension(options = {}) {
|
|
|
1285
1242
|
let metadataDrainTask;
|
|
1286
1243
|
let lastMetadataSnapshot;
|
|
1287
1244
|
let metadataRefreshTimer;
|
|
1288
|
-
|
|
1245
|
+
const sessionReportTasks = /* @__PURE__ */ new Set();
|
|
1246
|
+
let shutdownController;
|
|
1289
1247
|
let shutdownSession;
|
|
1290
1248
|
let shutdownTask;
|
|
1291
1249
|
function requestId(kind) {
|
|
@@ -1323,7 +1281,7 @@ function createHerdrAgentStateExtension(options = {}) {
|
|
|
1323
1281
|
function reportSession(sessionStartSource) {
|
|
1324
1282
|
const sessionRef = currentSessionRef();
|
|
1325
1283
|
if (!sessionRef) return Promise.resolve();
|
|
1326
|
-
|
|
1284
|
+
const task = safeSend(
|
|
1327
1285
|
{
|
|
1328
1286
|
id: requestId("session"),
|
|
1329
1287
|
method: "pane.report_agent_session",
|
|
@@ -1338,6 +1296,9 @@ function createHerdrAgentStateExtension(options = {}) {
|
|
|
1338
1296
|
},
|
|
1339
1297
|
sessionController.signal
|
|
1340
1298
|
);
|
|
1299
|
+
sessionReportTasks.add(task);
|
|
1300
|
+
void task.finally(() => sessionReportTasks.delete(task));
|
|
1301
|
+
return task;
|
|
1341
1302
|
}
|
|
1342
1303
|
function stateRequest(state) {
|
|
1343
1304
|
return {
|
|
@@ -1477,8 +1438,10 @@ function createHerdrAgentStateExtension(options = {}) {
|
|
|
1477
1438
|
const generation = ++sessionGeneration;
|
|
1478
1439
|
const replaced = new DOMException("Herdr session replaced", "AbortError");
|
|
1479
1440
|
sessionController.abort(replaced);
|
|
1480
|
-
|
|
1481
|
-
|
|
1441
|
+
shutdownController?.abort(replaced);
|
|
1442
|
+
shutdownController = void 0;
|
|
1443
|
+
shutdownTask = void 0;
|
|
1444
|
+
shutdownSession = void 0;
|
|
1482
1445
|
if (metadataRefreshTimer) clearTimeout(metadataRefreshTimer);
|
|
1483
1446
|
metadataRefreshTimer = void 0;
|
|
1484
1447
|
queuedMetadata = void 0;
|
|
@@ -1500,7 +1463,7 @@ function createHerdrAgentStateExtension(options = {}) {
|
|
|
1500
1463
|
const sessionReport = reportSession(event.reason);
|
|
1501
1464
|
publishMetadata(ctx);
|
|
1502
1465
|
await Promise.all([sessionReport, widgetStart]);
|
|
1503
|
-
if (generation !== sessionGeneration || sessionController.signal.aborted || !rootSession) {
|
|
1466
|
+
if (generation !== sessionGeneration || activeSession !== ctx.sessionManager || sessionController.signal.aborted || !rootSession) {
|
|
1504
1467
|
return;
|
|
1505
1468
|
}
|
|
1506
1469
|
agentActive = !ctx.isIdle();
|
|
@@ -1543,24 +1506,27 @@ function createHerdrAgentStateExtension(options = {}) {
|
|
|
1543
1506
|
sessionController.abort(new DOMException("Herdr session shut down", "AbortError"));
|
|
1544
1507
|
queuedState = void 0;
|
|
1545
1508
|
queuedMetadata = void 0;
|
|
1546
|
-
await Promise.allSettled([drainTask, metadataDrainTask, widget.shutdown(ctx)]);
|
|
1547
|
-
const stillOwnsShutdown = shutdownGeneration === sessionGeneration && activeSession === session && !rootSession;
|
|
1548
|
-
if (shouldClearMetadata && stillOwnsShutdown) {
|
|
1509
|
+
await Promise.allSettled([...sessionReportTasks, drainTask, metadataDrainTask, widget.shutdown(ctx)]);
|
|
1510
|
+
const stillOwnsShutdown = () => shutdownGeneration === sessionGeneration && activeSession === session && !rootSession;
|
|
1511
|
+
if (shouldClearMetadata && stillOwnsShutdown()) {
|
|
1549
1512
|
const controller = new AbortController();
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1513
|
+
shutdownController = controller;
|
|
1514
|
+
try {
|
|
1515
|
+
await safeSend(
|
|
1516
|
+
createHerdrMetadataRequest({
|
|
1517
|
+
id: requestId(),
|
|
1518
|
+
paneId: environment.paneId,
|
|
1519
|
+
source: SOURCE,
|
|
1520
|
+
seq: nextReportSeq(),
|
|
1521
|
+
snapshot: createHerdrMetadataClearSnapshot()
|
|
1522
|
+
}),
|
|
1523
|
+
controller.signal
|
|
1524
|
+
);
|
|
1525
|
+
} finally {
|
|
1526
|
+
if (shutdownController === controller) shutdownController = void 0;
|
|
1527
|
+
}
|
|
1562
1528
|
}
|
|
1563
|
-
if (
|
|
1529
|
+
if (!stillOwnsShutdown()) {
|
|
1564
1530
|
return;
|
|
1565
1531
|
}
|
|
1566
1532
|
lastMetadataSnapshot = void 0;
|