@giladbarnea/pi-simple-team 2.0.20 → 2.0.22
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 +2 -1
- package/child-tools.ts +38 -2
- package/index.ts +113 -27
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -149,7 +149,8 @@ Your main uses `team_log` when it needs to understand the chain of events in hig
|
|
|
149
149
|
Provides main a timestamped, filterable, append-only record of the team’s messages, tool calls, and lifecycle events.
|
|
150
150
|
Attempts can end before retries finish. A separate run row reports final settlement as ended or cancelled. Ended does not imply success.
|
|
151
151
|
A run that ends on a provider error adds an error row with the provider's message and sets the teammate's status to `error` with that message, until a later run completes. Main also gets a message saying so.
|
|
152
|
-
A background teammate that exits without being stopped, after it registered, also sends main a message with its exit code. A teammate that quits itself (exit code 0) does not.
|
|
152
|
+
A background teammate that exits without being stopped, after it registered, also sends main a message with its exit code. A teammate that quits itself (exit code 0) does not.
|
|
153
|
+
A Herdr pane teammate gets the same messages. If its process dies, main is told that it exited. If it is idle when its pane is closed, or it receives SIGHUP or SIGTERM, main gets a neutral message that names the signal, because either can be on purpose. A pane closed while its teammate works usually ends Pi at once, so main is told that it exited. A restart closes the teammate's previous pane. A pane that main closes itself sends nothing.
|
|
153
154
|
|
|
154
155
|
### 🌅 Herdr Support
|
|
155
156
|
|
package/child-tools.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import * as http from "node:http";
|
|
2
|
+
import * as net from "node:net";
|
|
2
3
|
import { defineTool, getMarkdownTheme, type AgentActivityOutcome, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
4
|
import { Type } from "typebox";
|
|
4
5
|
import { formatContextWindowReport, requireKnownContextUsage } from "./context-window.ts";
|
|
@@ -32,6 +33,8 @@ export interface ChildRuntimeConfig {
|
|
|
32
33
|
teamId?: string;
|
|
33
34
|
teamName: string;
|
|
34
35
|
teammateName: string;
|
|
36
|
+
/** Names this start of the teammate's process to main. A main that predates process ids sets none and checks none. */
|
|
37
|
+
processId?: string;
|
|
35
38
|
participants: string[];
|
|
36
39
|
canManageOwnTeams: boolean;
|
|
37
40
|
interruptWaitTimeoutMilliseconds?: number;
|
|
@@ -60,6 +63,7 @@ function readRequiredChildRuntimeConfig(): ChildRuntimeConfig {
|
|
|
60
63
|
teamId,
|
|
61
64
|
teamName: requiredEnvironmentVariable("PI_SIMPLE_TEAM_TEAM_NAME"),
|
|
62
65
|
teammateName: requiredEnvironmentVariable("PI_SIMPLE_TEAM_MEMBER"),
|
|
66
|
+
processId: process.env.PI_SIMPLE_TEAM_PROCESS,
|
|
63
67
|
participants: readParticipants(),
|
|
64
68
|
canManageOwnTeams: process.env.PI_SIMPLE_TEAM_CAN_MANAGE_OWN_TEAMS === "1",
|
|
65
69
|
};
|
|
@@ -94,6 +98,7 @@ export async function callParent(config: ChildRuntimeConfig, tool: string, args:
|
|
|
94
98
|
token: config.callbackToken,
|
|
95
99
|
team: config.teamId ?? config.teamName,
|
|
96
100
|
from: config.teammateName,
|
|
101
|
+
process: config.processId,
|
|
97
102
|
tool,
|
|
98
103
|
args,
|
|
99
104
|
}),
|
|
@@ -107,6 +112,35 @@ export async function callParent(config: ChildRuntimeConfig, tool: string, args:
|
|
|
107
112
|
return (await response.json()) as JsonRecord;
|
|
108
113
|
}
|
|
109
114
|
|
|
115
|
+
type ShutdownSignal = "SIGHUP" | "SIGTERM";
|
|
116
|
+
|
|
117
|
+
/** Lives on globalThis, because it belongs to the process: Pi loads this module again on a reload or a session replacement. */
|
|
118
|
+
interface ProcessLifeline {
|
|
119
|
+
socket: net.Socket;
|
|
120
|
+
signal?: ShutdownSignal;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const lifelineKey: unique symbol = Symbol.for("pi-simple-team.lifeline");
|
|
124
|
+
const lifelineHolder = globalThis as { [lifelineKey]?: ProcessLifeline };
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Main has no process handle for a Herdr pane teammate. This connection stays open for the life of the process, so its close tells main that the process ended.
|
|
128
|
+
* The process also notes the signal that shuts it down in order, because a closed pane arrives as SIGHUP. Pi's interactive mode registers its own handlers for both signals before it loads extensions, so these listeners never replace the default termination.
|
|
129
|
+
*/
|
|
130
|
+
function holdLifeline(config: ChildRuntimeConfig, port: number): void {
|
|
131
|
+
if (lifelineHolder[lifelineKey]) return;
|
|
132
|
+
const socket = net.connect(port, "127.0.0.1", () => {
|
|
133
|
+
socket.write(`${JSON.stringify({ token: config.callbackToken, team: config.teamId ?? config.teamName, from: config.teammateName, process: config.processId })}\n`);
|
|
134
|
+
});
|
|
135
|
+
// Main closing first must not crash the teammate.
|
|
136
|
+
socket.on("error", () => undefined);
|
|
137
|
+
socket.unref();
|
|
138
|
+
const lifeline: ProcessLifeline = { socket };
|
|
139
|
+
// Prepended, because Pi 1.4 emits session_shutdown from inside its own signal handler.
|
|
140
|
+
for (const signal of ["SIGHUP", "SIGTERM"] as const) process.prependListener(signal, () => { lifeline.signal ??= signal; });
|
|
141
|
+
lifelineHolder[lifelineKey] = lifeline;
|
|
142
|
+
}
|
|
143
|
+
|
|
110
144
|
function toolResult(payload: JsonRecord): { content: [{ type: "text"; text: string }]; details: JsonRecord } {
|
|
111
145
|
return {
|
|
112
146
|
content: [{ type: "text" as const, text: JSON.stringify(payload, null, 2) }],
|
|
@@ -289,8 +323,9 @@ function startChildRuntime(pi: ExtensionAPI, config: ChildRuntimeConfig): void {
|
|
|
289
323
|
const address = server.address();
|
|
290
324
|
if (!address || typeof address === "string") throw new Error("Child delivery server did not get a port");
|
|
291
325
|
|
|
326
|
+
let registration: JsonRecord;
|
|
292
327
|
try {
|
|
293
|
-
await callParent(config, "register", {
|
|
328
|
+
registration = await callParent(config, "register", {
|
|
294
329
|
url: `http://127.0.0.1:${address.port}/deliver`,
|
|
295
330
|
sessionId: context.sessionManager.getSessionId(),
|
|
296
331
|
sessionFile: context.sessionManager.getSessionFile(),
|
|
@@ -301,11 +336,12 @@ function startChildRuntime(pi: ExtensionAPI, config: ChildRuntimeConfig): void {
|
|
|
301
336
|
context.shutdown();
|
|
302
337
|
throw error;
|
|
303
338
|
}
|
|
339
|
+
if (typeof registration.lifelinePort === "number") holdLifeline(config, registration.lifelinePort);
|
|
304
340
|
});
|
|
305
341
|
|
|
306
342
|
pi.on("session_shutdown", async (event) => {
|
|
307
343
|
markIdle();
|
|
308
|
-
await notifyParent({ type: "session_shutdown", reason: event.reason });
|
|
344
|
+
await notifyParent({ type: "session_shutdown", reason: event.reason, signal: lifelineHolder[lifelineKey]?.signal });
|
|
309
345
|
await new Promise<void>((resolve, reject) => {
|
|
310
346
|
if (!server) {
|
|
311
347
|
resolve();
|
package/index.ts
CHANGED
|
@@ -3,6 +3,7 @@ import type { ChildProcess } from "node:child_process";
|
|
|
3
3
|
import crypto from "node:crypto";
|
|
4
4
|
import * as fs from "node:fs";
|
|
5
5
|
import http from "node:http";
|
|
6
|
+
import * as net from "node:net";
|
|
6
7
|
import * as path from "node:path";
|
|
7
8
|
import { fileURLToPath } from "node:url";
|
|
8
9
|
import { defineTool, type ContextUsage, type ExtensionAPI, type ExtensionContext, getMarkdownTheme, getPackageDir } from "@earendil-works/pi-coding-agent";
|
|
@@ -49,11 +50,19 @@ interface RunFailure {
|
|
|
49
50
|
replaced: TeamStatus;
|
|
50
51
|
}
|
|
51
52
|
|
|
52
|
-
/**
|
|
53
|
-
|
|
53
|
+
/**
|
|
54
|
+
* One start of a teammate's process. Main gives the process this record's id, and the process sends it with every callback,
|
|
55
|
+
* so main never mistakes a replaced process for the current one. Its end is judged by its own record.
|
|
56
|
+
* Main has no process handle for a Herdr pane teammate, so that process also holds a lifeline connection, which closes when it ends.
|
|
57
|
+
*/
|
|
58
|
+
interface ProcessRecord {
|
|
59
|
+
id: string;
|
|
54
60
|
registered: boolean;
|
|
55
61
|
stopRequested: boolean;
|
|
56
62
|
quitReported: boolean;
|
|
63
|
+
/** Set once main has recorded this process's end, so a callback still in flight when it died changes nothing. */
|
|
64
|
+
ended?: boolean;
|
|
65
|
+
lifeline?: net.Socket;
|
|
57
66
|
}
|
|
58
67
|
|
|
59
68
|
interface TeammateState {
|
|
@@ -70,7 +79,7 @@ interface TeammateState {
|
|
|
70
79
|
sessionMaterialized: boolean;
|
|
71
80
|
lastModelActivityAt?: string;
|
|
72
81
|
process?: ChildProcess;
|
|
73
|
-
processRecord?:
|
|
82
|
+
processRecord?: ProcessRecord;
|
|
74
83
|
paneId?: string;
|
|
75
84
|
deliveryUrl?: string;
|
|
76
85
|
ready?: Promise<void>;
|
|
@@ -117,6 +126,8 @@ const callbackToken = crypto.randomBytes(24).toString("hex");
|
|
|
117
126
|
let callbackServer: http.Server | undefined;
|
|
118
127
|
let callbackReady: Promise<void> | undefined;
|
|
119
128
|
let callbackUrl = "";
|
|
129
|
+
let lifelineServer: net.Server | undefined;
|
|
130
|
+
let lifelinePort = 0;
|
|
120
131
|
|
|
121
132
|
function status(word: string, phrase: string): TeamStatus {
|
|
122
133
|
return { word, phrase, updated: new Date().toISOString() };
|
|
@@ -376,19 +387,56 @@ function notifyOwner(team: TeamState, teammate: TeammateState, notification: str
|
|
|
376
387
|
* A notice for an exit nobody asked for. A self-quit (code 0 after a quit shutdown) and a stop by the parent are excluded.
|
|
377
388
|
* @example isUnexpectedExit({ registered: true, stopRequested: false, quitReported: true }, 143, null) // true
|
|
378
389
|
*/
|
|
379
|
-
function isUnexpectedExit(record:
|
|
390
|
+
function isUnexpectedExit(record: ProcessRecord, code: number | null, signal: NodeJS.Signals | null): boolean {
|
|
380
391
|
const selfQuit = code === 0 && signal === null && record.quitReported;
|
|
381
392
|
return record.registered && !record.stopRequested && !selfQuit;
|
|
382
393
|
}
|
|
383
394
|
|
|
384
|
-
/**
|
|
385
|
-
|
|
395
|
+
/**
|
|
396
|
+
* Tells the team owner that a teammate's process ended, in the same three lines for every transport: what happened, the cause, what to do.
|
|
397
|
+
* Waits for main's own shutdown to mark the team first, so a signal that reaches main and its teammates together sends nothing.
|
|
398
|
+
*/
|
|
399
|
+
function scheduleEndNotice(team: TeamState, teammate: TeammateState, happened: string, cause: string, advice: string): void {
|
|
386
400
|
setTimeout(() => {
|
|
387
401
|
if (team.stopping || teams.get(team.id ?? team.name) !== team) return;
|
|
388
|
-
notifyOwner(team, teammate, `Teammate "${teammate.name}" on team "${team.name}" (team ID: ${team.id ?? team.name})
|
|
402
|
+
notifyOwner(team, teammate, `Teammate "${teammate.name}" on team "${team.name}" (team ID: ${team.id ?? team.name}) ${happened}.\nCause: ${cause}\n${advice}`);
|
|
389
403
|
}, exitNoticeGraceMilliseconds).unref();
|
|
390
404
|
}
|
|
391
405
|
|
|
406
|
+
/** A Herdr pane teammate's process ended without a shutdown callback: a crash, a kill, or a terminal that vanished under a working Pi. */
|
|
407
|
+
function recordAbruptEnd(team: TeamState, teammate: TeammateState, record: ProcessRecord): void {
|
|
408
|
+
if (record.stopRequested || record.quitReported || record.ended) return;
|
|
409
|
+
record.ended = true;
|
|
410
|
+
teammate.alive = false;
|
|
411
|
+
teammate.active = false;
|
|
412
|
+
teammate.deliveryUrl = undefined;
|
|
413
|
+
team.statuses.set(teammate.name, status("stopped", "Ended without shutting down"));
|
|
414
|
+
appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "exit", summary: "ended without shutting down" });
|
|
415
|
+
persistActiveTeamManifest(team);
|
|
416
|
+
scheduleEndNotice(team, teammate, "exited", "its Pi process ended without shutting down (a crash, a kill, or its pane closed while it worked)", "Check its pane if it is still open. Use team_resume to restart it.");
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
type ShutdownSignal = "SIGHUP" | "SIGTERM";
|
|
420
|
+
|
|
421
|
+
/** What a signal shutdown most likely means. Nobody can tell who sent the signal or why, so neither reads as a failure. */
|
|
422
|
+
const signalReasons: Record<ShutdownSignal, string> = {
|
|
423
|
+
SIGHUP: "Its pane may have been closed on purpose.",
|
|
424
|
+
SIGTERM: "Something outside the team may have stopped it on purpose.",
|
|
425
|
+
};
|
|
426
|
+
|
|
427
|
+
/** A teammate's Pi shut down in order. Only a Herdr pane teammate reports a signal: nobody can tell who closed its pane or why, so the notice stays neutral. */
|
|
428
|
+
function recordQuit(team: TeamState, teammate: TeammateState, signal: unknown): void {
|
|
429
|
+
const record = teammate.processRecord!;
|
|
430
|
+
if (record.ended) return;
|
|
431
|
+
record.ended = true;
|
|
432
|
+
record.quitReported = true;
|
|
433
|
+
const afterSignal = typeof signal === "string" ? ` after ${signal}` : "";
|
|
434
|
+
team.statuses.set(teammate.name, status("stopped", afterSignal ? `Shut down${afterSignal}` : "Session shut down"));
|
|
435
|
+
appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "exit", summary: `session shut down${afterSignal}`, details: { reason: "quit", ...(afterSignal ? { signal } : {}) } });
|
|
436
|
+
if (!afterSignal || record.stopRequested) return;
|
|
437
|
+
scheduleEndNotice(team, teammate, `shut down${afterSignal}`, `its Pi received ${signal} and shut down in order. ${signalReasons[signal as ShutdownSignal]}`, "Use team_resume to restart it if you still need it.");
|
|
438
|
+
}
|
|
439
|
+
|
|
392
440
|
async function kickoffTeammates(team: TeamState, teammates: TeammateState[], startIdle: boolean, resumption?: { instructions?: string; emptyRestarts: TeammateState[] }): Promise<void> {
|
|
393
441
|
const outcomes = await Promise.allSettled(teammates.map((teammate) => {
|
|
394
442
|
const initialize = !resumption || resumption.emptyRestarts.includes(teammate);
|
|
@@ -563,6 +611,7 @@ function childEnvironmentOverrides(team: TeamState, teammate: TeammateState, par
|
|
|
563
611
|
PI_SIMPLE_TEAM_TEAM: team.id ?? team.name,
|
|
564
612
|
PI_SIMPLE_TEAM_TEAM_NAME: team.name,
|
|
565
613
|
PI_SIMPLE_TEAM_MEMBER: teammate.name,
|
|
614
|
+
PI_SIMPLE_TEAM_PROCESS: teammate.processRecord!.id,
|
|
566
615
|
PI_SIMPLE_TEAM_PARTICIPANTS: JSON.stringify(participants),
|
|
567
616
|
PI_SIMPLE_TEAM_CAN_MANAGE_OWN_TEAMS: teammate.canManageOwnTeams ? "1" : "0",
|
|
568
617
|
};
|
|
@@ -617,9 +666,9 @@ function attachRpcTeammate(team: TeamState, teammate: TeammateState, participant
|
|
|
617
666
|
stdio: ["pipe", "ignore", "pipe"],
|
|
618
667
|
env: { ...process.env, ...childEnvironmentOverrides(team, teammate, participants) },
|
|
619
668
|
});
|
|
620
|
-
const record
|
|
669
|
+
const record = teammate.processRecord!;
|
|
670
|
+
const rejectReady = teammate.rejectReady;
|
|
621
671
|
teammate.process = proc;
|
|
622
|
-
teammate.processRecord = record;
|
|
623
672
|
teammate.alive = true;
|
|
624
673
|
|
|
625
674
|
proc.stderr?.on("data", (chunk: Buffer | string) => {
|
|
@@ -628,10 +677,10 @@ function attachRpcTeammate(team: TeamState, teammate: TeammateState, participant
|
|
|
628
677
|
});
|
|
629
678
|
proc.on("exit", (code, signal) => {
|
|
630
679
|
teammate.alive = false;
|
|
631
|
-
|
|
680
|
+
rejectReady?.(new Error(`${teammate.name} exited (code=${code}, signal=${signal})`));
|
|
632
681
|
team.statuses.set(teammate.name, status("stopped", `Exited code=${code} signal=${signal}`));
|
|
633
682
|
appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "exit", summary: `exited (code=${code}, signal=${signal})`, details: { code, signal } });
|
|
634
|
-
if (isUnexpectedExit(record, code, signal))
|
|
683
|
+
if (isUnexpectedExit(record, code, signal)) scheduleEndNotice(team, teammate, "exited", `exited (code=${code}, signal=${signal})`, "Code 143 or 129 means its Pi shut down after SIGTERM or SIGHUP. Check team_log for its last stderr lines. Use team_resume to restart it.");
|
|
635
684
|
});
|
|
636
685
|
appendSpawnLog(team, teammate);
|
|
637
686
|
}
|
|
@@ -711,6 +760,10 @@ async function startTeammate(
|
|
|
711
760
|
startOptions: ChildStartOptions = {},
|
|
712
761
|
): Promise<void> {
|
|
713
762
|
startOptions.signal?.throwIfAborted();
|
|
763
|
+
// A Pi session has no lock against a second writer, so a restart ends the previous process, or closes its pane, before it starts the next.
|
|
764
|
+
await stopRpcTeammate(teammate);
|
|
765
|
+
await closeHerdrPane(teammate);
|
|
766
|
+
teammate.processRecord = { id: crypto.randomUUID(), registered: false, stopRequested: false, quitReported: false };
|
|
714
767
|
if (teammate.transport === "herdr") await attachHerdrTeammate(team, teammate, participants, herdrParentPaneId!, startOptions);
|
|
715
768
|
else attachRpcTeammate(team, teammate, participants, startOptions);
|
|
716
769
|
await awaitChildRegistration(teammate, startOptions.signal);
|
|
@@ -752,6 +805,8 @@ function isHerdrPaneNotFound(error: unknown): boolean {
|
|
|
752
805
|
|
|
753
806
|
async function closeHerdrPane(teammate: TeammateState): Promise<void> {
|
|
754
807
|
if (!teammate.paneId) return;
|
|
808
|
+
teammate.processRecord!.stopRequested = true;
|
|
809
|
+
teammate.processRecord!.lifeline?.destroy();
|
|
755
810
|
try {
|
|
756
811
|
await runCommand("herdr", ["pane", "close", teammate.paneId], 10_000);
|
|
757
812
|
} catch (error) {
|
|
@@ -762,7 +817,7 @@ async function closeHerdrPane(teammate: TeammateState): Promise<void> {
|
|
|
762
817
|
|
|
763
818
|
async function stopRpcTeammate(teammate: TeammateState): Promise<void> {
|
|
764
819
|
const processToStop = teammate.process;
|
|
765
|
-
if (!processToStop ||
|
|
820
|
+
if (!processToStop || processToStop.exitCode !== null || processToStop.signalCode !== null) return;
|
|
766
821
|
|
|
767
822
|
await new Promise<void>((resolve) => {
|
|
768
823
|
let forceKillTimeout: ReturnType<typeof setTimeout> | undefined;
|
|
@@ -827,11 +882,49 @@ async function shutdownTeam(team: TeamState): Promise<string[]> {
|
|
|
827
882
|
function closeCallbackServerIfUnused(): void {
|
|
828
883
|
if (teams.size > 0 || !callbackServer) return;
|
|
829
884
|
callbackServer.close();
|
|
885
|
+
lifelineServer!.close();
|
|
830
886
|
callbackServer = undefined;
|
|
887
|
+
lifelineServer = undefined;
|
|
831
888
|
callbackReady = undefined;
|
|
832
889
|
callbackUrl = "";
|
|
833
890
|
}
|
|
834
891
|
|
|
892
|
+
/**
|
|
893
|
+
* Accepts one connection per Herdr pane teammate process. Its first line names the teammate and its process id, and its close is that process ending.
|
|
894
|
+
* A raw socket, because a Bun HTTP server does not report a client that died while its request was open.
|
|
895
|
+
*/
|
|
896
|
+
function acceptLifeline(socket: net.Socket): void {
|
|
897
|
+
socket.on("error", () => undefined);
|
|
898
|
+
socket.once("data", (hello: Buffer) => {
|
|
899
|
+
const { token, team: teamId, from, process: processId } = parseLifelineHello(hello);
|
|
900
|
+
const team = token === callbackToken ? teams.get(String(teamId)) : undefined;
|
|
901
|
+
const teammate = team?.members.get(String(from));
|
|
902
|
+
const record = teammate?.processRecord;
|
|
903
|
+
if (!team || !teammate || !record || record.id !== processId) {
|
|
904
|
+
socket.destroy();
|
|
905
|
+
return;
|
|
906
|
+
}
|
|
907
|
+
record.lifeline = socket;
|
|
908
|
+
socket.on("close", () => recordAbruptEnd(team, teammate, record));
|
|
909
|
+
});
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
/** Any local process can connect, so a hello that is not JSON names nobody. */
|
|
913
|
+
function parseLifelineHello(hello: Buffer): { token?: unknown; team?: unknown; from?: unknown; process?: unknown } {
|
|
914
|
+
try {
|
|
915
|
+
return JSON.parse(hello.toString("utf8")) as { token?: unknown; team?: unknown; from?: unknown; process?: unknown };
|
|
916
|
+
} catch {
|
|
917
|
+
return {};
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
function listenOnLoopback(server: http.Server | net.Server): Promise<number> {
|
|
922
|
+
return new Promise<number>((resolve, reject) => {
|
|
923
|
+
server.once("error", reject);
|
|
924
|
+
server.listen(0, "127.0.0.1", () => resolve((server.address() as net.AddressInfo).port));
|
|
925
|
+
});
|
|
926
|
+
}
|
|
927
|
+
|
|
835
928
|
async function ensureCallbackServer(): Promise<void> {
|
|
836
929
|
if (callbackReady) return callbackReady;
|
|
837
930
|
|
|
@@ -839,15 +932,11 @@ async function ensureCallbackServer(): Promise<void> {
|
|
|
839
932
|
void handleCallbackRequest(request, response);
|
|
840
933
|
});
|
|
841
934
|
callbackServer = server;
|
|
935
|
+
lifelineServer = net.createServer(acceptLifeline);
|
|
842
936
|
|
|
843
|
-
callbackReady =
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
const address = server.address();
|
|
847
|
-
if (!address || typeof address === "string") throw new Error("Team callback server did not get a port");
|
|
848
|
-
callbackUrl = `http://127.0.0.1:${address.port}/callback`;
|
|
849
|
-
resolve();
|
|
850
|
-
});
|
|
937
|
+
callbackReady = Promise.all([listenOnLoopback(server), listenOnLoopback(lifelineServer)]).then(([callbackPort, port]) => {
|
|
938
|
+
callbackUrl = `http://127.0.0.1:${callbackPort}/callback`;
|
|
939
|
+
lifelinePort = port;
|
|
851
940
|
});
|
|
852
941
|
return callbackReady;
|
|
853
942
|
}
|
|
@@ -918,12 +1007,8 @@ function handleChildEvent(team: TeamState, teammate: TeammateState, event: JsonR
|
|
|
918
1007
|
if (event.type === "session_shutdown") {
|
|
919
1008
|
teammate.alive = false;
|
|
920
1009
|
teammate.deliveryUrl = undefined;
|
|
921
|
-
if (event.reason === "quit") {
|
|
922
|
-
if (teammate.processRecord) teammate.processRecord.quitReported = true;
|
|
923
|
-
team.statuses.set(teammate.name, status("stopped", "Session shut down"));
|
|
924
|
-
appendTeamLog(team, { team: team.name, teammate: teammate.name, direction: "runtime", kind: "exit", summary: "session shut down", details: { reason: event.reason } });
|
|
925
|
-
}
|
|
926
1010
|
}
|
|
1011
|
+
if (event.type === "session_shutdown" && event.reason === "quit") recordQuit(team, teammate, event.signal);
|
|
927
1012
|
const logInput = normalizeChildEvent(team.name, teammate.name, event);
|
|
928
1013
|
if (logInput) appendTeamLog(team, logInput);
|
|
929
1014
|
if (["agent_start", "work_queued", "agent_settled", "session_shutdown"].includes(String(event.type))) persistActiveTeamManifest(team);
|
|
@@ -942,6 +1027,7 @@ async function handleCallbackRequest(request: http.IncomingMessage, response: ht
|
|
|
942
1027
|
const tool = String(body.tool);
|
|
943
1028
|
const args = (body.args ?? {}) as JsonRecord;
|
|
944
1029
|
const teammate = team.members.get(from);
|
|
1030
|
+
if (teammate && body.process !== teammate.processRecord?.id) throw new Error(`Teammate ${from} on team ${team.name} was restarted. This process is no longer that teammate.`);
|
|
945
1031
|
|
|
946
1032
|
if (tool === "register") {
|
|
947
1033
|
if (!teammate) throw new Error(`Unknown teammate: ${from}`);
|
|
@@ -966,9 +1052,9 @@ async function handleCallbackRequest(request: http.IncomingMessage, response: ht
|
|
|
966
1052
|
teammate.alive = true;
|
|
967
1053
|
teammate.active = false;
|
|
968
1054
|
team.statuses.set(teammate.name, status("idle", "Spawned"));
|
|
969
|
-
|
|
1055
|
+
teammate.processRecord!.registered = true;
|
|
970
1056
|
teammate.resolveReady?.();
|
|
971
|
-
writeJson(response, 200, { accepted: true, team: team.name, from });
|
|
1057
|
+
writeJson(response, 200, { accepted: true, team: team.name, from, ...(teammate.transport === "herdr" ? { lifelinePort } : {}) });
|
|
972
1058
|
return;
|
|
973
1059
|
}
|
|
974
1060
|
|