@linxin666/dsh-remote-bridge 0.4.8 → 0.4.9
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.i18n.yaml +2 -2
- package/README.md +50 -17
- package/README.zh.md +50 -17
- package/lib/client.js +274 -253
- package/lib/client.js.map +1 -1
- package/lib/index.js +6690 -2277
- package/lib/types/client/PairEntry.d.ts +2 -2
- package/lib/types/client/PairPanel.d.ts +10 -2
- package/lib/types/client/icons.d.ts +5 -13
- package/lib/types/client/locales.d.ts +10 -14
- package/lib/types/client/semantic.d.ts +9 -5
- package/lib/types/core/commands.d.ts +59 -0
- package/lib/types/core/connection.d.ts +68 -0
- package/lib/types/core/devices.d.ts +98 -2
- package/lib/types/core/hub.d.ts +65 -15
- package/lib/types/core/liveactivity.d.ts +324 -0
- package/lib/types/core/protocol.d.ts +260 -1
- package/lib/types/core/push.d.ts +178 -0
- package/lib/types/core/questions.d.ts +61 -9
- package/lib/types/core/session-meta.d.ts +55 -1
- package/lib/types/core/squads.d.ts +130 -0
- package/lib/types/core/usage-stats.d.ts +160 -0
- package/lib/types/core/usage.d.ts +294 -0
- package/lib/types/host/apns.d.ts +151 -0
- package/lib/types/host/squads-ledger.d.ts +39 -0
- package/lib/types/host/squads.d.ts +77 -0
- package/lib/types/host/usage-stats.d.ts +75 -0
- package/lib/types/host/watchers.d.ts +88 -0
- package/lib/types/index.d.ts +18 -2
- package/package.json +13 -13
- package/src/client/PairEntry.tsx +58 -31
- package/src/client/PairPanel.tsx +181 -97
- package/src/client/icons.tsx +17 -60
- package/src/client/locales.ts +15 -23
- package/src/client/panel.module.css +239 -186
- package/src/client/semantic.ts +10 -6
- package/src/core/commands.ts +95 -0
- package/src/core/connection.ts +646 -10
- package/src/core/devices.ts +221 -3
- package/src/core/hub.ts +362 -42
- package/src/core/liveactivity.ts +833 -0
- package/src/core/protocol.ts +294 -1
- package/src/core/push.ts +354 -0
- package/src/core/questions.ts +81 -10
- package/src/core/session-meta.ts +73 -1
- package/src/core/squads.ts +345 -0
- package/src/core/usage-stats.ts +424 -0
- package/src/core/usage.ts +937 -0
- package/src/core/wire.ts +8 -0
- package/src/host/apns.ts +320 -0
- package/src/host/squads-ledger.ts +105 -0
- package/src/host/squads.ts +206 -0
- package/src/host/usage-stats.ts +155 -0
- package/src/host/watchers.ts +272 -0
- package/src/index.ts +257 -8
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 宿主上 `dsh-usage` 插件的两条路由,按 `usage.stats` 需要的那一格读出来。
|
|
3
|
+
*
|
|
4
|
+
* 那个插件把台账挂在**同一个** web 服务上(`/api/dsh-usage/overview` 与
|
|
5
|
+
* `/api/dsh-usage/day`,见它的 `host/routes.ts`),所以这里不去进程里找它的服务
|
|
6
|
+
* ——它不发布任何 cordis 服务——而是对本机回环 origin 发一次真正的 GET。路径在这
|
|
7
|
+
* 里重写一遍而不是 import 过来:本包不依赖任何别的插件,能跨过来的只有冻结的路径
|
|
8
|
+
* 字符串。
|
|
9
|
+
*
|
|
10
|
+
* 端口从哪来:先问宿主自己的 `webServer.getOrigin()`(那是它已经绑定的地址,含
|
|
11
|
+
* 协议与端口,也是 `dsh-agents` 那一格用的同一条路);拿不到时退回
|
|
12
|
+
* `${protocol}//127.0.0.1:${port}` 的监听端口探测。后者只在这台宿主把监听绑在
|
|
13
|
+
* 回环地址上时才连得通,绑到别的网卡上会连不上——那时答案是 `probe-failed`,
|
|
14
|
+
* 而不是一个编出来的读数。
|
|
15
|
+
*
|
|
16
|
+
* 一次读的三种结局:答了、路由不存在、这次没读到。第三种带一句短原因。**404 是
|
|
17
|
+
* 第二种**:那台宿主没挂这个插件,是一件事实;而连接被拒、超时、非 200、读不出
|
|
18
|
+
* JSON 都是第三种。
|
|
19
|
+
* @module dsh-remote-bridge/host/usage-stats
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import type { UsageStatsOutcome, UsageStatsTransport } from '../core/usage-stats.ts'
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* 那个插件挂的两条路由;按它的 `USAGE_API_PREFIX` 拼出来。
|
|
26
|
+
*/
|
|
27
|
+
export const USAGE_OVERVIEW_PATH = '/api/dsh-usage/overview'
|
|
28
|
+
export const USAGE_DAY_PATH = '/api/dsh-usage/day'
|
|
29
|
+
|
|
30
|
+
/** 一次回环读的超时。那个插件从内存里答,这个时限只是不让一次卡住拖住连接。 */
|
|
31
|
+
export const USAGE_PROBE_TIMEOUT_MS = 5_000
|
|
32
|
+
|
|
33
|
+
/** 宿主 web 服务在这条路上要的那两格;结构读取,不导入它的类型。 */
|
|
34
|
+
export interface WebServerAddress {
|
|
35
|
+
/** 已经绑定的 origin,形如 `http://127.0.0.1:3080`;监听之前会抛。 */
|
|
36
|
+
getOrigin?(): string
|
|
37
|
+
/** 监听器说的协议,随配置而不是随请求。 */
|
|
38
|
+
readonly protocol?: string
|
|
39
|
+
/** 实际监听的端口(端口写 0 时是系统分配的那个);绑定之前是 undefined。 */
|
|
40
|
+
readonly port?: number
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** 构造 {@link LoopbackUsage} 的全部输入。 */
|
|
44
|
+
export interface LoopbackUsageOptions {
|
|
45
|
+
/** 每次读数都重新解析一次:这一行挂载时监听器可能还没有端口。 */
|
|
46
|
+
readonly origin: () => string | undefined
|
|
47
|
+
/** 出站调用的接缝;生产默认是本进程的 `fetch`。 */
|
|
48
|
+
readonly fetch?: typeof fetch
|
|
49
|
+
/** 一次读的超时;默认 {@link USAGE_PROBE_TIMEOUT_MS}。 */
|
|
50
|
+
readonly timeoutMs?: number
|
|
51
|
+
readonly log: (message: string) => void
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* 本机 web 服务的 origin。
|
|
56
|
+
*
|
|
57
|
+
* 先问宿主给的那个(它知道自己的绑定地址),拿不到就退回 127.0.0.1 上的监听端口。
|
|
58
|
+
* 两条都不成立时回 undefined,调用方据此答 `probe-failed`。
|
|
59
|
+
* @param server - 宿主 web 服务,可能还没挂载。
|
|
60
|
+
* @returns origin,或者 undefined。
|
|
61
|
+
*/
|
|
62
|
+
export function hostWebOrigin(server: WebServerAddress | undefined): string | undefined {
|
|
63
|
+
if (server === undefined) return undefined
|
|
64
|
+
try {
|
|
65
|
+
const origin = typeof server.getOrigin === 'function' ? server.getOrigin() : undefined
|
|
66
|
+
if (typeof origin === 'string' && origin !== '') return origin
|
|
67
|
+
} catch {
|
|
68
|
+
// 监听还没绑定:getOrigin() 会抛,落回下面的端口探测。
|
|
69
|
+
}
|
|
70
|
+
const port = server.port
|
|
71
|
+
if (typeof port !== 'number' || !Number.isInteger(port) || port <= 0) return undefined
|
|
72
|
+
return `${server.protocol === 'https:' ? 'https:' : 'http:'}//127.0.0.1:${port}`
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** 宿主那两条路由,走本机回环。 */
|
|
76
|
+
export class LoopbackUsage implements UsageStatsTransport {
|
|
77
|
+
readonly #options: LoopbackUsageOptions
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* @param options - origin 解析函数、出站调用与超时。
|
|
81
|
+
*/
|
|
82
|
+
constructor(options: LoopbackUsageOptions) {
|
|
83
|
+
this.#options = options
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* `GET /api/dsh-usage/overview`。
|
|
88
|
+
* @returns 宿主答的那份聚合,或者为什么没读到。
|
|
89
|
+
*/
|
|
90
|
+
overview(): Promise<UsageStatsOutcome> {
|
|
91
|
+
return this.#read(USAGE_OVERVIEW_PATH)
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* `GET /api/dsh-usage/day?date=<day>`。
|
|
96
|
+
* @param day - 本地日期键 `YYYY-MM-DD`。
|
|
97
|
+
* @returns 那一天的台账,或者为什么没读到。
|
|
98
|
+
*/
|
|
99
|
+
day(day: string): Promise<UsageStatsOutcome> {
|
|
100
|
+
return this.#read(`${USAGE_DAY_PATH}?date=${encodeURIComponent(day)}`)
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* 读一条路由。
|
|
105
|
+
*
|
|
106
|
+
* 没有 origin 是「这台宿主没有可寻址的 web 服务」,与插件没挂是两件事,所以它
|
|
107
|
+
* 落在 `failed` 上;只有 404 才落在 `missing` 上。
|
|
108
|
+
* @param path - 以 `/` 开头的路径,含查询串。
|
|
109
|
+
* @returns 读到的那一格。
|
|
110
|
+
*/
|
|
111
|
+
async #read(path: string): Promise<UsageStatsOutcome> {
|
|
112
|
+
const origin = this.#origin()
|
|
113
|
+
if (origin === undefined) return { kind: 'failed', reason: 'this host has no web server origin' }
|
|
114
|
+
const call = this.#options.fetch ?? globalThis.fetch
|
|
115
|
+
try {
|
|
116
|
+
const response = await call(`${origin}${path}`, {
|
|
117
|
+
headers: { accept: 'application/json' },
|
|
118
|
+
signal: AbortSignal.timeout(this.#timeout()),
|
|
119
|
+
})
|
|
120
|
+
// 路由不存在 = 那台宿主没挂这个插件。这是关于宿主的实施事实,不是错误。
|
|
121
|
+
if (response.status === 404) return { kind: 'missing' }
|
|
122
|
+
if (!response.ok) return { kind: 'failed', reason: `HTTP ${response.status}` }
|
|
123
|
+
const body: unknown = await response.json().catch(() => undefined)
|
|
124
|
+
return body === undefined ? { kind: 'failed', reason: 'unrecognized response shape' } : { kind: 'answer', body }
|
|
125
|
+
} catch (error) {
|
|
126
|
+
return { kind: 'failed', reason: shortReason(error) }
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** 这一次读要用的 origin;解析本身抛错按「没有 origin」处理。 */
|
|
131
|
+
#origin(): string | undefined {
|
|
132
|
+
try {
|
|
133
|
+
return this.#options.origin()
|
|
134
|
+
} catch (error) {
|
|
135
|
+
this.#options.log(`the host web origin could not be resolved: ${shortReason(error)}`)
|
|
136
|
+
return undefined
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** 一次读的超时。 */
|
|
141
|
+
#timeout(): number {
|
|
142
|
+
return this.#options.timeoutMs ?? USAGE_PROBE_TIMEOUT_MS
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* 一句短原因:过线的只有「这次为什么没读到」,不是一整条堆栈。
|
|
148
|
+
* @param error - 抛出来的东西。
|
|
149
|
+
* @returns 至多 120 个字符的一行。
|
|
150
|
+
*/
|
|
151
|
+
function shortReason(error: unknown): string {
|
|
152
|
+
const text = error instanceof Error ? error.message : String(error)
|
|
153
|
+
const line = text.split('\n')[0] ?? text
|
|
154
|
+
return line.length > 120 ? `${line.slice(0, 117)}...` : line
|
|
155
|
+
}
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The bridge's own follow streams: one per session that holds a live card.
|
|
3
|
+
*
|
|
4
|
+
* §28 and §29 both describe things this bridge must report while it is the only
|
|
5
|
+
* party still awake, and everything that reports them used to hang off a
|
|
6
|
+
* client's own stream: a turn end was observed only while this bridge was
|
|
7
|
+
* draining a follow stream for a connected phone. A suspended app has no such
|
|
8
|
+
* stream — its socket is closed and the subscription is aborted with the
|
|
9
|
+
* connection — so the card frozen on its lock screen kept saying "running" long
|
|
10
|
+
* after the turn was over, and no APNs delivery ever failed, because nothing was
|
|
11
|
+
* ever sent.
|
|
12
|
+
*
|
|
13
|
+
* A standing watcher is that missing party: for one session with at least one
|
|
14
|
+
* registered live-activity token this bridge opens its OWN follow stream, under
|
|
15
|
+
* the same in-process owner peer every other gateway call speaks for, and turns
|
|
16
|
+
* the one frame it cares about — `turn/end` — into the two things a card needs:
|
|
17
|
+
* §28's notification and §29's card end, each addressed to that session alone.
|
|
18
|
+
*
|
|
19
|
+
* Five rules keep that from becoming a second, unaccountable scheduler:
|
|
20
|
+
*
|
|
21
|
+
* - a watcher exists exactly while its session holds a card token, reconciled by
|
|
22
|
+
* {@link StandingWatchers.sync} from the roster rather than from any client
|
|
23
|
+
* frame;
|
|
24
|
+
* - at most {@link WATCHER_LIMIT} streams are open at once; past that a session
|
|
25
|
+
* is logged once and left unwatched, so a card on a session that never ends
|
|
26
|
+
* cannot grow the set without bound;
|
|
27
|
+
* - dedupe is inherited, not added: a client that is also following the same
|
|
28
|
+
* session sees the same turn end, and the two reports collapse in the layers
|
|
29
|
+
* that already own that rule — §28.5's `(sessionId, event)` window and §29's
|
|
30
|
+
* identical-content key. No third window is introduced here;
|
|
31
|
+
* - a stream that ends on its own is re-armed after {@link WATCHER_REOPEN_MS},
|
|
32
|
+
* because the next turn is the next thing a card has to show;
|
|
33
|
+
* - nothing a watcher does can reach a client frame: every failure is one log
|
|
34
|
+
* line, and a stream that cannot be opened is dropped rather than retried in a
|
|
35
|
+
* tight loop.
|
|
36
|
+
* @module dsh-remote-bridge/host/watchers
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
import { SNAPSHOT_MAX_MESSAGES } from '../core/connection.ts'
|
|
40
|
+
import { deltaOfFollowFrame, MessageIndex, readFollowBaseline, SpawnCallIndex, ToolCallIndex } from '../core/dsh-frames.ts'
|
|
41
|
+
import { failureText, withServiceUnavailableRetry } from '../core/gateway-errors.ts'
|
|
42
|
+
import type { LiveActivityNotifier } from '../core/liveactivity.ts'
|
|
43
|
+
import { pushEventOfTurnEnd, type PushNotifier } from '../core/push.ts'
|
|
44
|
+
import { sessionAddress, wireArgs, type BridgeGateway, type GatewayPeer } from '../core/wire.ts'
|
|
45
|
+
|
|
46
|
+
/** Most standing streams this bridge keeps open at once. */
|
|
47
|
+
export const WATCHER_LIMIT = 64
|
|
48
|
+
/** How long a watcher waits before re-opening a stream that ended on its own. */
|
|
49
|
+
export const WATCHER_REOPEN_MS = 1_000
|
|
50
|
+
|
|
51
|
+
export interface StandingWatcherOptions {
|
|
52
|
+
/** The host's gateway, the same one the connections speak through. */
|
|
53
|
+
readonly gateway: BridgeGateway
|
|
54
|
+
/** The in-process owner peer every call of this bridge speaks for. */
|
|
55
|
+
readonly peer: GatewayPeer
|
|
56
|
+
/**
|
|
57
|
+
* Sessions that currently hold at least one registered live-activity token,
|
|
58
|
+
* read from the roster on every reconcile.
|
|
59
|
+
*/
|
|
60
|
+
readonly sessions: () => readonly string[]
|
|
61
|
+
/** The card path of §29; absent is a bridge with no signing key. */
|
|
62
|
+
readonly liveActivity?: LiveActivityNotifier
|
|
63
|
+
/** The notification path of §28; absent for the same reason. */
|
|
64
|
+
readonly push?: PushNotifier
|
|
65
|
+
readonly log: (message: string) => void
|
|
66
|
+
readonly limit?: number
|
|
67
|
+
readonly reopenMs?: number
|
|
68
|
+
readonly maxMessages?: number
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** One open stream, and the handle that closes it. */
|
|
72
|
+
interface Watching {
|
|
73
|
+
readonly controller: AbortController
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* The bridge's stand-in for a client that is no longer there.
|
|
78
|
+
*
|
|
79
|
+
* Deliberately inert when neither push path is configured: {@link sync} returns
|
|
80
|
+
* without opening anything, so a bridge without an Apple signing key keeps the
|
|
81
|
+
* exact stream count it had before this module existed.
|
|
82
|
+
*/
|
|
83
|
+
export class StandingWatchers {
|
|
84
|
+
readonly #options: StandingWatcherOptions
|
|
85
|
+
/** Open streams by session id. */
|
|
86
|
+
readonly #open = new Map<string, Watching>()
|
|
87
|
+
/** Sessions a reconcile had to refuse for the cap, so each is logged once. */
|
|
88
|
+
readonly #refused = new Set<string>()
|
|
89
|
+
/** Pending re-arm timers, cleared on dispose. */
|
|
90
|
+
readonly #timers = new Set<NodeJS.Timeout>()
|
|
91
|
+
#disposed = false
|
|
92
|
+
|
|
93
|
+
constructor(options: StandingWatcherOptions) {
|
|
94
|
+
this.#options = options
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** @returns how many standing streams are open right now. */
|
|
98
|
+
get size(): number {
|
|
99
|
+
return this.#open.size
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** @returns whether this bridge has any path worth opening a stream for. */
|
|
103
|
+
get enabled(): boolean {
|
|
104
|
+
return this.#options.liveActivity !== undefined || this.#options.push !== undefined
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Reconcile the open streams with the sessions that hold a card right now.
|
|
109
|
+
*
|
|
110
|
+
* Called when the roster changes (a registration arrived, a dead token was
|
|
111
|
+
* retired) and when a stream ends. Idempotent, and safe to call before the
|
|
112
|
+
* roster has been read: no session with a token means nothing to watch.
|
|
113
|
+
*/
|
|
114
|
+
sync(): void {
|
|
115
|
+
if (this.#disposed || !this.enabled) return
|
|
116
|
+
let wanted: readonly string[]
|
|
117
|
+
try {
|
|
118
|
+
wanted = this.#options.sessions()
|
|
119
|
+
} catch (error) {
|
|
120
|
+
this.#options.log(`watcher reconcile failed: ${failureText(error)}`)
|
|
121
|
+
return
|
|
122
|
+
}
|
|
123
|
+
const desired = new Set(wanted)
|
|
124
|
+
for (const [sessionId, watching] of this.#open) {
|
|
125
|
+
if (desired.has(sessionId)) continue
|
|
126
|
+
this.#open.delete(sessionId)
|
|
127
|
+
watching.controller.abort()
|
|
128
|
+
this.#options.log(`watcher close session=${sessionId} reason=cards-gone`)
|
|
129
|
+
}
|
|
130
|
+
const limit = this.#options.limit ?? WATCHER_LIMIT
|
|
131
|
+
for (const sessionId of desired) {
|
|
132
|
+
if (this.#open.has(sessionId)) continue
|
|
133
|
+
if (this.#open.size >= limit) {
|
|
134
|
+
if (!this.#refused.has(sessionId)) {
|
|
135
|
+
this.#refused.add(sessionId)
|
|
136
|
+
this.#options.log(`watcher refused session=${sessionId} reason=limit(${String(limit)})`)
|
|
137
|
+
}
|
|
138
|
+
continue
|
|
139
|
+
}
|
|
140
|
+
this.#watch(sessionId)
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Close every stream and drop every pending re-arm. Idempotent. */
|
|
145
|
+
dispose(): void {
|
|
146
|
+
if (this.#disposed) return
|
|
147
|
+
this.#disposed = true
|
|
148
|
+
for (const timer of this.#timers) clearTimeout(timer)
|
|
149
|
+
this.#timers.clear()
|
|
150
|
+
for (const watching of this.#open.values()) watching.controller.abort()
|
|
151
|
+
this.#open.clear()
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Open one session's stream and start consuming it. */
|
|
155
|
+
#watch(sessionId: string): void {
|
|
156
|
+
const watching: Watching = { controller: new AbortController() }
|
|
157
|
+
this.#open.set(sessionId, watching)
|
|
158
|
+
this.#options.log(`watcher open session=${sessionId} reason=cards`)
|
|
159
|
+
void this.#run(sessionId, watching).catch((error: unknown) => {
|
|
160
|
+
// A watch that cannot even be started is one line: the caller is this
|
|
161
|
+
// bridge itself, and there is no frame to fail.
|
|
162
|
+
this.#options.log(`watcher failed session=${sessionId}: ${failureText(error)}`)
|
|
163
|
+
})
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Consume one session's stream until it ends or is aborted. */
|
|
167
|
+
async #run(sessionId: string, watching: Watching): Promise<void> {
|
|
168
|
+
const signal = watching.controller.signal
|
|
169
|
+
let iterator: AsyncIterator<unknown>
|
|
170
|
+
try {
|
|
171
|
+
const stream = await withServiceUnavailableRetry(() => this.#options.gateway.stream({
|
|
172
|
+
namespace: 'session',
|
|
173
|
+
method: 'follow',
|
|
174
|
+
args: wireArgs('session', 'follow', {
|
|
175
|
+
address: sessionAddress(sessionId),
|
|
176
|
+
// The shape a connection opens: one stream per session carries both
|
|
177
|
+
// the baseline and the process-local deltas. The watcher needs no
|
|
178
|
+
// baseline — attaching is what makes it a party.
|
|
179
|
+
assistantStream: true,
|
|
180
|
+
maxMessages: this.#options.maxMessages ?? SNAPSHOT_MAX_MESSAGES,
|
|
181
|
+
}),
|
|
182
|
+
peer: this.#options.peer,
|
|
183
|
+
signal,
|
|
184
|
+
}))
|
|
185
|
+
iterator = stream[Symbol.asyncIterator]()
|
|
186
|
+
} catch (error) {
|
|
187
|
+
this.#options.log(`watcher stream refused session=${sessionId}: ${failureText(error)}`)
|
|
188
|
+
// Not re-armed: a stream the host refuses would be refused again on every
|
|
189
|
+
// retry, and the next roster change is the honest trigger to try once more.
|
|
190
|
+
this.#settle(sessionId, watching, false)
|
|
191
|
+
return
|
|
192
|
+
}
|
|
193
|
+
const toolCalls = new ToolCallIndex()
|
|
194
|
+
const messages = new MessageIndex()
|
|
195
|
+
// No capability gate here: a watcher publishes no frame, so the thread kind
|
|
196
|
+
// of a delta is none of its business.
|
|
197
|
+
const memory = { subagentThread: false, spawnCalls: new SpawnCallIndex() }
|
|
198
|
+
try {
|
|
199
|
+
const first = await iterator.next()
|
|
200
|
+
if (first.done === true || readFollowBaseline(first.value) === undefined) {
|
|
201
|
+
this.#options.log(`watcher stream unusable session=${sessionId}`)
|
|
202
|
+
await iterator.return?.()
|
|
203
|
+
this.#settle(sessionId, watching, false)
|
|
204
|
+
return
|
|
205
|
+
}
|
|
206
|
+
for (;;) {
|
|
207
|
+
const next = await iterator.next()
|
|
208
|
+
if (next.done === true) break
|
|
209
|
+
if (signal.aborted) break
|
|
210
|
+
const delta = deltaOfFollowFrame(next.value, toolCalls, messages, memory)
|
|
211
|
+
if (delta === undefined || delta.kind !== 'turn-end') continue
|
|
212
|
+
this.#turnEnded(sessionId, delta.reason)
|
|
213
|
+
}
|
|
214
|
+
} catch (error) {
|
|
215
|
+
if (!signal.aborted) this.#options.log(`watcher stream ended session=${sessionId}: ${failureText(error)}`)
|
|
216
|
+
} finally {
|
|
217
|
+
this.#settle(sessionId, watching)
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Report one turn end to both channels that need it.
|
|
223
|
+
*
|
|
224
|
+
* Both, on purpose: §28's notification is what wakes a phone that is not
|
|
225
|
+
* holding a socket, and §29's card end is what clears a lock screen. Reporting
|
|
226
|
+
* only one of them leaves the other surface stale, which is the exact state
|
|
227
|
+
* this module exists to end.
|
|
228
|
+
*/
|
|
229
|
+
#turnEnded(sessionId: string, reason: string): void {
|
|
230
|
+
try {
|
|
231
|
+
this.#options.push?.notify(pushEventOfTurnEnd(reason), sessionId)
|
|
232
|
+
this.#options.liveActivity?.noteTurnEnd(sessionId, reason)
|
|
233
|
+
const pushed = this.#options.liveActivity?.enabled === true ? 'card' : 'notification-only'
|
|
234
|
+
this.#options.log(`watcher turn-end session=${sessionId} reason=${reason} pushed=${pushed}`)
|
|
235
|
+
} catch (error) {
|
|
236
|
+
this.#options.log(`watcher turn-end session=${sessionId} failed: ${failureText(error)}`)
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Forget one stream's handle, and re-arm it when that is the right answer.
|
|
242
|
+
* @param sessionId - the session whose stream is over.
|
|
243
|
+
* @param watching - the exact stream being settled, so a newer one is untouched.
|
|
244
|
+
* @param rearm - whether a stream that was open and then ended should come back.
|
|
245
|
+
*/
|
|
246
|
+
#settle(sessionId: string, watching: Watching, rearm = true): void {
|
|
247
|
+
watching.controller.abort()
|
|
248
|
+
if (this.#open.get(sessionId) === watching) this.#open.delete(sessionId)
|
|
249
|
+
if (rearm) this.#rearm(sessionId)
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Schedule one reconcile, so a session still holding a card gets its stream
|
|
254
|
+
* back after the stream it was on ended.
|
|
255
|
+
*/
|
|
256
|
+
#rearm(sessionId: string): void {
|
|
257
|
+
if (this.#disposed || this.#open.has(sessionId)) return
|
|
258
|
+
let wanted = false
|
|
259
|
+
try {
|
|
260
|
+
wanted = this.#options.sessions().includes(sessionId)
|
|
261
|
+
} catch {
|
|
262
|
+
wanted = false
|
|
263
|
+
}
|
|
264
|
+
if (!wanted) return
|
|
265
|
+
const timer = setTimeout(() => {
|
|
266
|
+
this.#timers.delete(timer)
|
|
267
|
+
this.sync()
|
|
268
|
+
}, this.#options.reopenMs ?? WATCHER_REOPEN_MS)
|
|
269
|
+
timer.unref?.()
|
|
270
|
+
this.#timers.add(timer)
|
|
271
|
+
}
|
|
272
|
+
}
|