@linxin666/dsh-remote-bridge 0.4.11 → 0.4.12

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.
@@ -1,58 +1,107 @@
1
1
  /**
2
- * When a finished turn may be announced: after the session it belongs to falls
2
+ * When a finished turn may be announced: after the family it belongs to falls
3
3
  * quiet, not when the frame arrives.
4
4
  *
5
5
  * A `turn/end` increment is a fact about one turn and nothing more. The work the
6
- * user started with it may still be going: the child sessions it delegated to and
7
- * the background jobs the host still holds under those sessions outlive the turn
8
- * that started them. A phone told "turn finished" at the frame wakes on a session
9
- * the roster still badges as running, reads a card that says ended while the work
10
- * goes on, and is told again by a second turn end it never asked for. §28's
11
- * notification and §29's card answer the same question — "is this session working
12
- * right now" — and that question has one answer, the one the client already
13
- * computes in `SessionRun`: the host's own `agentRunning` for the session, any
14
- * descendant session still running, and any job the host attributes to either.
6
+ * user started with it may still be going: the subagent sessions the host spawned
7
+ * under it at any depth, and the background jobs the host still holds under any of
8
+ * them, outlive the turn that started them. A phone told "turn finished" at the
9
+ * frame wakes on a roster that still badges a session running, reads a card that
10
+ * says ended while the work goes on, and is told again by a second turn end it
11
+ * never asked for. §28's notification and §29's card answer the same question — "is
12
+ * this work still going" — and that question has one answer, the family's.
15
13
  *
16
- * So a turn end is registered here instead of sent, and sent once the host says
17
- * the session is quiet. Three rules hold that together:
14
+ * The family is the root a session's parent chain climbs to, plus every session
15
+ * under that root at any depth. A leaf session's own turn end therefore waits for
16
+ * the root and for the siblings and cousins it shares that root with, which is the
17
+ * work the user actually started. So a turn end is registered here instead of sent,
18
+ * and sent once the host says the family is quiet. Three rules hold that together:
18
19
  *
19
- * - the answer comes from the host and nowhere else: one `session/list` read for
20
- * the running flag and the parent chain, and the host's job registry for the
21
- * jobs it attributes to a session. This module invents no timer-based guess and
22
- * reads no client state, because a guess that says "quiet" is a lock screen
23
- * saying the work finished when it did not;
20
+ * - the answer comes from the host and nowhere else: one `session/list` read for the
21
+ * running flags, the parent chain and each session's origin, and the host's job
22
+ * registry for the jobs it attributes to a session. This module invents no
23
+ * timer-based guess and reads no client state, because a guess that says "quiet"
24
+ * is a lock screen saying the work finished when it did not;
24
25
  * - nothing on the frame path waits: a registration stores five fields and arms a
25
26
  * timer, so a follow stream still publishes its increment at the speed it did
26
27
  * before;
27
- * - the wait is bounded. At {@link TURN_END_QUIET_MAX_MS} the announcement goes
28
- * out anyway and the line it logs names what was still going, because a
29
- * notification that never arrives is the failure this channel exists to prevent.
28
+ * - the wait has no deadline. A family that stays busy is never announced, and a
29
+ * host that cannot answer is asked again rather than read as quiet: announcing
30
+ * work that is still running is the failure this channel exists to prevent, and a
31
+ * notification that never arrives is the lesser one. One question, though, is
32
+ * bounded ({@link TURN_END_QUIET_PROBE_TIMEOUT_MS}): a read the gateway never
33
+ * returns is abandoned as that question's own failure and the entry asks again, so
34
+ * a stuck call cannot leave the entry holding no question to ask and no way to
35
+ * speak. One line at {@link TURN_END_QUIET_REPORT_MS} says the bridge is still
36
+ * waiting, so an operator is not left guessing why a phone stayed silent.
37
+ *
38
+ * Not every turn end is the phone's to hear. A session the host spawned as a
39
+ * subagent (`origin: "subagent"`) ends turns nobody asked this bridge about, so its
40
+ * turn end is dropped on its first answer unless the phone itself prompted that
41
+ * session over the wire.
30
42
  * @module dsh-remote-bridge/core/turn-end-quiet
31
43
  */
32
44
  import type { JobRoster } from './jobs.ts';
33
45
  import type { LiveActivityNotifier } from './liveactivity.ts';
