@awebai/oats-pi 0.70.1 → 0.70.2
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 +20 -0
- package/extension/failed-turn.mjs +14 -35
- package/extension/index.ts +8 -2
- package/extension/ui-prompt.mjs +30 -0
- package/extension/waiting-claim.mjs +274 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -27,6 +27,26 @@ from the same release tag). This bridge registers no operational tools. It only:
|
|
|
27
27
|
and recovering (`agent_settled`, pi 0.80.4 and later): a waiting claim
|
|
28
28
|
through `oats instance waiting`, producer `oats.pi`, cleared by the next run,
|
|
29
29
|
so the instance shows as needing input instead of idling unseen;
|
|
30
|
+
- reports a dialog an extension opens (`ctx.ui.select`, `confirm`, `input`,
|
|
31
|
+
`editor` and `custom`: a question tool's, say) for as long as it is open, in
|
|
32
|
+
pi's terminal UI and in RPC mode alike (`ui_prompt_start` and
|
|
33
|
+
`ui_prompt_end`, pi 0.84.4 and later): the same claim, producer `oats.pi`,
|
|
34
|
+
with reason `question` and the dialog's title as its text, cut to fit, or no
|
|
35
|
+
text for a dialog with no title. The instance shows as needing input, with
|
|
36
|
+
the question, and a scheduled wake holds its Enter instead of answering the
|
|
37
|
+
dialog. Closing the dialog clears the claim, and so does a session that ends
|
|
38
|
+
with it open, which waits for that write. An open dialog is shown over a
|
|
39
|
+
failed turn, which shows again once the dialog closes. Outside an OATS
|
|
40
|
+
instance nothing is reported. A screen of pi's own (its project trust
|
|
41
|
+
prompt, a picker a person opened) fires neither event and has no claim.
|
|
42
|
+
The bridge that sets the claim, a dialog's or a failed turn's, records a
|
|
43
|
+
mark while it stands, `<home>/.pi/oats-pi-claim.json` (`{pid, start, token,
|
|
44
|
+
reason}`), and clears only the claim its own mark stands for: a second pi in
|
|
45
|
+
the home (a nested one, a subagent's session) leaves a live pi's claim, and
|
|
46
|
+
never replaces its question. A question left by a pi that died with its
|
|
47
|
+
dialog open is cleared when the home's next pi starts; with no pi to start,
|
|
48
|
+
clear it with `oats instance waiting clear --producer oats.pi --home <home>`
|
|
49
|
+
([whose claim it is](../../docs/capabilities.md#oatscore-needs-input));
|
|
30
50
|
- journals compaction summaries and sends resume nudges when the active
|
|
31
51
|
knowledge capability created `STATE.md`/`log.md`. A startup gets the nudge
|
|
32
52
|
only when pi kept an earlier session of the home (pi files a session once
|
|
@@ -9,47 +9,29 @@
|
|
|
9
9
|
* and later) says pi will not go on, and a pi without it reports nothing. The last
|
|
10
10
|
* run decides: a retry that worked leaves nothing to report, and an abort is not an
|
|
11
11
|
* error, even one that cancels a retry's backoff, where no agent_end follows the
|
|
12
|
-
* error it was retrying. The next run clears the claim
|
|
13
|
-
*
|
|
14
|
-
*
|
|
12
|
+
* error it was retrying. The next run clears the claim, and a bridge's first run
|
|
13
|
+
* clears what nobody alive holds: what an earlier pi in the session left
|
|
14
|
+
* (waiting-claim.mjs). After that, a run with no claim to clear starts no process.
|
|
15
|
+
* A run's end reaches the claim too, failed or not: that is when a live pi finds a
|
|
16
|
+
* question a second pi left when it died inside the run (a nested one, a
|
|
17
|
+
* subagent's), which no later event of this pi would otherwise clear.
|
|
15
18
|
*/
|
|
16
|
-
import {
|
|
17
|
-
import { join } from "node:path";
|
|
19
|
+
import { claimMessage } from "./waiting-claim.mjs";
|
|
18
20
|
|
|
19
|
-
|
|
20
|
-
* (lib/refused-text.mjs REFUSED_TEXT), which this package cannot import before it
|
|
21
|
-
* has found the kernel. A claim the kernel refuses is a stuck instance nobody
|
|
22
|
-
* sees. A test pins the two equal. */
|
|
23
|
-
export const MESSAGE_REFUSED = /[\p{Cc}\u2028\u2029\u202A-\u202E\u2066-\u2069\u200B\u2060\uFEFF\u{E0000}-\u{E007F}]/gu;
|
|
24
|
-
/** The kernel's longest message, in code points (lib/instance-events.mjs WAITING_MESSAGE_MAX). */
|
|
25
|
-
const MESSAGE_MAX = 200;
|
|
21
|
+
export { MESSAGE_REFUSED } from "./waiting-claim.mjs";
|
|
26
22
|
|
|
27
23
|
/** The claim's message for a run's error: one the kernel accepts, whatever the provider said. */
|
|
28
24
|
export function failedTurnMessage(error) {
|
|
29
|
-
const said =
|
|
30
|
-
|
|
31
|
-
return points.length > MESSAGE_MAX ? `${points.slice(0, MESSAGE_MAX - 1).join("")}…` : points.join("");
|
|
25
|
+
const said = claimMessage(error);
|
|
26
|
+
return said ? claimMessage(`Turn failed: ${said}`) : "Turn failed";
|
|
32
27
|
}
|
|
33
28
|
|
|
34
|
-
/**
|
|
35
|
-
|
|
36
|
-
* still under way would land after its clear. A write is bounded by its timeout, and
|
|
37
|
-
* a failed one is dropped: reporting must never break a session. */
|
|
38
|
-
export function reportFailedTurn(pi, home) {
|
|
29
|
+
/** `claim`: the home's waiting claim (waiting-claim.mjs waitingClaim). */
|
|
30
|
+
export function reportFailedTurn(pi, claim) {
|
|
39
31
|
let failure;
|
|
40
|
-
let claimed = true;
|
|
41
|
-
let writes = Promise.resolve();
|
|
42
|
-
const waiting = (...args) => {
|
|
43
|
-
const argv = ["instance", "waiting", ...args, "--producer", "oats.pi", "--home", home, "--json"];
|
|
44
|
-
writes = writes.then(() => new Promise((done) => {
|
|
45
|
-
execFile(join(home, ".oats", "bin", "oats"), argv, { cwd: home, timeout: 5000 }, () => done());
|
|
46
|
-
}));
|
|
47
|
-
};
|
|
48
32
|
pi.on("agent_start", () => {
|
|
49
33
|
failure = undefined;
|
|
50
|
-
|
|
51
|
-
claimed = false;
|
|
52
|
-
waiting("clear");
|
|
34
|
+
claim.turnFailed(undefined);
|
|
53
35
|
});
|
|
54
36
|
pi.on("agent_end", (event) => {
|
|
55
37
|
const last = event.messages?.findLast((message) => message.role === "assistant");
|
|
@@ -58,9 +40,6 @@ export function reportFailedTurn(pi, home) {
|
|
|
58
40
|
pi.on("agent_settled", (event) => {
|
|
59
41
|
const reported = event.aborted ? undefined : failure;
|
|
60
42
|
failure = undefined;
|
|
61
|
-
|
|
62
|
-
claimed = true;
|
|
63
|
-
waiting("set", "--reason", "attention", `--message=${reported}`);
|
|
43
|
+
claim.turnFailed(reported);
|
|
64
44
|
});
|
|
65
|
-
pi.on("session_shutdown", () => writes);
|
|
66
45
|
}
|
package/extension/index.ts
CHANGED
|
@@ -4,11 +4,15 @@
|
|
|
4
4
|
* The kernel materializes every spawned instance's exact set in
|
|
5
5
|
* .agents/skills; this bridge contributes it inside an instance, plus the
|
|
6
6
|
* pre-workspace oats-getting-started bootstrap outside one, and drives the
|
|
7
|
-
* memory session events.
|
|
7
|
+
* memory session events. Inside an instance it also reports what the session
|
|
8
|
+
* waits on a person for (an open dialog, a turn that failed) as the home's
|
|
9
|
+
* waiting claim. Ambient skills coexist with the OATS-composed set.
|
|
8
10
|
*/
|
|
9
11
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
10
12
|
import { appendLogEntry, PACKAGED_SKILLS_DIR } from "./core-loader.mjs";
|
|
11
13
|
import { reportFailedTurn } from "./failed-turn.mjs";
|
|
14
|
+
import { reportUiPrompt } from "./ui-prompt.mjs";
|
|
15
|
+
import { waitingClaim } from "./waiting-claim.mjs";
|
|
12
16
|
import { closeSync, existsSync, openSync, readdirSync, readSync, statSync } from "node:fs";
|
|
13
17
|
import { join } from "node:path";
|
|
14
18
|
|
|
@@ -27,7 +31,9 @@ export default function (pi: ExtensionAPI) {
|
|
|
27
31
|
|
|
28
32
|
if (isInstance) {
|
|
29
33
|
holdOpeningTask(pi);
|
|
30
|
-
|
|
34
|
+
const claim = waitingClaim(pi, agentHome!);
|
|
35
|
+
reportFailedTurn(pi, claim);
|
|
36
|
+
reportUiPrompt(pi, claim);
|
|
31
37
|
|
|
32
38
|
pi.on("session_compact", async (event) => {
|
|
33
39
|
if (!existsSync(join(agentHome!, "STATE.md"))) return;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ui-prompt.mjs — a pi agent's question raises needs-input. pi has no question
|
|
3
|
+
* dialog of its own: every blocking one is an extension's (`ctx.ui.select`,
|
|
4
|
+
* `confirm`, `input`, `editor`, `custom`; a question tool's, say), and pi 0.84.4
|
|
5
|
+
* and later fire `ui_prompt_start` and `ui_prompt_end` around it, in its terminal
|
|
6
|
+
* UI and in RPC mode alike. The bridge holds a `question` claim between the two,
|
|
7
|
+
* as oats.core does for Claude Code's dialogs, so the instance shows as needing
|
|
8
|
+
* input and a scheduled wake holds its Enter. A pi before 0.84.4 fires neither
|
|
9
|
+
* and reports nothing.
|
|
10
|
+
*
|
|
11
|
+
* pi coalesces nested and overlapping dialogs into one span, and the claim's text
|
|
12
|
+
* is that span's title: the first dialog's, when it has one (`custom` has none).
|
|
13
|
+
* pi does not wait for an event's handlers before it sends the next (it queues a
|
|
14
|
+
* microtask each), so where an extension ahead of the bridge awaits in its start
|
|
15
|
+
* handler, a dialog answered at once can reach the bridge end first. The count
|
|
16
|
+
* keeps that pair from leaving a claim behind.
|
|
17
|
+
*/
|
|
18
|
+
import { claimMessage } from "./waiting-claim.mjs";
|
|
19
|
+
|
|
20
|
+
export function reportUiPrompt(pi, claim) {
|
|
21
|
+
let open = 0;
|
|
22
|
+
pi.on("ui_prompt_start", (event) => {
|
|
23
|
+
open += 1;
|
|
24
|
+
if (open > 0) claim.asked(claimMessage(event?.title));
|
|
25
|
+
});
|
|
26
|
+
pi.on("ui_prompt_end", () => {
|
|
27
|
+
open -= 1;
|
|
28
|
+
if (open <= 0) claim.asked(undefined);
|
|
29
|
+
});
|
|
30
|
+
}
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* waiting-claim.mjs — the bridge's waiting claim on its home: the kernel's own
|
|
3
|
+
* (`oats instance waiting`, producer `oats.pi`), which shows the instance as
|
|
4
|
+
* needing input and, with reason `question`, holds a scheduled wake's Enter.
|
|
5
|
+
*
|
|
6
|
+
* A producer holds one claim, and the bridge has two things to say: a dialog is
|
|
7
|
+
* open (ui-prompt.mjs) and the last turn failed (failed-turn.mjs). The open
|
|
8
|
+
* dialog is shown over the failed turn, because an Enter would answer it, and a
|
|
9
|
+
* dialog that closes shows the failed turn again while it still stands.
|
|
10
|
+
*
|
|
11
|
+
* More than one bridge can run in a home: a nested pi or a subagent's session
|
|
12
|
+
* carries the home's OATS_INSTANCE_HOME too, and a pi can die with its dialog
|
|
13
|
+
* open. So the bridge that sets the claim records a mark beside it, in pi's own
|
|
14
|
+
* project directory: `<home>/.pi/oats-pi-claim.json`, `{ pid, start, token,
|
|
15
|
+
* reason }`, the holder's process (its pid and start time, so a reused pid is
|
|
16
|
+
* not taken for it), this bridge (the token) and the claim's reason. A bridge
|
|
17
|
+
* clears only the claim its own mark stands for, by the mark and never by the
|
|
18
|
+
* claim's reason, and a holder that is alive keeps its claim: another bridge
|
|
19
|
+
* leaves it, except that a question replaces a live holder's failed turn. The
|
|
20
|
+
* mark is in the agent's own home and decides only claims the agent could set
|
|
21
|
+
* or clear itself.
|
|
22
|
+
*/
|
|
23
|
+
import { execFile, execFileSync } from "node:child_process";
|
|
24
|
+
import { randomUUID } from "node:crypto";
|
|
25
|
+
import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
26
|
+
import { join } from "node:path";
|
|
27
|
+
|
|
28
|
+
/** The characters the kernel refuses in a claim's message: a copy of its set
|
|
29
|
+
* (lib/refused-text.mjs REFUSED_TEXT), which this package cannot import before it
|
|
30
|
+
* has found the kernel. A claim the kernel refuses is a stuck instance nobody
|
|
31
|
+
* sees. A test pins the two equal. */
|
|
32
|
+
export const MESSAGE_REFUSED = /[\p{Cc}\u2028\u2029\u202A-\u202E\u2066-\u2069\u200B\u2060\uFEFF\u{E0000}-\u{E007F}]/gu;
|
|
33
|
+
/** The kernel's longest message, in code points (lib/instance-events.mjs WAITING_MESSAGE_MAX). */
|
|
34
|
+
const MESSAGE_MAX = 200;
|
|
35
|
+
|
|
36
|
+
/** One message the kernel accepts, whatever the text: one line, the refused
|
|
37
|
+
* characters replaced, cut to fit. "" for a text that says nothing. */
|
|
38
|
+
export function claimMessage(text) {
|
|
39
|
+
const line = typeof text === "string" ? text.replace(/\s+/gu, " ").trim().replace(MESSAGE_REFUSED, "\ufffd") : "";
|
|
40
|
+
const points = [...line];
|
|
41
|
+
return points.length > MESSAGE_MAX ? `${points.slice(0, MESSAGE_MAX - 1).join("")}…` : line;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Where a home's mark is. */
|
|
45
|
+
export const markPath = (home) => join(home, ".pi", "oats-pi-claim.json");
|
|
46
|
+
|
|
47
|
+
/** A Linux process's state letter and start time, from its stat (fields 3 and 22, counted
|
|
48
|
+
* after the command's closing parenthesis, which a command name cannot spoof), or null. */
|
|
49
|
+
function procStat(pid) {
|
|
50
|
+
try {
|
|
51
|
+
const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
|
|
52
|
+
const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
|
|
53
|
+
return fields[19] ? { state: fields[0], start: fields[19] } : null;
|
|
54
|
+
} catch { return null; }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** When a process started, as a string that is the same for every reader while it
|
|
58
|
+
* lives, or null where that cannot be read. Linux: the start time in its stat.
|
|
59
|
+
* Elsewhere: what `ps` prints for it. */
|
|
60
|
+
export function processStart(pid) {
|
|
61
|
+
const stat = procStat(pid);
|
|
62
|
+
if (stat) return stat.start;
|
|
63
|
+
try { return execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], { encoding: "utf8", timeout: 2000, stdio: ["ignore", "pipe", "ignore"] }).trim() || null; }
|
|
64
|
+
catch { return null; }
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Whether the process a mark names is still that process. One that cannot be told
|
|
68
|
+
* apart from it counts as alive: a live holder's claim taken for a dead one's would
|
|
69
|
+
* be cleared under an open dialog. A process that has exited and waits for its
|
|
70
|
+
* parent to reap it (Linux state Z, or X) is gone; where there is no /proc, such a
|
|
71
|
+
* one counts as alive until it is reaped. */
|
|
72
|
+
function holderAlive(mark) {
|
|
73
|
+
try { process.kill(mark.pid, 0); }
|
|
74
|
+
catch (error) { if (error?.code !== "EPERM") return false; }
|
|
75
|
+
const state = procStat(mark.pid)?.state;
|
|
76
|
+
if (state === "Z" || state === "X") return false;
|
|
77
|
+
const start = processStart(mark.pid);
|
|
78
|
+
return start === null || mark.start === null || start === mark.start;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** The home's mark, or null: none, or one that does not read as a mark. */
|
|
82
|
+
function readMark(home) {
|
|
83
|
+
try {
|
|
84
|
+
const mark = JSON.parse(readFileSync(markPath(home), "utf8"));
|
|
85
|
+
const valid = Number.isInteger(mark?.pid) && mark.pid > 0 && (mark.start === null || typeof mark.start === "string")
|
|
86
|
+
&& typeof mark.token === "string" && (mark.reason === "question" || mark.reason === "attention");
|
|
87
|
+
return valid ? mark : null;
|
|
88
|
+
} catch { return null; }
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** The home's claim: `asked(message)` while a dialog is open (a string, "" for one
|
|
92
|
+
* with no words) and `asked(undefined)` once it closed; `turnFailed(message)` for a
|
|
93
|
+
* turn that failed and `turnFailed(undefined)` once that is over.
|
|
94
|
+
*
|
|
95
|
+
* Each change is one step, and steps run one at a time, so a clear cannot pass the
|
|
96
|
+
* set it answers. A step shows what stands when it runs, so a dialog that opened and
|
|
97
|
+
* closed while an earlier write was under way starts no process. A step reads the
|
|
98
|
+
* mark, then:
|
|
99
|
+
* - to show a claim: writes its own mark, then the claim. A live holder's claim
|
|
100
|
+
* stays instead, unless this one is a question and that one a failed turn. A
|
|
101
|
+
* bridge so blocked looks again every second while it still has a claim to show,
|
|
102
|
+
* so a second pi's open dialog is claimed once the first pi's has closed.
|
|
103
|
+
* - to show none: clears the claim its own mark stands for, then removes the mark.
|
|
104
|
+
* Once a run has started, this bridge's first such step also clears what nobody
|
|
105
|
+
* alive holds: a mark whose holder is gone, or a claim with no mark (a bridge
|
|
106
|
+
* from before the mark left it, or a session that ended on a failed turn). A
|
|
107
|
+
* session that starts and ends with no run clears no leftover. After that, a
|
|
108
|
+
* step with no claim to clear starts no process, and only reads the mark: it
|
|
109
|
+
* clears the question of a holder that is gone, a second pi that died with its
|
|
110
|
+
* dialog open while this one lives.
|
|
111
|
+
* - when its session starts (`session_start`): clears only the question of a holder
|
|
112
|
+
* that is gone, a pi that died with its dialog open. A failed turn waits for the
|
|
113
|
+
* next run, as before.
|
|
114
|
+
*
|
|
115
|
+
* A session that ends closes its dialog and waits for its steps: a /reload's next
|
|
116
|
+
* bridge starts its own, a set still under way would land after its clear, and a pi
|
|
117
|
+
* that exits would leave a dialog's claim behind. A failed turn's claim outlives the
|
|
118
|
+
* session, as before, and gives up its mark, so the next bridge's first run clears
|
|
119
|
+
* it. A write is bounded by its timeout. A set the kernel did not take is dropped,
|
|
120
|
+
* as is a mark that cannot be written; a clear it did not take keeps the mark and is
|
|
121
|
+
* tried again at the bridge's next step, and a question's by itself too, at growing
|
|
122
|
+
* waits, because a question left standing holds every wake. Reporting must never
|
|
123
|
+
* break a session.
|
|
124
|
+
*
|
|
125
|
+
* Two bridges are not fenced against each other: a step reads the mark and then
|
|
126
|
+
* writes, so a clear that read "nobody alive holds it" can land after another pi's
|
|
127
|
+
* set, and that pi's dialog then has no claim until it closes. The window is the
|
|
128
|
+
* two kernel calls' jitter. A failed turn that another pi's question replaced is
|
|
129
|
+
* not shown again when that dialog closes: its bridge learns of it only at its
|
|
130
|
+
* next step. A dialog that opens before this bridge's first run takes a leftover
|
|
131
|
+
* failed turn with it, for the same reason: the question replaces the producer's
|
|
132
|
+
* one claim, and this bridge has no failed turn of its own to show again. */
|
|
133
|
+
/** How often a bridge whose claim a live holder blocks looks again, in ms. */
|
|
134
|
+
const BLOCKED_RETRY_MS = 1000;
|
|
135
|
+
/** The longest wait before a question's clear the kernel did not take is tried again, in ms: the
|
|
136
|
+
* wait starts at BLOCKED_RETRY_MS and doubles, so a kernel that keeps failing costs a process a
|
|
137
|
+
* minute, not one a second. */
|
|
138
|
+
const CLEAR_RETRY_MAX_MS = 60000;
|
|
139
|
+
/** The tokens of this process's bridges whose session has not ended, shared by every copy of this
|
|
140
|
+
* module pi loads (a /reload and a session replacement load it again in the same process). A mark
|
|
141
|
+
* of this process whose token is not here is an ended bridge's: nobody's. */
|
|
142
|
+
const LIVE_BRIDGES = (globalThis[Symbol.for("@awebai/oats-pi/waiting-claim/live-bridges")] ??= new Set());
|
|
143
|
+
|
|
144
|
+
export function waitingClaim(pi, home) {
|
|
145
|
+
const self = { pid: process.pid, start: processStart(process.pid), token: randomUUID() };
|
|
146
|
+
const mine = (mark) => mark !== null && mark.pid === self.pid && mark.token === self.token;
|
|
147
|
+
/** Whether a mark's holder is alive: another process that is (holderAlive), or a bridge of this
|
|
148
|
+
* process whose session has not ended. */
|
|
149
|
+
const alive = (mark) => mark.pid === self.pid && mark.start === self.start ? LIVE_BRIDGES.has(mark.token) : holderAlive(mark);
|
|
150
|
+
LIVE_BRIDGES.add(self.token);
|
|
151
|
+
let question;
|
|
152
|
+
let failure;
|
|
153
|
+
// What this bridge's claim says, "" for none; undefined until its first step.
|
|
154
|
+
let shown;
|
|
155
|
+
let steps = Promise.resolve();
|
|
156
|
+
// The timer of this bridge's next look (blocked by a live holder, or after a question's clear the
|
|
157
|
+
// kernel did not take), how many such clears in a row, and whether the session has ended (no
|
|
158
|
+
// look after).
|
|
159
|
+
let retry;
|
|
160
|
+
let refused = 0;
|
|
161
|
+
let ended = false;
|
|
162
|
+
// Whether a run has started or ended in this bridge's time: only then is a leftover its to clear.
|
|
163
|
+
let ran = false;
|
|
164
|
+
|
|
165
|
+
/** One kernel call. Whether the kernel took it: false for a refusal, a failure and the timeout. */
|
|
166
|
+
const waiting = (...args) => new Promise((done) => {
|
|
167
|
+
const argv = ["instance", "waiting", ...args, "--producer", "oats.pi", "--home", home, "--json"];
|
|
168
|
+
execFile(join(home, ".oats", "bin", "oats"), argv, { cwd: home, timeout: 5000 }, (error) => done(!error));
|
|
169
|
+
});
|
|
170
|
+
/** Remove a file of the mark's. One that stays is harmless: a mark reads as its holder's while that
|
|
171
|
+
* lives and as nobody's after, and a draft is never read. */
|
|
172
|
+
const drop = (path) => {
|
|
173
|
+
try { rmSync(path, { force: true }); }
|
|
174
|
+
catch { /* left where it is */ }
|
|
175
|
+
};
|
|
176
|
+
const writeMark = (reason) => {
|
|
177
|
+
const path = markPath(home), draft = `${path}.${self.pid}.${self.token}`;
|
|
178
|
+
try {
|
|
179
|
+
mkdirSync(join(home, ".pi"), { recursive: true });
|
|
180
|
+
writeFileSync(draft, `${JSON.stringify({ ...self, reason })}\n`);
|
|
181
|
+
renameSync(draft, path);
|
|
182
|
+
} catch { drop(draft); }
|
|
183
|
+
};
|
|
184
|
+
const removeMark = () => drop(markPath(home));
|
|
185
|
+
/** Clear the claim, then remove the mark, unless a live holder wrote its own meanwhile. False when
|
|
186
|
+
* the kernel did not take the clear: the claim may stand, so the mark stays, for a later try by
|
|
187
|
+
* this bridge or, once this pi is gone, by the home's next one. */
|
|
188
|
+
const clearClaim = async () => {
|
|
189
|
+
if (!(await waiting("clear"))) return false;
|
|
190
|
+
const left = readMark(home);
|
|
191
|
+
if (left === null || mine(left) || !alive(left)) removeMark();
|
|
192
|
+
return true;
|
|
193
|
+
};
|
|
194
|
+
/** One step after the others. A step that throws is dropped: reporting must never break a session. */
|
|
195
|
+
const then = (run) => { steps = steps.then(run).catch(() => undefined); };
|
|
196
|
+
|
|
197
|
+
const wanted = () => question !== undefined ? ["question", question] : failure !== undefined ? ["attention", failure] : [];
|
|
198
|
+
/** Take the next step by itself after a wait, unless the session has ended. Any step cancels it. */
|
|
199
|
+
const lookAgain = (ms) => {
|
|
200
|
+
if (ended) return;
|
|
201
|
+
retry = setTimeout(() => change(), ms);
|
|
202
|
+
retry.unref?.();
|
|
203
|
+
};
|
|
204
|
+
/** Clear the question of a holder that is gone: a pi that died with its dialog open. */
|
|
205
|
+
const clearDeadQuestion = async () => {
|
|
206
|
+
const mark = readMark(home);
|
|
207
|
+
if (mark === null || mark.reason !== "question" || mine(mark) || alive(mark)) return;
|
|
208
|
+
await clearClaim();
|
|
209
|
+
};
|
|
210
|
+
const step = async () => {
|
|
211
|
+
clearTimeout(retry);
|
|
212
|
+
const [reason, message] = wanted();
|
|
213
|
+
const next = reason === undefined ? "" : `${reason} ${message}`;
|
|
214
|
+
if (next === shown) {
|
|
215
|
+
// Nothing to show and nothing shown: a look at the mark, for a second pi's question that
|
|
216
|
+
// outlived it. A run's start and its end come here, so a live pi clears it by the end of a
|
|
217
|
+
// run: a nested pi dies inside the run, after the start's look.
|
|
218
|
+
if (next === "") await clearDeadQuestion();
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
const first = shown === undefined;
|
|
222
|
+
const mark = readMark(home);
|
|
223
|
+
const other = mark !== null && !mine(mark) && alive(mark) ? mark : null;
|
|
224
|
+
if (reason === undefined) {
|
|
225
|
+
// Nothing of its own yet, and what an earlier pi left waits for a run.
|
|
226
|
+
if (first && !ran) return;
|
|
227
|
+
// Its own claim, or on its first run a leftover, unless a live holder has the claim. A clear
|
|
228
|
+
// the kernel did not take is tried again at this bridge's next step, and a question's by
|
|
229
|
+
// itself too, at growing waits: left standing in a quiet session, it would hold the very wake
|
|
230
|
+
// that session waits for.
|
|
231
|
+
const before = shown;
|
|
232
|
+
shown = "";
|
|
233
|
+
if (other !== null) return;
|
|
234
|
+
if (await clearClaim()) { refused = 0; return; }
|
|
235
|
+
shown = before;
|
|
236
|
+
if (before?.startsWith("question ")) lookAgain(Math.min(CLEAR_RETRY_MAX_MS, BLOCKED_RETRY_MS * 2 ** refused++));
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
if (other !== null && !(reason === "question" && other.reason === "attention")) {
|
|
240
|
+
// The holder's claim stays, and this bridge shows none. Blocked on its first step, it has
|
|
241
|
+
// yet to look for a leftover.
|
|
242
|
+
shown = first ? undefined : "";
|
|
243
|
+
lookAgain(BLOCKED_RETRY_MS);
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
shown = next;
|
|
247
|
+
writeMark(reason);
|
|
248
|
+
await waiting("set", "--reason", reason, ...(message ? [`--message=${message}`] : []));
|
|
249
|
+
};
|
|
250
|
+
const change = () => then(step);
|
|
251
|
+
|
|
252
|
+
pi.on("session_start", () => {
|
|
253
|
+
ended = false;
|
|
254
|
+
LIVE_BRIDGES.add(self.token);
|
|
255
|
+
then(clearDeadQuestion);
|
|
256
|
+
});
|
|
257
|
+
pi.on("session_shutdown", () => {
|
|
258
|
+
ended = true;
|
|
259
|
+
question = undefined;
|
|
260
|
+
change();
|
|
261
|
+
// A failed turn's claim outlives the session and gives up its mark. A question whose clear the
|
|
262
|
+
// kernel did not take keeps its mark, and this bridge is live no more: the next bridge of this
|
|
263
|
+
// process, or the home's next pi, clears it as it starts.
|
|
264
|
+
then(() => {
|
|
265
|
+
if (shown?.startsWith("attention ") && mine(readMark(home))) removeMark();
|
|
266
|
+
LIVE_BRIDGES.delete(self.token);
|
|
267
|
+
});
|
|
268
|
+
return steps;
|
|
269
|
+
});
|
|
270
|
+
return {
|
|
271
|
+
asked(message) { question = message; change(); },
|
|
272
|
+
turnFailed(message) { ran = true; failure = message; change(); },
|
|
273
|
+
};
|
|
274
|
+
}
|
package/package.json
CHANGED