@staix/agent-hub 0.35.0 → 0.37.0
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/CHANGELOG.md +43 -0
- package/README.md +25 -4
- package/THIRD_PARTY_NOTICES.md +0 -18
- package/docs/agent-notes/README.md +71 -1
- package/docs/agent-notes/adapters.md +5 -2
- package/docs/agent-notes/bus.md +1 -0
- package/docs/agent-notes/daemon.md +7 -6
- package/docs/agent-notes/local-worker.md +1 -0
- package/docs/agent-notes/models.md +5 -3
- package/docs/agent-notes/tasks.md +9 -2
- package/docs/agent-notes/tests.md +1 -1
- package/docs/contracts/companion-cli-v1.json +70 -0
- package/docs/design/adapters.md +115 -2
- package/docs/design/agent-hub-architecture.md +10 -2
- package/docs/design/bus.md +8 -0
- package/docs/design/execution-reference.md +171 -11
- package/docs/design/guidance-experiments.md +438 -0
- package/docs/design/guidance-probes.md +802 -0
- package/docs/design/model-routes.md +1053 -0
- package/docs/design/supervision.md +121 -0
- package/docs/design/task-board.md +111 -0
- package/docs/dogfood.md +24 -15
- package/docs/events.md +20 -1
- package/docs/memory.md +3 -3
- package/docs/operations.md +366 -133
- package/docs/profiles.md +2 -2
- package/docs/quickstart.md +114 -3
- package/docs/research.md +5 -3
- package/docs/sdlc.md +113 -7
- package/docs/security.md +88 -6
- package/docs/specs/2026-09-19-agent-hub-design.md +14 -11
- package/docs/specs/2026-10-04-switchyard-source-port-design.md +3 -1
- package/docs/verification/2026-10-25-qwen-dual-output-t0.md +22 -0
- package/docs/verification/2026-11-08-qwen-0269-model-setter-1317.md +25 -11
- package/docs/verification/2026-11-09-qwen-0270-acp.md +181 -0
- package/docs/verification/2026-11-09-qwen-0270-model-setter-1317.md +61 -0
- package/docs/verification/2026-11-10-0.36.0.md +59 -0
- package/docs/verification/2026-11-10-claude-implementer-2.1.322.md +59 -0
- package/docs/verification/2026-11-10-qwen-0270-dual-output.md +367 -0
- package/docs/verification/2026-11-10-qwen-0271-dual-output.md +101 -0
- package/docs/verification/2026-11-11-0.37.0.md +40 -0
- package/docs/verification/2026-11-11-guidance-probe-t2-1226.md +153 -0
- package/docs/verification/2026-11-11-qwen-setter-suggestions-off.md +167 -0
- package/docs/verification/claude-shell-wrapper-native.py +1 -1
- package/docs/verified.json +27 -27
- package/package.json +3 -4
- package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
- package/plugins/agent-hub/kimi-hook.js +3570 -1800
- package/plugins/agent-hub/server.js +4112 -1913
- package/src/adapters/channel-peer.ts +7 -1
- package/src/adapters/claude-channel.ts +7 -4
- package/src/adapters/compat.ts +10 -10
- package/src/adapters/local-probe.ts +174 -0
- package/src/adapters/local-worker.ts +233 -22
- package/src/adapters/qwen-dual.ts +324 -44
- package/src/cli/console-state.ts +25 -6
- package/src/cli/console-versions.ts +99 -0
- package/src/cli/console.ts +13 -1
- package/src/cli/guidance.ts +67 -0
- package/src/cli/help.ts +12 -4
- package/src/cli/identity.ts +10 -3
- package/src/cli/init-prompt.ts +15 -2
- package/src/cli/init-required-checks.ts +122 -0
- package/src/cli/init-settings.ts +10 -4
- package/src/cli/init.ts +39 -3
- package/src/cli/install-paths.ts +7 -2
- package/src/cli/lineage.ts +78 -0
- package/src/cli/main.ts +171 -14
- package/src/cli/runtime-version-warning.ts +2 -2
- package/src/cli/sdlc-output.ts +9 -5
- package/src/cli/setup-research.ts +10 -0
- package/src/hub/autonomy-defaults.ts +20 -9
- package/src/hub/board.ts +346 -4
- package/src/hub/build-entry.ts +11 -0
- package/src/hub/bus.ts +12 -0
- package/src/hub/ci-watch.ts +4 -4
- package/src/hub/config-apply.ts +6 -3
- package/src/hub/config-trust.ts +7 -1
- package/src/hub/control-client.ts +5 -2
- package/src/hub/daemon.ts +508 -26
- package/src/hub/delivery-hints.ts +4 -2
- package/src/hub/delivery-journal.ts +50 -2
- package/src/hub/delivery-public.ts +51 -0
- package/src/hub/dogfood-profile.ts +8 -4
- package/src/hub/events.ts +3 -2
- package/src/hub/execution-lineage-owner.ts +272 -0
- package/src/hub/execution-lineage.ts +52 -8
- package/src/hub/execution-links.ts +85 -0
- package/src/hub/guidance-probe-store.ts +713 -0
- package/src/hub/guidance-probes.ts +358 -0
- package/src/hub/guidance-variants.ts +398 -0
- package/src/hub/handoff.ts +1 -0
- package/src/hub/hub-tools.ts +43 -2
- package/src/hub/inference.ts +18 -5
- package/src/hub/manager.ts +44 -2
- package/src/hub/memory-policy.ts +2 -2
- package/src/hub/operational-authority.ts +13 -1
- package/src/hub/peers.ts +6 -1
- package/src/hub/planning.ts +1 -1
- package/src/hub/ports.ts +1 -1
- package/src/hub/progress.ts +47 -23
- package/src/hub/report.ts +2 -0
- package/src/hub/research.ts +1 -0
- package/src/hub/restart.ts +20 -0
- package/src/hub/roles.ts +26 -0
- package/src/hub/routing.ts +4 -1
- package/src/hub/sdlc-merge.ts +39 -1
- package/src/hub/sdlc-release-authorization.ts +139 -17
- package/src/hub/sdlc-release-policy.ts +100 -0
- package/src/hub/sdlc-release.ts +60 -8
- package/src/hub/sdlc.ts +62 -11
- package/src/hub/settings.ts +2 -0
- package/src/hub/supervision-proposals.ts +405 -0
- package/src/hub/supervision-rules.ts +388 -0
- package/src/hub/supervision.ts +2 -0
- package/src/hub/task-approval.ts +2 -2
- package/src/hub/task-repository.ts +5 -0
- package/src/hub/tasks.ts +917 -53
- package/src/local/probe-errors.ts +28 -0
- package/src/local/probe-sandbox.ts +224 -0
- package/src/local/probe-types.ts +108 -0
- package/src/local/probe-workspace.ts +237 -0
- package/src/local/sandbox.ts +71 -2
- package/src/local/tools.ts +135 -9
- package/src/memory/capture.ts +2 -2
- package/src/models/relay.ts +9 -2
- package/src/models/route/advisor-trigger.ts +88 -0
- package/src/models/route/config.ts +39 -8
- package/src/models/route/conversation-view.ts +179 -0
- package/src/models/route/decision-evidence.ts +1 -1
- package/src/models/route/decision.ts +193 -26
- package/src/models/route/escalation-control.ts +30 -0
- package/src/models/route/hub-prompts.ts +97 -0
- package/src/models/route/judge-choice.ts +155 -0
- package/src/models/route/judge-replies.ts +102 -0
- package/src/models/route/labels.ts +14 -70
- package/src/models/route/observation-signals.ts +250 -0
- package/src/models/route/plan-execute-choice.ts +27 -0
- package/src/models/route/relay-selector.ts +10 -9
- package/src/models/route/runtime.ts +129 -60
- package/src/models/route/stage-diagnostics.ts +22 -0
- package/src/models/route/stage-evidence.ts +55 -0
- package/src/models/route/stage-fallback.ts +58 -0
- package/src/models/route/stage-input.ts +155 -0
- package/src/models/route/stage.ts +5 -147
- package/src/models/route/turn-state.ts +77 -0
- package/src/omniroute/client.ts +3 -0
- package/src/ui/guidance-panel.ts +156 -0
- package/src/ui/guidance-view.ts +43 -0
- package/src/ui/lineage-view.ts +34 -0
- package/src/ui/plugin.ts +141 -27
- package/src/version.ts +4 -0
- package/templates/adec/README.md +32 -0
- package/templates/adec/ahub.plan-execute.json +23 -0
- package/templates/adec/ahub.stage.json +23 -0
- package/LICENSES/Apache-2.0.txt +0 -204
- package/src/models/route/advisor.ts +0 -102
- package/src/models/route/escalation.ts +0 -82
- package/src/models/route/judge.ts +0 -23
- package/src/models/route/normalize.ts +0 -103
- package/src/models/route/plan-execute.ts +0 -52
- package/src/models/route/prompts.ts +0 -8
- package/src/models/route/signals.ts +0 -247
- package/src/models/route/state.ts +0 -54
- package/src/models/route/text.ts +0 -61
|
@@ -15,7 +15,7 @@ import type { PermissionRequest } from "./acp.ts";
|
|
|
15
15
|
* `submit` and `confirmation_response` lines to the input file and tails the event file.
|
|
16
16
|
*
|
|
17
17
|
* Two limits, by design (spec: "Qwen dual-output TUI amendment"):
|
|
18
|
-
* 1. A hub deny
|
|
18
|
+
* 1. A hub deny has a known disposition but supplies no native completion signal: keep later inputs fenced until a new personal turn completes or a verified fresh generation starts.
|
|
19
19
|
* 2. The input protocol cannot stop a turn and SIGINT does not either: the watchdog never cancels. It marks the turn stalled, and the
|
|
20
20
|
* person presses Esc in the Qwen terminal. The hub never types into the terminal and never signals the process to stop a turn.
|
|
21
21
|
*/
|
|
@@ -37,6 +37,10 @@ export interface QwenDualOptions {
|
|
|
37
37
|
pollMs?: number;
|
|
38
38
|
/** How often the owner process is checked (ms). */
|
|
39
39
|
ownerMs?: number;
|
|
40
|
+
/** Absolute wait after a deny, never an idle inference. Expiry retains the durable input fence. */
|
|
41
|
+
denyQuiescenceMs?: number;
|
|
42
|
+
/** Host-only fault seam. Never supplied by native event data or configuration. */
|
|
43
|
+
writeInput?: (fd: number, bytes: Buffer) => number;
|
|
40
44
|
preamble?: string;
|
|
41
45
|
/** The hub's own tools by exact `mcp__<server>__<tool>` name, never by prefix. */
|
|
42
46
|
autoApprove?: (toolName: string) => boolean;
|
|
@@ -58,15 +62,22 @@ export interface QwenDualOptions {
|
|
|
58
62
|
const SUBMIT_CAP = 256 * 1024;
|
|
59
63
|
const READ_CAP = 1024 * 1024;
|
|
60
64
|
const ANSWERED_CAP = 256;
|
|
65
|
+
export const QWEN_DENY_QUIESCENCE_MS = 30_000;
|
|
66
|
+
export const QWEN_DENY_QUIESCENCE_NOTE = "Qwen gave no signal that the denied turn ended; queued messages remain unsubmitted. Type a new prompt or press Esc in the Qwen terminal, then complete a personal turn; or end that terminal and run ahub qwen --mode tui";
|
|
67
|
+
export const QWEN_DENY_STORAGE_NOTE = "the hub could not persist Qwen's input fence state; queued messages remain unsubmitted. Check the Qwen state directory's storage and permissions before completing a new personal turn or restarting Qwen with ahub qwen --mode tui";
|
|
68
|
+
export const QWEN_INPUT_UNCERTAIN_NOTE = "Qwen's input file has an incomplete or unconfirmed record; queued messages remain unsubmitted. Inspect and end Qwen in its terminal, then run ahub qwen --mode tui to start a verified fresh generation";
|
|
61
69
|
/** What the console, status and dashboard say while a turn is stalled. */
|
|
62
70
|
export const QWEN_STALLED_NOTE = "stalled: Qwen has said nothing for a while; the hub cannot stop a Qwen turn, press Esc in the Qwen terminal";
|
|
63
71
|
/** Shown while the hub cannot read the event file: the Qwen TUI itself keeps working, so this is never idle. */
|
|
64
72
|
export const QWEN_DETACHED_NOTE = "detached: the hub cannot read Qwen's event file; Qwen keeps working in its terminal and the hub reattaches when the file is readable again";
|
|
65
73
|
const DIR = "qwen-dual";
|
|
66
74
|
|
|
67
|
-
type StateFile = { v: 1; sessionId?: string; offset: number; generation: number; ownerPid?: number; ownerSignature?: string };
|
|
75
|
+
type StateFile = { v: 1; sessionId?: string; offset: number; generation: number; ownerPid?: number; ownerSignature?: string; denyPending?: true };
|
|
68
76
|
interface Turn { envs: Envelope[]; deliveryId?: string; text: string; started: boolean; accepted: boolean }
|
|
69
77
|
type Json = Record<string, any>;
|
|
78
|
+
class QwenInputUncertain extends Error {
|
|
79
|
+
constructor() { super(QWEN_INPUT_UNCERTAIN_NOTE); }
|
|
80
|
+
}
|
|
70
81
|
|
|
71
82
|
/** Whether a Qwen tool request names the hub's state dir: the input file is a prompt channel, so a write or command that reaches it is refused. */
|
|
72
83
|
export function qwenDualNamesStateDir(input: unknown, stateDir: string): boolean {
|
|
@@ -135,6 +146,23 @@ export class QwenDualPeer extends BasePeer {
|
|
|
135
146
|
private pollFailures = 0;
|
|
136
147
|
/** Inside an event line longer than READ_CAP: its rest is dropped through the next newline. */
|
|
137
148
|
private discarding = false;
|
|
149
|
+
private denyTimer?: ReturnType<typeof setTimeout>;
|
|
150
|
+
private denyCursor = 0;
|
|
151
|
+
private eventCursor = 0;
|
|
152
|
+
private eventStart = 0;
|
|
153
|
+
private freshFenceOwner?: string;
|
|
154
|
+
private personalProof?: { generation: number; session: string; owner: string; assistant: boolean };
|
|
155
|
+
private readCompletion?: { kind: "personal" | "fresh"; generation: number; session: string; owner: string; source: string; personal?: object };
|
|
156
|
+
private freshCompletionAllowed = false;
|
|
157
|
+
private freshRead?: { generation: number; source: string; session?: string; activity: boolean };
|
|
158
|
+
private freshEventIdentity?: string;
|
|
159
|
+
private polling = false;
|
|
160
|
+
private fenceFile?: string;
|
|
161
|
+
private denyStorageFailure = false;
|
|
162
|
+
private inputBlocked = false;
|
|
163
|
+
private freshInputPending = false;
|
|
164
|
+
private freshBaselineAbsent = false;
|
|
165
|
+
private freshEventReady = false;
|
|
138
166
|
|
|
139
167
|
constructor(id: PeerId, private readonly opts: QwenDualOptions) {
|
|
140
168
|
super(id, opts.watchdogMs);
|
|
@@ -149,7 +177,9 @@ export class QwenDualPeer extends BasePeer {
|
|
|
149
177
|
get adopted(): boolean { return this.adopting; }
|
|
150
178
|
private adopting = false;
|
|
151
179
|
get stalled(): boolean { return this.stalled_; }
|
|
152
|
-
get statusNotice(): { code: "qwen-stalled" | "qwen-detached"; message: string } | undefined {
|
|
180
|
+
get statusNotice(): { code: "qwen-stalled" | "qwen-detached" | "qwen-deny-quiescence"; message: string } | undefined {
|
|
181
|
+
if (this.inputBlocked || this.freshInputPending) return { code: "qwen-deny-quiescence", message: QWEN_INPUT_UNCERTAIN_NOTE };
|
|
182
|
+
if (this.state_.denyPending) return { code: "qwen-deny-quiescence", message: this.denyStorageFailure ? QWEN_DENY_STORAGE_NOTE : QWEN_DENY_QUIESCENCE_NOTE };
|
|
153
183
|
if (this.detached) return { code: "qwen-detached", message: QWEN_DETACHED_NOTE };
|
|
154
184
|
return this.stalled_ ? { code: "qwen-stalled", message: QWEN_STALLED_NOTE } : undefined;
|
|
155
185
|
}
|
|
@@ -185,18 +215,22 @@ export class QwenDualPeer extends BasePeer {
|
|
|
185
215
|
if (!info.isFile() || info.size > 4096) return;
|
|
186
216
|
const buffer = Buffer.alloc(info.size); readSync(fd, buffer, 0, info.size, 0);
|
|
187
217
|
const raw = JSON.parse(buffer.toString("utf8")) as Partial<StateFile>;
|
|
218
|
+
if (Object.hasOwn(raw, "denyPending")) this.state_.denyPending = true;
|
|
188
219
|
if (raw.v !== 1 || !Number.isSafeInteger(raw.offset) || raw.offset! < 0 || !Number.isSafeInteger(raw.generation)) return;
|
|
189
220
|
this.state_ = { v: 1, offset: raw.offset!, generation: raw.generation!,
|
|
190
221
|
...(qwenSessionId(raw.sessionId) ? { sessionId: raw.sessionId } : {}),
|
|
191
|
-
...(Number.isSafeInteger(raw.ownerPid) && typeof raw.ownerSignature === "string" ? { ownerPid: raw.ownerPid, ownerSignature: raw.ownerSignature } : {})
|
|
222
|
+
...(Number.isSafeInteger(raw.ownerPid) && typeof raw.ownerSignature === "string" ? { ownerPid: raw.ownerPid, ownerSignature: raw.ownerSignature } : {}),
|
|
223
|
+
// Unknown/malformed fence metadata never grants readiness. Only the literal true is written by this host.
|
|
224
|
+
...(Object.hasOwn(raw, "denyPending") ? { denyPending: true as const } : {}) };
|
|
192
225
|
} catch { /* no usable record: a fresh launch */ }
|
|
193
226
|
finally { if (fd !== undefined) try { closeSync(fd); } catch { /* nothing to close */ } }
|
|
194
227
|
}
|
|
195
228
|
|
|
196
|
-
private saveState():
|
|
229
|
+
private saveState(): boolean {
|
|
197
230
|
const temp = `${this.stateFile}.${process.pid}.tmp`;
|
|
198
|
-
try { writeFileSync(temp, `${JSON.stringify(this.state_)}\n`, { mode: 0o600 }); renameSync(temp, this.stateFile); }
|
|
199
|
-
catch { this.opts.log?.(`[${this.id}] could not record its Qwen read position`); }
|
|
231
|
+
try { writeFileSync(temp, `${JSON.stringify(this.state_)}\n`, { mode: 0o600 }); renameSync(temp, this.stateFile); return true; }
|
|
232
|
+
catch { try { this.opts.log?.(`[${this.id}] could not record its Qwen read position`); } catch { /* advisory failure never changes the checked write result */ } }
|
|
233
|
+
return false;
|
|
200
234
|
}
|
|
201
235
|
|
|
202
236
|
private ownerAlive(): boolean {
|
|
@@ -209,8 +243,10 @@ export class QwenDualPeer extends BasePeer {
|
|
|
209
243
|
mkdirSync(this.dir, { recursive: true, mode: 0o700 });
|
|
210
244
|
const dir = lstatSync(this.dir);
|
|
211
245
|
if (!dir.isDirectory() || dir.isSymbolicLink() || (typeof process.getuid === "function" && dir.uid !== process.getuid()) || (dir.mode & 0o077) !== 0) throw new Error("Qwen dual-output directory is not private to the person running the hub");
|
|
246
|
+
this._launch = undefined;
|
|
212
247
|
this.loadState();
|
|
213
248
|
for (const path of [this.inputFile, this.eventFile]) this.ensureFile(path, true);
|
|
249
|
+
this.checkInputTail();
|
|
214
250
|
this.stopping = false; this.exited = false;
|
|
215
251
|
if (this.ownerAlive()) {
|
|
216
252
|
// The hub restarted while the person's Qwen kept running: read on from the saved offset. No event is processed twice and no launch happens.
|
|
@@ -221,27 +257,80 @@ export class QwenDualPeer extends BasePeer {
|
|
|
221
257
|
// ponytail: a Qwen turn that was running when the hub went away is not known here, so the adopted peer reads idle until the next event says otherwise.
|
|
222
258
|
// Upgrade: record the open hub turn in state.json and settle it on adoption.
|
|
223
259
|
this.sessionSeen = this.state_.sessionId !== undefined; this.primed = true;
|
|
260
|
+
if (this.state_.denyPending || this.freshInputPending) { this.denyCursor = size; }
|
|
224
261
|
this.saveState();
|
|
225
262
|
} else {
|
|
226
263
|
// A fresh or resumed launch. Qwen opens an existing event file without truncating or appending, so it would overwrite it from byte 0: start from empty files.
|
|
227
264
|
this.adopting = false;
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
this.
|
|
235
|
-
|
|
236
|
-
|
|
265
|
+
const fenced = this.state_.denyPending || this.inputBlocked || this.freshInputPending;
|
|
266
|
+
if (fenced) {
|
|
267
|
+
const rows = (this.opts.table ?? processTable)();
|
|
268
|
+
const flag = `--input-file ${this.inputFile}`;
|
|
269
|
+
this.freshBaselineAbsent = rows !== undefined && !rows.some(row => row.pid !== process.pid && row.command.includes(flag));
|
|
270
|
+
}
|
|
271
|
+
if (fenced && !this.freshBaselineAbsent) {
|
|
272
|
+
// No file rotation/truncation or launcher may overlap an unverified existing native owner.
|
|
273
|
+
this.sessionSeen = this.state_.sessionId !== undefined; this.primed = true;
|
|
274
|
+
this.denyCursor = lstatSync(this.eventFile).size;
|
|
275
|
+
this.setState("offline");
|
|
276
|
+
try { this.opts.onNotice?.(`${this.id}: the hub could not verify that the old Qwen terminal is absent; inspect and end that terminal before running ahub qwen --mode tui again`); } catch { /* already offline */ }
|
|
277
|
+
} else {
|
|
278
|
+
this.resume = this.opts.sessionId !== undefined || this.state_.sessionId !== undefined;
|
|
279
|
+
const resumeId = this.opts.sessionId ?? this.state_.sessionId;
|
|
280
|
+
const denyPending = this.state_.denyPending;
|
|
281
|
+
if (denyPending || this.inputBlocked) this.freshFenceOwner = this.ownerIdentity();
|
|
282
|
+
this.freshInputPending = this.inputBlocked;
|
|
283
|
+
this.freshEventReady = this.prepareFreshEvents(!!fenced);
|
|
284
|
+
if (fenced && !this.freshEventReady) {
|
|
285
|
+
this.freshInputPending = true; this.denyCursor = this.state_.offset;
|
|
286
|
+
this.setState("offline");
|
|
287
|
+
try { this.opts.onNotice?.(`${this.id}: a fresh empty Qwen event file could not be prepared; inspect the Qwen state directory and events.prev.jsonl before running ahub qwen --mode tui again`); } catch { /* already offline */ }
|
|
288
|
+
} else {
|
|
289
|
+
closeSync(openSync(this.inputFile, constants.O_WRONLY | constants.O_NOFOLLOW | constants.O_TRUNC)); // Qwen starts reading at the file's current end, so earlier submits are never replayed; empty is the clearest record
|
|
290
|
+
this.inputBlocked = false;
|
|
291
|
+
this.state_ = { v: 1, offset: 0, generation: this.state_.generation + 1, ...(resumeId ? { sessionId: resumeId } : {}), ...(denyPending ? { denyPending } : {}) };
|
|
292
|
+
this.sessionSeen = false;
|
|
293
|
+
if (fenced) {
|
|
294
|
+
this.discardReadProof();
|
|
295
|
+
this.fenceFile = this.freshEventIdentity; this.denyCursor = 0; this.eventCursor = 0; this.eventStart = 0;
|
|
296
|
+
this.detached = false; this.discarding = false; this.pollFailures = 0;
|
|
297
|
+
this.freshRead = { generation: this.state_.generation, source: this.freshEventIdentity!, activity: false };
|
|
298
|
+
}
|
|
299
|
+
this.saveState();
|
|
300
|
+
this.writeLaunch(resumeId);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
237
303
|
}
|
|
238
304
|
this.poller = setInterval(() => this.poll(), this.opts.pollMs ?? 100); this.poller.unref?.();
|
|
239
305
|
if (!this.monitor) { this.monitor = setInterval(() => this.checkOwner(), this.opts.ownerMs ?? 1_000); this.monitor.unref?.(); }
|
|
240
306
|
this.poll();
|
|
241
|
-
if (this.adopting && !this.detached && this.sessionSeen) this.setState("idle");
|
|
307
|
+
if (this.adopting && !this.detached && this.sessionSeen && !this.state_.denyPending && !this.inputBlocked && !this.freshInputPending) this.setState("idle");
|
|
242
308
|
// A TUI that has not announced itself yet is not attached: the hub treats the peer as offline until session_start.
|
|
243
309
|
}
|
|
244
310
|
|
|
311
|
+
private prepareFreshEvents(fenced: boolean): boolean {
|
|
312
|
+
if (!fenced) {
|
|
313
|
+
const previous = lstatSync(this.eventFile);
|
|
314
|
+
if (previous.size > 0) { try { renameSync(this.eventFile, join(this.dir, "events.prev.jsonl")); } catch { /* preserve the legacy nonfenced rotation ceiling */ } this.ensureFile(this.eventFile, true); }
|
|
315
|
+
return true;
|
|
316
|
+
}
|
|
317
|
+
this.freshEventIdentity = undefined;
|
|
318
|
+
let fd: number | undefined;
|
|
319
|
+
let ready = false;
|
|
320
|
+
try {
|
|
321
|
+
const previous = lstatSync(this.eventFile);
|
|
322
|
+
if (previous.size > 0) renameSync(this.eventFile, join(this.dir, "events.prev.jsonl"));
|
|
323
|
+
this.ensureFile(this.eventFile, true);
|
|
324
|
+
fd = openSync(this.eventFile, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
325
|
+
const info = fstatSync(fd);
|
|
326
|
+
ready = info.isFile() && info.size === 0;
|
|
327
|
+
if (ready) this.freshEventIdentity = `${info.dev}:${info.ino}`;
|
|
328
|
+
} catch { /* no verified empty source */ }
|
|
329
|
+
finally { if (fd !== undefined) try { closeSync(fd); } catch { ready = false; } }
|
|
330
|
+
if (!ready) this.freshEventIdentity = undefined;
|
|
331
|
+
return ready;
|
|
332
|
+
}
|
|
333
|
+
|
|
245
334
|
private writeLaunch(resumeId: string | undefined): void {
|
|
246
335
|
const [bin, ...rest] = this.opts.cmd.filter(word => word !== "--acp");
|
|
247
336
|
if (!bin) throw new Error("qwen_cmd must name an executable");
|
|
@@ -274,12 +363,19 @@ export class QwenDualPeer extends BasePeer {
|
|
|
274
363
|
|
|
275
364
|
private checkOwner(): void {
|
|
276
365
|
if (this.stopping || this.exited) return;
|
|
277
|
-
if (this.state_.ownerPid === undefined) {
|
|
278
|
-
|
|
366
|
+
if (this.state_.ownerPid === undefined) {
|
|
367
|
+
if (this.sessionSeen) this.discoverOwner();
|
|
368
|
+
this.verifyFreshInput();
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
if (this.ownerAlive()) {
|
|
372
|
+
this.verifyFreshInput();
|
|
373
|
+
return;
|
|
374
|
+
}
|
|
279
375
|
if (this.state === "offline" && !this.sessionSeen) return;
|
|
280
376
|
this.exited = true;
|
|
281
377
|
this.opts.log?.(`[${this.id}] the Qwen TUI exited`);
|
|
282
|
-
this.failTurn("the Qwen terminal ended before the turn settled; inspect it before retrying");
|
|
378
|
+
this.failTurn("the Qwen terminal ended before the turn settled; inspect it before retrying", true);
|
|
283
379
|
this.abortApprovals();
|
|
284
380
|
delete this.state_.ownerPid; delete this.state_.ownerSignature; this.saveState();
|
|
285
381
|
this.setState("offline");
|
|
@@ -288,19 +384,64 @@ export class QwenDualPeer extends BasePeer {
|
|
|
288
384
|
|
|
289
385
|
// ---- delivery ----------------------------------------------------------------------------------------------------
|
|
290
386
|
|
|
387
|
+
private inputHasCompleteTail(fd: number): boolean {
|
|
388
|
+
const info = fstatSync(fd);
|
|
389
|
+
if (!info.isFile()) return false;
|
|
390
|
+
if (info.size === 0) return true;
|
|
391
|
+
const last = Buffer.alloc(1);
|
|
392
|
+
return readSync(fd, last, 0, last.length, info.size - last.length) === last.length && last[0] === 10;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
private freshRecoveryCurrent(): boolean {
|
|
396
|
+
const launch = this.freshRead;
|
|
397
|
+
return this.freshEventReady && this.freshBaselineAbsent && this.freshFenceOwner !== undefined
|
|
398
|
+
&& !!launch && launch.generation === this.state_.generation && launch.session === this.state_.sessionId
|
|
399
|
+
&& this.sessionSeen && this.ownerIdentity() !== this.freshFenceOwner;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
private verifyFreshInput(): void {
|
|
403
|
+
if (!(this.state_.denyPending || this.freshInputPending) || !this.freshCompletionAllowed || !this.freshRecoveryCurrent() || !this.ownerAlive()) return;
|
|
404
|
+
this.readCompletion = { kind: "fresh", generation: this.state_.generation, session: this.state_.sessionId!, owner: this.ownerIdentity(), source: this.freshRead!.source };
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
private checkInputTail(): void {
|
|
408
|
+
let fd: number | undefined;
|
|
409
|
+
try {
|
|
410
|
+
fd = openSync(this.inputFile, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
411
|
+
if (!this.inputHasCompleteTail(fd)) this.blockInput();
|
|
412
|
+
} catch { this.blockInput(); }
|
|
413
|
+
finally { if (fd !== undefined) try { closeSync(fd); } catch { this.blockInput(); } }
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
private blockInput(): void {
|
|
417
|
+
const newlyBlocked = !this.inputBlocked;
|
|
418
|
+
this.inputBlocked = true; this.discardReadProof();
|
|
419
|
+
this.failTurn(QWEN_INPUT_UNCERTAIN_NOTE, true);
|
|
420
|
+
this.setState("offline");
|
|
421
|
+
if (newlyBlocked) try { this.opts.onNotice?.(`${this.id}: ${QWEN_INPUT_UNCERTAIN_NOTE}`); } catch { /* already fenced */ }
|
|
422
|
+
}
|
|
423
|
+
|
|
291
424
|
private appendInput(record: Json): void {
|
|
292
|
-
const
|
|
293
|
-
if (
|
|
294
|
-
|
|
425
|
+
const bytes = Buffer.from(`${JSON.stringify(record)}\n`, "utf8");
|
|
426
|
+
if (bytes.length > SUBMIT_CAP) throw new Error("Qwen submit exceeds its size bound");
|
|
427
|
+
if (this.inputBlocked || this.freshInputPending) throw new QwenInputUncertain();
|
|
428
|
+
const fd = openSync(this.inputFile, constants.O_RDWR | constants.O_APPEND | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
429
|
+
let writerAttempted = false;
|
|
295
430
|
try {
|
|
296
431
|
const info = fstatSync(fd);
|
|
297
432
|
if (!info.isFile() || (info.mode & 0o077) !== 0 || (typeof process.getuid === "function" && info.uid !== process.getuid())) throw new Error("Qwen input file is not private");
|
|
298
|
-
|
|
299
|
-
|
|
433
|
+
if (!this.inputHasCompleteTail(fd)) throw new QwenInputUncertain();
|
|
434
|
+
// ponytail: a torn prefix ending in newline is not detected by this tail guard. If observed, add a durable write-intent record before every input write.
|
|
435
|
+
writerAttempted = true;
|
|
436
|
+
try { if ((this.opts.writeInput ?? writeSync)(fd, bytes) !== bytes.length) throw new QwenInputUncertain(); }
|
|
437
|
+
catch { throw new QwenInputUncertain(); } // no retry or remainder: the writer may already have appended a prefix
|
|
438
|
+
} finally {
|
|
439
|
+
try { closeSync(fd); } catch (error) { if (writerAttempted) throw new QwenInputUncertain(); throw error; }
|
|
440
|
+
}
|
|
300
441
|
}
|
|
301
442
|
|
|
302
443
|
async deliver(envs: Envelope[], deliveryId?: string): Promise<void> {
|
|
303
|
-
if (this.state !== "idle" || this.stopping || this.detached) {
|
|
444
|
+
if (this.state !== "idle" || this.stopping || this.detached || this.state_.denyPending || this.inputBlocked) {
|
|
304
445
|
if (deliveryId) this.delivery({ id: deliveryId, state: "failed_safe", reason: `${this.id} is ${this.state}` });
|
|
305
446
|
throw new Error(`${this.id} is ${this.state}`);
|
|
306
447
|
}
|
|
@@ -312,6 +453,7 @@ export class QwenDualPeer extends BasePeer {
|
|
|
312
453
|
this.setState("busy"); // synchronously: the bus must not drain the next envelope into this turn
|
|
313
454
|
try { this.appendInput({ type: "submit", text }); }
|
|
314
455
|
catch (error) {
|
|
456
|
+
if (error instanceof QwenInputUncertain) { this.blockInput(); throw error; }
|
|
315
457
|
this.turn = undefined;
|
|
316
458
|
if (deliveryId) this.delivery({ id: deliveryId, state: "failed_safe", reason: "Qwen input file could not be written" });
|
|
317
459
|
this.setState("idle");
|
|
@@ -323,7 +465,7 @@ export class QwenDualPeer extends BasePeer {
|
|
|
323
465
|
// ---- watchdog: report, never cancel -----------------------------------------------------------------------------------
|
|
324
466
|
|
|
325
467
|
protected override onWatchdog(): void {
|
|
326
|
-
if (this.state !== "busy" || this.stalled_) return;
|
|
468
|
+
if (this.state !== "busy" || this.stalled_ || this.state_.denyPending) return;
|
|
327
469
|
if (this.pending.size > 0) { this.touch(); return; } // a person deciding is not Qwen going silent
|
|
328
470
|
this.stalled_ = true;
|
|
329
471
|
this.opts.log?.(`[${this.id}] turn stalled; the hub cannot stop it (press Esc in the Qwen terminal)`);
|
|
@@ -343,21 +485,29 @@ export class QwenDualPeer extends BasePeer {
|
|
|
343
485
|
if (this.detached) return;
|
|
344
486
|
this.detached = true;
|
|
345
487
|
this.opts.log?.(`[${this.id}] event file ${reason}: detached`);
|
|
346
|
-
this.
|
|
488
|
+
this.discardReadProof();
|
|
489
|
+
this.failTurn("the Qwen event file became unreadable before the turn settled; inspect the Qwen terminal before retrying", true);
|
|
347
490
|
this.abortApprovals();
|
|
348
491
|
if (this.state !== "offline") this.setState("offline"); // detached is never idle: nothing can be delivered to a TUI nobody can read
|
|
349
492
|
}
|
|
350
493
|
|
|
351
494
|
private poll(): void {
|
|
352
|
-
if (this.stopping) return;
|
|
495
|
+
if (this.stopping || this.polling) return;
|
|
496
|
+
this.polling = true;
|
|
353
497
|
let fd: number | undefined;
|
|
354
498
|
try {
|
|
499
|
+
this.checkInputTail();
|
|
355
500
|
fd = openSync(this.eventFile, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
356
501
|
const info = fstatSync(fd);
|
|
357
502
|
if (!info.isFile()) throw new Error("not a regular file");
|
|
358
|
-
if (this.
|
|
503
|
+
if (this.state_.denyPending || this.freshInputPending) {
|
|
504
|
+
const identity = `${info.dev}:${info.ino}`;
|
|
505
|
+
if (this.detached || this.fenceFile !== undefined && identity !== this.fenceFile) { this.discardReadProof(); this.denyCursor = info.size; }
|
|
506
|
+
this.fenceFile = identity;
|
|
507
|
+
}
|
|
508
|
+
if (this.detached) { this.detached = false; this.pollFailures = 0; this.opts.log?.(`[${this.id}] event file readable again: reattached`); if (this.sessionSeen && this.state === "offline" && !this.exited && !this.state_.denyPending && !this.inputBlocked && !this.freshInputPending) this.setState("idle"); }
|
|
359
509
|
let offset = this.state_.offset;
|
|
360
|
-
if (info.size < offset) { offset = 0; this.discarding = false; this.state_.generation++; this.opts.log?.(`[${this.id}] event file was replaced; reading from its start`); }
|
|
510
|
+
if (info.size < offset) { offset = 0; this.discarding = false; this.state_.generation++; this.discardReadProof(); this.denyCursor = info.size; this.opts.log?.(`[${this.id}] event file was replaced; reading from its start`); }
|
|
361
511
|
while (offset < info.size) {
|
|
362
512
|
const want = Math.min(info.size - offset, READ_CAP), buffer = Buffer.alloc(want);
|
|
363
513
|
const got = readSync(fd, buffer, 0, want, offset);
|
|
@@ -373,29 +523,52 @@ export class QwenDualPeer extends BasePeer {
|
|
|
373
523
|
const end = buffer.subarray(0, got).lastIndexOf(10) + 1;
|
|
374
524
|
if (end === 0) {
|
|
375
525
|
if (got < READ_CAP) break; // a partial line waits for its newline
|
|
526
|
+
this.discardReadProof();
|
|
376
527
|
this.opts.log?.(`[${this.id}] dropped an event line over ${READ_CAP} bytes`);
|
|
377
528
|
this.discarding = true; offset += got; this.state_.offset = offset; continue;
|
|
378
529
|
}
|
|
530
|
+
const start = offset;
|
|
379
531
|
offset += end;
|
|
380
532
|
this.state_.offset = offset;
|
|
381
|
-
for (
|
|
533
|
+
for (let cursor = 0; cursor < end;) {
|
|
534
|
+
const newline = buffer.indexOf(10, cursor);
|
|
535
|
+
const rawLine = buffer.subarray(cursor, newline);
|
|
536
|
+
const line = rawLine.toString("utf8");
|
|
537
|
+
this.eventStart = start + cursor;
|
|
538
|
+
cursor = newline + 1;
|
|
539
|
+
this.eventCursor = start + cursor;
|
|
540
|
+
if (!Buffer.from(line).equals(rawLine)) { this.discardReadProof(); continue; }
|
|
541
|
+
if (line.trim()) this.parse(line);
|
|
542
|
+
}
|
|
382
543
|
if (this.stopping) break;
|
|
383
544
|
}
|
|
545
|
+
this.finishFencedRead(fd);
|
|
384
546
|
this.saveState();
|
|
385
547
|
} catch (error) {
|
|
386
548
|
this.pollFailures++;
|
|
387
549
|
if (!this.detached) this.detach(`could not be read (${(error as NodeJS.ErrnoException).code ?? "error"})`);
|
|
388
|
-
} finally {
|
|
550
|
+
} finally {
|
|
551
|
+
if (fd !== undefined) try { closeSync(fd); } catch { /* nothing to close */ }
|
|
552
|
+
this.polling = false;
|
|
553
|
+
}
|
|
389
554
|
}
|
|
390
555
|
|
|
391
556
|
private parse(line: string): void {
|
|
392
557
|
let event: Json;
|
|
393
|
-
try { event = JSON.parse(line) as Json; } catch { this.opts.log?.(`[${this.id}] skipped an unreadable event line`); return; }
|
|
394
|
-
if (!event || typeof event !== "object" || typeof event.type !== "string") return;
|
|
395
|
-
try { this.handle(event); } catch (error) { this.opts.log?.(`[${this.id}] event handling failed: ${sanitize((error as Error).message)}`); }
|
|
558
|
+
try { event = JSON.parse(line) as Json; } catch { this.discardReadProof(); this.opts.log?.(`[${this.id}] skipped an unreadable event line`); return; }
|
|
559
|
+
if (!event || typeof event !== "object" || typeof event.type !== "string") { this.discardReadProof(); return; }
|
|
560
|
+
try { this.handle(event); } catch (error) { this.discardReadProof(); this.opts.log?.(`[${this.id}] event handling failed: ${sanitize((error as Error).message)}`); }
|
|
396
561
|
}
|
|
397
562
|
|
|
398
563
|
private handle(event: Json): void {
|
|
564
|
+
if (this.inputBlocked) return;
|
|
565
|
+
const fenced = this.state_.denyPending || this.freshInputPending;
|
|
566
|
+
if (fenced && this.eventStart < this.denyCursor) { this.discardReadProof(); return; }
|
|
567
|
+
if (fenced && event.type !== "system") {
|
|
568
|
+
this.readCompletion = undefined; this.freshCompletionAllowed = false;
|
|
569
|
+
if (this.freshRead) this.freshRead.activity = true;
|
|
570
|
+
this.observeDenied(event); return;
|
|
571
|
+
}
|
|
399
572
|
this.alive();
|
|
400
573
|
switch (event.type) {
|
|
401
574
|
case "system": return this.onSystem(event);
|
|
@@ -410,22 +583,32 @@ export class QwenDualPeer extends BasePeer {
|
|
|
410
583
|
}
|
|
411
584
|
|
|
412
585
|
private onSystem(event: Json): void {
|
|
413
|
-
|
|
586
|
+
const fenced = this.state_.denyPending || this.freshInputPending;
|
|
587
|
+
if (fenced) { this.personalProof = undefined; this.readCompletion = undefined; this.freshCompletionAllowed = false; }
|
|
588
|
+
if (event.subtype !== "session_start") { if (fenced && this.freshRead) this.freshRead.activity = true; return; }
|
|
414
589
|
const data = event.data ?? {};
|
|
415
590
|
const id = event.session_id ?? data.session_id;
|
|
416
|
-
if (!qwenSessionId(id)) return;
|
|
591
|
+
if (!qwenSessionId(id)) { if (fenced && this.freshRead) this.freshRead.activity = true; return; }
|
|
417
592
|
// The TUI states its own contract: a version, protocol or event set the hub did not verify is refused, however it was launched.
|
|
418
593
|
const verdict = assessVersion("qwen-dual", data.version);
|
|
419
594
|
const supported: unknown = data.supported_events;
|
|
420
595
|
if (!verdict.ok || data.protocol_version !== 2 || !Array.isArray(supported) || !["user", "assistant", "stream_event", "control_request", "control_response"].every(name => supported.includes(name))) {
|
|
596
|
+
if (fenced && this.freshRead) this.freshRead.activity = true;
|
|
421
597
|
this.opts.log?.(`[${this.id}] the Qwen TUI's dual-output contract is not verified; not attached`);
|
|
422
598
|
try { this.opts.onNotice?.(`${this.id}: this Qwen's dual-output contract is not verified (${verdict.ok ? "protocol or event set" : verdict.reason}); the hub did not attach it`); } catch { /* notice only */ }
|
|
423
599
|
return;
|
|
424
600
|
}
|
|
425
|
-
this.state_.
|
|
601
|
+
if (this.state_.denyPending && this.freshFenceOwner === undefined && id !== this.state_.sessionId) { this.discardReadProof(); return; }
|
|
602
|
+
this.state_.sessionId = id; this.sessionSeen = true;
|
|
603
|
+
if (fenced && this.freshRead) {
|
|
604
|
+
if (this.freshRead.session === undefined) { this.freshRead.session = id; this.freshCompletionAllowed = !this.freshRead.activity; }
|
|
605
|
+
else this.freshRead.activity = true; // a replay never re-arms an invalidated fresh-header candidate
|
|
606
|
+
}
|
|
607
|
+
this.saveState();
|
|
426
608
|
// Bind the owner now, not on the next tick: a hub that stops in between would record no owner and relaunch over a Qwen that is still running.
|
|
427
609
|
this.discoverOwner();
|
|
428
|
-
|
|
610
|
+
this.verifyFreshInput();
|
|
611
|
+
if (!this.stopping && !this.detached && this.state === "offline" && !this.state_.denyPending && !this.freshInputPending) this.setState("idle");
|
|
429
612
|
}
|
|
430
613
|
|
|
431
614
|
/**
|
|
@@ -516,6 +699,90 @@ export class QwenDualPeer extends BasePeer {
|
|
|
516
699
|
|
|
517
700
|
// ---- approvals ------------------------------------------------------------------------------------------------------------
|
|
518
701
|
|
|
702
|
+
private ownerIdentity(): string { return `${this.state_.ownerPid}:${this.state_.ownerSignature}`; }
|
|
703
|
+
|
|
704
|
+
/** A deny has no completion ACK. Only a subsequent personal turn, or a verified new launch, can reopen input. */
|
|
705
|
+
private observeDenied(event: Json): void {
|
|
706
|
+
if (this.stopping || this.exited || this.detached || this.eventCursor <= this.denyCursor) return;
|
|
707
|
+
const session = this.state_.sessionId;
|
|
708
|
+
if (!session || event.session_id !== session || !this.ownerAlive()) { this.discardReadProof(); return; }
|
|
709
|
+
if (event.type === "user") {
|
|
710
|
+
if (this.isNotificationEvent(event) || this.promptText(event) === undefined) { this.discardReadProof(); return; }
|
|
711
|
+
this.personalProof = { generation: this.state_.generation, session, owner: this.ownerIdentity(), assistant: false };
|
|
712
|
+
return;
|
|
713
|
+
}
|
|
714
|
+
const proof = this.personalProof;
|
|
715
|
+
if (!proof || proof.generation !== this.state_.generation || proof.session !== session || proof.owner !== this.ownerIdentity()) return;
|
|
716
|
+
if (event.type === "assistant") {
|
|
717
|
+
const message = event.message;
|
|
718
|
+
proof.assistant = message?.stop_reason === "end_turn" && Array.isArray(message.content) && !message.content.some((block: Json) => block?.type === "tool_use");
|
|
719
|
+
} else if (event.type === "stream_event" && event.event?.type === "message_stop") {
|
|
720
|
+
if (proof.assistant && this.fenceFile !== undefined) this.readCompletion = { kind: "personal", generation: proof.generation, session: proof.session, owner: proof.owner, source: this.fenceFile, personal: proof };
|
|
721
|
+
proof.assistant = false;
|
|
722
|
+
} else proof.assistant = false;
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
private discardReadProof(): void {
|
|
726
|
+
this.personalProof = undefined; this.readCompletion = undefined; this.freshCompletionAllowed = false;
|
|
727
|
+
if (this.freshRead) this.freshRead.activity = true;
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
private finishFencedRead(fd: number): void {
|
|
731
|
+
const candidate = this.readCompletion;
|
|
732
|
+
if (!(this.state_.denyPending || this.freshInputPending) || !candidate || this.discarding) return;
|
|
733
|
+
if (!this.ownerAlive()) { this.discardReadProof(); return; }
|
|
734
|
+
if (this.readCompletion !== candidate || this.stopping || this.exited || this.detached || this.inputBlocked
|
|
735
|
+
|| candidate.generation !== this.state_.generation || candidate.session !== this.state_.sessionId || candidate.owner !== this.ownerIdentity()
|
|
736
|
+
|| candidate.kind === "personal" && candidate.personal !== this.personalProof
|
|
737
|
+
|| candidate.kind === "fresh" && !this.freshCompletionAllowed
|
|
738
|
+
|| this.freshInputPending && !this.freshRecoveryCurrent()) { this.discardReadProof(); return; }
|
|
739
|
+
const current = fstatSync(fd), named = lstatSync(this.eventFile);
|
|
740
|
+
if (!current.isFile() || !named.isFile() || named.isSymbolicLink() || current.dev !== named.dev || current.ino !== named.ino
|
|
741
|
+
|| `${current.dev}:${current.ino}` !== candidate.source
|
|
742
|
+
|| this.freshInputPending && candidate.source !== this.freshRead?.source
|
|
743
|
+
|| current.size !== this.state_.offset || named.size !== current.size) { this.discardReadProof(); return; }
|
|
744
|
+
// ponytail: this proves only the observed frontier; atomic exclusion of future person input needs a serialized native idle ACK.
|
|
745
|
+
this.readCompletion = undefined; this.freshInputPending = false;
|
|
746
|
+
this.clearDenyFence();
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
private clearDenyFence(): void {
|
|
750
|
+
if (this.inputBlocked || this.freshInputPending) return;
|
|
751
|
+
// A refusal before the deny append leaves an unsettled original turn. Recovery is not evidence of its outcome.
|
|
752
|
+
if (this.turn) this.failTurn("the approval outcome was not confirmed before Qwen recovered; inspect the terminal and held delivery before retrying", true);
|
|
753
|
+
delete this.state_.denyPending;
|
|
754
|
+
if (!this.saveState()) {
|
|
755
|
+
this.state_.denyPending = true; this.discardReadProof(); this.denyStorageFailure = true;
|
|
756
|
+
this.setState("offline");
|
|
757
|
+
try { this.opts.onNotice?.(`${this.id}: ${QWEN_DENY_STORAGE_NOTE}`); } catch { /* advisory only, the fence is already restored */ }
|
|
758
|
+
return;
|
|
759
|
+
}
|
|
760
|
+
if (this.denyTimer) clearTimeout(this.denyTimer);
|
|
761
|
+
this.denyTimer = undefined; this.discardReadProof(); this.freshFenceOwner = undefined;
|
|
762
|
+
this.denyStorageFailure = false; this.stalled_ = false; this.lastAssistant = undefined;
|
|
763
|
+
this.opts.onStalled?.(false);
|
|
764
|
+
if (!this.stopping && !this.detached && !this.exited) this.setState("idle");
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
private fenceDeny(): boolean {
|
|
768
|
+
let fd: number | undefined;
|
|
769
|
+
try {
|
|
770
|
+
fd = openSync(this.eventFile, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
771
|
+
const info = fstatSync(fd);
|
|
772
|
+
if (!info.isFile()) throw new Error("not a regular file");
|
|
773
|
+
this.denyCursor = info.size; this.fenceFile = `${info.dev}:${info.ino}`;
|
|
774
|
+
this.state_.denyPending = true;
|
|
775
|
+
if (!this.saveState()) throw new Error("could not persist fence");
|
|
776
|
+
this.discardReadProof(); this.lastAssistant = undefined;
|
|
777
|
+
return true;
|
|
778
|
+
} catch {
|
|
779
|
+
// No deny is appended without its restart fence. Keep any saved marker conservative as well.
|
|
780
|
+
this.state_.denyPending = true; this.denyStorageFailure = true; this.setState("offline");
|
|
781
|
+
try { this.opts.onNotice?.(`${this.id}: the hub could not persist the deny input fence; answer the pending prompt in the Qwen terminal and inspect its state before restarting the hub`); } catch { /* notice only */ }
|
|
782
|
+
return false;
|
|
783
|
+
} finally { if (fd !== undefined) closeSync(fd); }
|
|
784
|
+
}
|
|
785
|
+
|
|
519
786
|
private abortApprovals(): void {
|
|
520
787
|
for (const { controller } of this.pending.values()) controller.abort();
|
|
521
788
|
this.pending.clear();
|
|
@@ -556,20 +823,31 @@ export class QwenDualPeer extends BasePeer {
|
|
|
556
823
|
}
|
|
557
824
|
|
|
558
825
|
private answer(requestId: string, allowed: boolean, turn: Turn, why?: string): void {
|
|
826
|
+
if (this.turn !== turn || this.stopping || this.state_.denyPending || this.answered.has(requestId)) return;
|
|
827
|
+
if (!allowed && !this.fenceDeny()) return;
|
|
559
828
|
try { this.appendInput({ type: "confirmation_response", request_id: requestId, allowed }); }
|
|
560
|
-
catch {
|
|
829
|
+
catch (error) {
|
|
830
|
+
if (error instanceof QwenInputUncertain) { this.blockInput(); return; }
|
|
561
831
|
// Qwen never received it: it is still blocked on the approval. Settling the turn (a deny) or reporting it answered would be a claim the hub cannot back, so the turn stays busy
|
|
562
832
|
// (the watchdog reports it if nothing moves) and the person is told to answer in the Qwen terminal, where the prompt is still open.
|
|
563
|
-
this.
|
|
833
|
+
if (!allowed) { delete this.state_.denyPending; if (!this.saveState()) { this.state_.denyPending = true; this.denyStorageFailure = true; this.setState("offline"); } }
|
|
834
|
+
try { this.opts.log?.(`[${this.id}] could not write an approval answer`); } catch { /* advisory only */ }
|
|
564
835
|
try { this.opts.onNotice?.(`${this.id}: the hub could not write its approval answer (the input file is unwritable); answer the prompt in the Qwen terminal`); } catch { /* notice only */ }
|
|
565
836
|
return;
|
|
566
837
|
}
|
|
567
838
|
this.answered.add(requestId); while (this.answered.size > ANSWERED_CAP) this.answered.delete(this.answered.values().next().value as string);
|
|
568
839
|
if (allowed || this.turn !== turn) return;
|
|
569
|
-
//
|
|
840
|
+
// Known delivery disposition is independent of native readiness. Never expose an idle gap to Bus.onState.
|
|
570
841
|
this.owner = undefined;
|
|
571
842
|
this.abortApprovals();
|
|
572
|
-
this.failTurn(why ?? "a hub deny cancelled the Qwen turn
|
|
843
|
+
this.failTurn(why ?? "a hub deny cancelled the Qwen turn without an answer; input remains fenced until a personal turn completes or a new Qwen generation starts", true, true);
|
|
844
|
+
this.clearWatchdog();
|
|
845
|
+
this.denyTimer = setTimeout(() => {
|
|
846
|
+
if (!this.state_.denyPending || this.stopping) return;
|
|
847
|
+
this.setState("offline");
|
|
848
|
+
try { this.opts.onNotice?.(`${this.id}: ${this.denyStorageFailure ? QWEN_DENY_STORAGE_NOTE : QWEN_DENY_QUIESCENCE_NOTE}`); } catch { /* notice only */ }
|
|
849
|
+
}, this.opts.denyQuiescenceMs ?? QWEN_DENY_QUIESCENCE_MS);
|
|
850
|
+
this.denyTimer.unref?.();
|
|
573
851
|
}
|
|
574
852
|
|
|
575
853
|
private onControlResponse(event: Json): void {
|
|
@@ -590,6 +868,8 @@ export class QwenDualPeer extends BasePeer {
|
|
|
590
868
|
async stop(reason?: string): Promise<void> {
|
|
591
869
|
if (reason !== undefined) this.requestedStopReason = reason;
|
|
592
870
|
this.stopping = true;
|
|
871
|
+
if (this.denyTimer) clearTimeout(this.denyTimer); this.denyTimer = undefined;
|
|
872
|
+
this.discardReadProof();
|
|
593
873
|
if (this.poller) clearInterval(this.poller); this.poller = undefined;
|
|
594
874
|
if (this.monitor) clearInterval(this.monitor); this.monitor = undefined;
|
|
595
875
|
this.abortApprovals();
|