34
46
  import { type PushNotifier } from './push.ts';
35
47
  import { type BridgeGateway, type GatewayPeer } from './wire.ts';
36
- /** Longest a registered turn end waits for its session to fall quiet, in milliseconds. */
37
- export declare const TURN_END_QUIET_MAX_MS = 600000;
48
+ /**
49
+ * How long a held turn end waits before the bridge logs that it is still waiting,
50
+ * in milliseconds.
51
+ *
52
+ * A progress line and never a send: the wait itself has no cap, because announcing a
53
+ * turn while its family still works is exactly what this module exists to prevent.
54
+ */
55
+ export declare const TURN_END_QUIET_REPORT_MS = 600000;
38
56
  /**
39
57
  * How long a held turn end waits before asking the host again, in milliseconds.
40
58
  *
41
- * A turn end usually finds its session already quiet — the host clears the flag
42
- * as the turn finishes — so the first question is the one that matters, and five
59
+ * A turn end usually finds its family already quiet — the host clears the flag as
60
+ * the turn finishes — so the first question is the one that matters, and five
43
61
  * seconds is short enough that the notification a user waits for is not visibly
44
62
  * late. The interval is also what bounds how many questions one held turn end can
45
63
  * cost: at most one every five seconds, never more than one in flight.
46
64
  */
47
65
  export declare const TURN_END_QUIET_INTERVAL_MS = 5000;
48
- /** The host's answer about the work one session still holds. */
66
+ /**
67
+ * How long one question to the host may stay unanswered before the bridge abandons
68
+ * that question, in milliseconds.
69
+ *
70
+ * Three times {@link TURN_END_QUIET_INTERVAL_MS}. A `session/list` read the host is
71
+ * willing to make comes back well inside one interval, so a question that outlives
72
+ * three of them is a call that will not return — a stuck gateway request, not a slow
73
+ * host — and an entry that keeps waiting for it has no next question to ask, which is
74
+ * exactly how a phone goes permanently silent. The bound belongs to the question and
75
+ * never to the turn end: an abandoned question answers nothing, the entry stays held,
76
+ * and the next question leaves on the usual interval.
77
+ */
78
+ export declare const TURN_END_QUIET_PROBE_TIMEOUT_MS = 15000;
79
+ /**
80
+ * How many session ids the gate remembers the phone prompting, at most.
81
+ *
82
+ * The set exists to tell the phone's own subagent sessions from the ones it merely
83
+ * watches, and a bridge that runs for weeks must not grow it without end: the oldest
84
+ * id is dropped first, and a session dropped that way and prompted again enters as a
85
+ * new one.
86
+ */
87
+ export declare const TURN_END_PHONE_PROMPTED_MAX = 5000;
88
+ /** The host's answer about the work one session's family still holds. */
49
89
  export interface QuietAnswer {
50
- /** Whether nothing under this session is still going. */
90
+ /** Whether nothing in this session's family is still going. */
51
91
  readonly quiet: boolean;
52
92
  /** What was still going when it was not, in one token for the log line. */
53
93
  readonly busy?: string;
94
+ /**
95
+ * Present only when the host says another session spawned this one
96
+ * (`origin: "subagent"`).
97
+ *
98
+ * Absent is a host that said nothing about the session's origin, which is not the
99
+ * same as saying it has none: a turn end is announced for anything the host does
100
+ * not name as a subagent.
101
+ */
102
+ readonly subagent?: boolean;
54
103
  }
55
- /** Whether one session is quiet right now, as the host answers it. */
104
+ /** Whether one session's family is quiet right now, as the host answers it. */
56
105
  export type QuietProbe = (sessionId: string) => Promise<QuietAnswer>;
57
106
  export interface TurnEndQuietOptions {
58
107
  /** The notification path of §28; absent is a bridge that sends no notification. */
@@ -62,17 +111,22 @@ export interface TurnEndQuietOptions {
62
111
  /**
63
112
  * The host's own answer, asked off the frame path.
64
113
  *
65
- * Absent is a bridge assembled without one, which cannot tell a quiet session
66
- * from a busy one and therefore reports at the frame rather than holding
67
- * anything back.
114
+ * Absent is a bridge assembled without one, which cannot tell a quiet family from
115
+ * a busy one — nor a subagent session from the phone's own — and therefore reports
116
+ * at the frame rather than holding anything back.
68
117
  */
69
118
  readonly probe?: QuietProbe;
70
119
  readonly now?: () => number;
71
120
  readonly log?: (message: string) => void;
72
- /** The wait budget; the default is {@link TURN_END_QUIET_MAX_MS}, and a deployment moves it. */
73
- readonly maxWaitMs?: number;
121
+ /** When the still-waiting line is logged; the default is {@link TURN_END_QUIET_REPORT_MS}. */
122
+ readonly reportAfterMs?: number;
74
123
  /** The re-check interval; the default is {@link TURN_END_QUIET_INTERVAL_MS}. */
75
124
  readonly intervalMs?: number;
125
+ /**
126
+ * How many phone-prompted session ids to remember; the default and the ceiling are
127
+ * both {@link TURN_END_PHONE_PROMPTED_MAX}, and a deployment lowers it for a suite.
128
+ */
129
+ readonly phonePromptLimit?: number;
76
130
  }
77
131
  /**
78
132
  * The bridge's outbound turn-end path: registration now, announcement when quiet.
@@ -90,7 +144,7 @@ export declare class TurnEndQuietGate {
90
144
  /** @returns how many turn ends are held right now. */
91
145
  get held(): number;
92
146
  /**
93
- * Hold one finished turn until its session is quiet, then announce it.
147
+ * Hold one finished turn until its family is quiet, then announce it.
94
148
  *
95
149
  * Returns at once and never awaits a host read: the caller is a follow stream
96
150
  * that has already published its increment.
@@ -98,6 +152,16 @@ export declare class TurnEndQuietGate {
98
152
  * @param reason - the host's own reason for ending it.
99
153
  */
100
154
  noteTurnEnd(sessionId: string, reason: string): void;
155
+ /**
156
+ * Remember that the phone itself prompted one session.
157
+ *
158
+ * This is the one thing that makes a subagent session's turn end announceable: the
159
+ * host spawns those on its own, and a phone that never asked that session anything
160
+ * is not waiting to hear how its turn went. Bounded and first in, first out, so the
161
+ * memory is the recent work rather than everything since the bridge started.
162
+ * @param sessionId - the session a `session/prompt` frame carried.
163
+ */
164
+ notePhonePrompt(sessionId: string): void;
101
165
  /**
102
166
  * Drop a held turn end because another turn is on.
103
167
  *
@@ -121,14 +185,14 @@ export interface SessionQuietProbeOptions {
121
185
  readonly jobs: JobRoster;
122
186
  }
123
187
  /**
124
- * The host's answer to "is this session quiet", built from its own two facts.
188
+ * The host's answer to "is this session's family quiet", built from its own facts.
125
189
  *
126
- * The session list is where the running flag and the parent chain come from, and
127
- * the job registry is where a job's owner and status come from; neither is
128
- * captured once, because both move while a held turn end waits. A read that cannot
129
- * be made is thrown rather than answered as quiet: "the host did not answer" and
130
- * "nothing is running" are different facts, and the caller retries the one and
131
- * announces the other.
190
+ * The session list is where the running flags, the parent chain and each session's
191
+ * origin come from, and the job registry is where a job's owner and status come
192
+ * from; neither is captured once, because both move while a held turn end waits. A
193
+ * read that cannot be made is thrown rather than answered as quiet: "the host did
194
+ * not answer" and "nothing is running" are different facts, and the caller retries
195
+ * the one and announces the other.
132
196
  * @param options - the faces the answer is read through.
133
197
  * @returns the probe the gate asks.
134
198
  */
@@ -61,20 +61,24 @@ export declare const OFFLINE_CLAIM_TTL_ENV = "DSH_REMOTE_BRIDGE_OFFLINE_CLAIM_TT
61
61
  * @returns the window in milliseconds.
62
62
  */
63
63
  export declare function offlineClaimTtl(env?: NodeJS.ProcessEnv): number;
64
- /** The environment variable that moves how long a finished turn waits for its session to go quiet (§28). */
64
+ /**
65
+ * The environment variable that moves when a still-waiting turn end is reported (§28).
66
+ *
67
+ * The name is the one deployments already set and is kept as it is; what it moves is
68
+ * the point at which the bridge says it is still waiting, because the wait itself has
69
+ * no cap.
70
+ */
65
71
  export declare const TURN_END_QUIET_MAX_ENV = "DSH_REMOTE_BRIDGE_TURN_END_QUIET_MAX_MS";
66
72
  /**
67
- * The quiet-wait budget this process runs with.
73
+ * The still-waiting report point this process runs with.
68
74
  *
69
- * The budget is the bridge's own constant and never a host fact, so a deployment
70
- * moves it here. A value that is missing, unreadable or not positive falls back to
71
- * the constant instead of closing the window: a zero budget would announce every
72
- * turn end at its frame, and an operator who wanted that would be turning push
73
- * off. The budget only bounds the wait — a session that does fall quiet inside it
74
- * is announced then, and one that does not is announced at the end with the
75
- * reason it was still busy.
75
+ * It is the bridge's own constant and never a host fact, so a deployment moves it
76
+ * here. A value that is missing, unreadable or not positive falls back to the
77
+ * constant: the point only decides when the log line saying the wait continues is
78
+ * written, and nothing about it can make the bridge announce work that is still
79
+ * running or withhold a turn end whose family is quiet.
76
80
  * @param env - the process environment, injectable for a suite.
77
- * @returns the budget in milliseconds.
81
+ * @returns the report point in milliseconds.
78
82
  */
79
83
  export declare function turnEndQuietMaxWait(env?: NodeJS.ProcessEnv): number;
80
84
  /**
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@linxin666/dsh-remote-bridge",
3
3
  "description": "DSH remote bridge: the host half serves protocol v1 over one exact /ios/v1 WebSocket route — session roster, history baseline, prompting, live turn increments with tool activity, interrupt, and in-process agent approval — to a device paired by a one-shot bootstrap token and a P-256 challenge-response, with the token endpoint admitted only from this machine; the browser half adds one sidebar-foot panel that shows that same one-shot token as a QR symbol and draws an interactive card inside the tool row without answering it, and adds no wire surface",
4
- "version": "0.4.11",
4
+ "version": "0.4.12",
5
5
  "icon": "./icon.svg",
6
6
  "type": "module",
7
7
  "engines": {
@@ -326,6 +326,13 @@ interface Subscription {
326
326
  */
327
327
  address: SessionAddress
328
328
  opened: Promise<Opening>
329
+ /**
330
+ * Whether this stream has delivered any frame after its opening one. The
331
+ * opening window is a moment, not a state: once the stream moves, that window
332
+ * is as old as the moment it was opened and can no longer answer for a session
333
+ * that has run a turn since.
334
+ */
335
+ advanced: boolean
329
336
  }
330
337
 
331
338
  /** The refusal half of every dispatch outcome. */
@@ -1356,7 +1363,7 @@ export class BridgeConnection {
1356
1363
  if (sessionId === undefined) return refusal(CODE_INVALID_ARGS, 'session.snapshot requires sessionId')
1357
1364
  const unfollowable = await this.#unfollowable(sessionId)
1358
1365
  if (unfollowable !== undefined) return refusal(CODE_SESSION_NOT_FOLLOWABLE, unfollowable)
1359
- const opening = await this.#awaitOpening(this.#ensureSubscription(sessionId))
1366
+ const opening = await this.#openingForBaseline(sessionId)
1360
1367
  if (!opening.ok) return refusal(opening.code, `session ${sessionId} produced no opening frame (${opening.msg})`)
1361
1368
  // A client that declared the trim capability chooses what it is sent, never
1362
1369
  // which turns it gets: the projection is trimmed inside each turn first, and
@@ -1479,7 +1486,7 @@ export class BridgeConnection {
1479
1486
  if (!budget.ok) return budget
1480
1487
  const unfollowable = await this.#unfollowable(sessionId)
1481
1488
  if (unfollowable !== undefined) return refusal(CODE_SESSION_NOT_FOLLOWABLE, unfollowable)
1482
- const opening = await this.#awaitOpening(this.#ensureSubscription(sessionId))
1489
+ const opening = await this.#openingForBaseline(sessionId)
1483
1490
  if (!opening.ok) return refusal(opening.code, `session ${sessionId} produced no opening frame (${opening.msg})`)
1484
1491
  const page = pageTurns(this.#projectionOf(opening.baseline.records), before, budget.maxBytes, (turns, nextBefore, hasMore) =>
1485
1492
  Buffer.byteLength(JSON.stringify(responseFrame(id, { turns, ...(nextBefore === undefined ? {} : { nextBefore }), hasMore })), 'utf8'))
@@ -1630,6 +1637,11 @@ export class BridgeConnection {
1630
1637
  if (!attachments.ok) return attachments
1631
1638
  const receipt = `${sessionId}\u0000${requestId}`
1632
1639
  if (this.#receipts.has(receipt)) return { ok: true, r: { accepted: true } }
1640
+ // A session the phone prompts is the phone's own work, which is the one thing that
1641
+ // makes its turn end announceable at all: the host's own subagent sessions are
1642
+ // dropped by the quiet gate unless they were prompted from here (§28/§29). The
1643
+ // fact is what the wire carried, not what the host accepted.
1644
+ this.#options.turnEndQuiet?.notePhonePrompt(sessionId)
1633
1645
  // A client may prompt without snapshotting first; the subscription is what
1634
1646
  // makes its own deltas reachable.
1635
1647
  this.#ensureSubscription(sessionId)
@@ -2429,6 +2441,7 @@ export class BridgeConnection {
2429
2441
  sessionId,
2430
2442
  controller: new AbortController(),
2431
2443
  address: this.#addressOf(sessionId),
2444
+ advanced: false,
2432
2445
  // Resolved without ever rejecting: a caller may subscribe without awaiting
2433
2446
  // the opening frame (`session.prompt` does exactly that), and an unobserved
2434
2447
  // rejection would take the whole host process down under node's default
@@ -2578,6 +2591,7 @@ export class BridgeConnection {
2578
2591
  for (;;) {
2579
2592
  const next = await iterator.next()
2580
2593
  if (next.done === true) return
2594
+ subscription.advanced = true
2581
2595
  const delta = deltaOfFollowFrame(next.value, this.#toolCalls, this.#messages, memory)
2582
2596
  if (delta === undefined) continue
2583
2597
  this.#emit(TOPIC_SESSION_DELTA, { sessionId: subscription.sessionId, ...delta })
@@ -2618,6 +2632,28 @@ export class BridgeConnection {
2618
2632
  this.#options.liveActivity?.noteTurnEnd(sessionId, reason)
2619
2633
  }
2620
2634
 
2635
+ /**
2636
+ * The opening frame a baseline read is answered from.
2637
+ *
2638
+ * A subscription that has delivered nothing since its opening frame still
2639
+ * holds the window that frame opened, so it is awaited and reused: a session
2640
+ * asked about while it stays silent costs one stream however often it is read.
2641
+ * One that HAS delivered a frame since has moved past that window, and reusing
2642
+ * it would answer a session that ran a turn on this very stream with the empty
2643
+ * baseline of the moment before that turn. Such a subscription is dropped —
2644
+ * its drain aborted and itself forgotten — and a fresh stream answers with the
2645
+ * window the harness opens now, which is the session as it is.
2646
+ * @param sessionId - the session whose baseline is wanted.
2647
+ * @returns that stream's opening frame, or why there is none.
2648
+ */
2649
+ async #openingForBaseline(sessionId: string): Promise<Opening> {
2650
+ const subscription = this.#ensureSubscription(sessionId)
2651
+ if (!subscription.advanced) return this.#awaitOpening(subscription)
2652
+ this.#forget(subscription)
2653
+ subscription.controller.abort()
2654
+ return this.#awaitOpening(this.#ensureSubscription(sessionId))
2655
+ }
2656
+
2621
2657
  /** Await a subscription's opening frame under a bounded wait. */
2622
2658
  async #awaitOpening(subscription: Subscription): Promise<Opening> {
2623
2659
  let timer: NodeJS.Timeout | undefined
@@ -560,7 +560,7 @@ export const CODE_COMMANDS_UNAVAILABLE = 'commands-unavailable'
560
560
  * it is a fact about this bridge, not about what a particular host mounts — and
561
561
  * only a call that needs the domain fails. A refusal the `dsh-agents` plugin
562
562
  * itself raised crosses with the plugin's own code instead (`team-not-found`,
563
- * `member-not-found`, `preset-unknown`, `workspace-required` and their
563
+ * `member-not-found`, `preset-unknown`, `workspace-unavailable` and their
564
564
  * neighbours).
565
565
  */
566
566
  export const CODE_SQUADS_UNAVAILABLE = 'squads-unavailable'