@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.
Files changed (55) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +50 -17
  3. package/README.zh.md +50 -17
  4. package/lib/client.js +274 -253
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +6690 -2277
  7. package/lib/types/client/PairEntry.d.ts +2 -2
  8. package/lib/types/client/PairPanel.d.ts +10 -2
  9. package/lib/types/client/icons.d.ts +5 -13
  10. package/lib/types/client/locales.d.ts +10 -14
  11. package/lib/types/client/semantic.d.ts +9 -5
  12. package/lib/types/core/commands.d.ts +59 -0
  13. package/lib/types/core/connection.d.ts +68 -0
  14. package/lib/types/core/devices.d.ts +98 -2
  15. package/lib/types/core/hub.d.ts +65 -15
  16. package/lib/types/core/liveactivity.d.ts +324 -0
  17. package/lib/types/core/protocol.d.ts +260 -1
  18. package/lib/types/core/push.d.ts +178 -0
  19. package/lib/types/core/questions.d.ts +61 -9
  20. package/lib/types/core/session-meta.d.ts +55 -1
  21. package/lib/types/core/squads.d.ts +130 -0
  22. package/lib/types/core/usage-stats.d.ts +160 -0
  23. package/lib/types/core/usage.d.ts +294 -0
  24. package/lib/types/host/apns.d.ts +151 -0
  25. package/lib/types/host/squads-ledger.d.ts +39 -0
  26. package/lib/types/host/squads.d.ts +77 -0
  27. package/lib/types/host/usage-stats.d.ts +75 -0
  28. package/lib/types/host/watchers.d.ts +88 -0
  29. package/lib/types/index.d.ts +18 -2
  30. package/package.json +13 -13
  31. package/src/client/PairEntry.tsx +58 -31
  32. package/src/client/PairPanel.tsx +181 -97
  33. package/src/client/icons.tsx +17 -60
  34. package/src/client/locales.ts +15 -23
  35. package/src/client/panel.module.css +239 -186
  36. package/src/client/semantic.ts +10 -6
  37. package/src/core/commands.ts +95 -0
  38. package/src/core/connection.ts +646 -10
  39. package/src/core/devices.ts +221 -3
  40. package/src/core/hub.ts +362 -42
  41. package/src/core/liveactivity.ts +833 -0
  42. package/src/core/protocol.ts +294 -1
  43. package/src/core/push.ts +354 -0
  44. package/src/core/questions.ts +81 -10
  45. package/src/core/session-meta.ts +73 -1
  46. package/src/core/squads.ts +345 -0
  47. package/src/core/usage-stats.ts +424 -0
  48. package/src/core/usage.ts +937 -0
  49. package/src/core/wire.ts +8 -0
  50. package/src/host/apns.ts +320 -0
  51. package/src/host/squads-ledger.ts +105 -0
  52. package/src/host/squads.ts +206 -0
  53. package/src/host/usage-stats.ts +155 -0
  54. package/src/host/watchers.ts +272 -0
  55. package/src/index.ts +257 -8
@@ -0,0 +1,178 @@
1
+ /**
2
+ * What this bridge tells a phone that is not listening.
3
+ *
4
+ * Every fact a phone needs already has a read on the wire — a roster, a
5
+ * baseline, a question list — and a notification is not one of them. It is the
6
+ * `turn ended` or `something is waiting` event, delivered by APNs to a device
7
+ * whose socket is closed, and nothing else: this module deliberately holds no
8
+ * session state, publishes no topic, and answers no method. A client that acts
9
+ * on a notification still has to read the fact behind it (protocol §28).
10
+ *
11
+ * Three rules live here, so the sender beside it cannot disagree about them:
12
+ *
13
+ * - the payload carries a session's NAME, its workspace's short name, the state
14
+ * and one deep link. Never a message, a tool output, a file name or a
15
+ * question's body — a notification crosses Apple's servers and sits on a lock
16
+ * screen, which is the last place session content should be;
17
+ * - the same `(sessionId, event)` inside {@link PUSH_DEDUPE_MS} is one
18
+ * notification, because two phones following one session both see the same
19
+ * turn end and the user has one lock screen;
20
+ * - a failed delivery is logged and dropped. Nothing here is awaited by the
21
+ * delta path, so a broken APNs connection cannot delay, reorder or suppress a
22
+ * frame that a connected phone is waiting for.
23
+ * @module dsh-remote-bridge/core/push
24
+ */
25
+ /** One thing a notification can be about. */
26
+ export type PushEvent = 'turn-end' | 'turn-error' | 'question' | 'approval';
27
+ /** Window inside which the same `(sessionId, event)` is one notification. */
28
+ export declare const PUSH_DEDUPE_MS = 30000;
29
+ /** Shortest gap between two notifications about the same session. */
30
+ export declare const PUSH_SESSION_INTERVAL_MS = 10000;
31
+ /** Most notifications this bridge sends in any rolling minute. */
32
+ export declare const PUSH_GLOBAL_PER_MINUTE = 30;
33
+ /** Sessions whose workspace short name is remembered for the payload. */
34
+ export declare const PUSH_WORKSPACE_LIMIT = 512;
35
+ /** The only deep-link form this channel emits. */
36
+ export declare const PUSH_DEEP_LINK_PREFIX = "whale://session/";
37
+ /** One device a notification can be addressed to. */
38
+ export interface PushAddress {
39
+ readonly deviceToken: string;
40
+ readonly environment: 'sandbox' | 'production';
41
+ readonly bundle: string;
42
+ readonly locale?: string;
43
+ }
44
+ /** The request body one APNs delivery carries (protocol §28.4). */
45
+ export interface PushNotification {
46
+ readonly aps: {
47
+ readonly alert: {
48
+ readonly title: string;
49
+ readonly body: string;
50
+ };
51
+ readonly sound: 'default';
52
+ };
53
+ /** Workspace short name; absent when this bridge cannot resolve one. */
54
+ readonly w?: string;
55
+ readonly s: string;
56
+ readonly st: PushEvent;
57
+ readonly url: string;
58
+ }
59
+ /** What one delivery attempt reported. */
60
+ export interface PushSendResult {
61
+ readonly ok: boolean;
62
+ /** The status APNs answered, when it answered at all. */
63
+ readonly status?: number;
64
+ /** The reason APNs named, or this bridge's own note. */
65
+ readonly reason?: string;
66
+ }
67
+ /** One delivery a sender refused, in the words the bridge needs to read it. */
68
+ export interface PushDeliveryFailure {
69
+ /** The registration APNs refused: the roster row holding it is a device that no longer exists. */
70
+ readonly deviceToken: string;
71
+ /** The status APNs answered, when it answered at all. */
72
+ readonly status?: number;
73
+ /** The reason APNs named, or this bridge's own note. */
74
+ readonly reason?: string;
75
+ }
76
+ /** What one {@link PushNotifier.notify} ended up doing, once every attempt settled. */
77
+ export interface PushDeliveryReport {
78
+ /** How many devices took the notification. */
79
+ readonly delivered: number;
80
+ /** Every attempt that did not land, in target order. */
81
+ readonly failures: readonly PushDeliveryFailure[];
82
+ }
83
+ /**
84
+ * @param failure - one refused delivery.
85
+ * @returns whether the registration behind it is dead for good.
86
+ *
87
+ * APNs says a token will never work again in three ways: 410 with
88
+ * `Unregistered`, and 400 with `Unregistered` or `BadDeviceToken`. All three are
89
+ * final facts about the registration — the app was removed, or this token belongs
90
+ * to another environment or bundle — so it is cleaned up instead of retried, and
91
+ * a claim held for it is a claim held for a phone that cannot come back.
92
+ */
93
+ export declare function isDeadPushToken(failure: PushDeliveryFailure): boolean;
94
+ /** Whatever actually reaches a device; the APNs client implements this. */
95
+ export interface PushSender {
96
+ send(target: PushAddress, notification: PushNotification): Promise<PushSendResult>;
97
+ }
98
+ /** What the payload builder may say about one session. */
99
+ export interface PushLabels {
100
+ readonly title?: string;
101
+ readonly workspace?: string;
102
+ }
103
+ export interface PushNotifierOptions {
104
+ /** The devices that asked to be notified, read per event. */
105
+ readonly targets: () => readonly PushAddress[];
106
+ /** The sender; absent is a bridge with no signing key, and then nothing happens. */
107
+ readonly sender?: PushSender;
108
+ /** The session's own title (§26's source), read per event. */
109
+ readonly titles?: (sessionId: string) => string | undefined;
110
+ readonly now?: () => number;
111
+ readonly log?: (message: string) => void;
112
+ readonly dedupeMs?: number;
113
+ readonly sessionIntervalMs?: number;
114
+ readonly globalPerMinute?: number;
115
+ }
116
+ /**
117
+ * The notification the channel sends for one event (protocol §28.4).
118
+ *
119
+ * Pure, and exported so the shape can be asserted without a sender: the keys
120
+ * are the contract, and the absence of any body text is the property that
121
+ * matters most.
122
+ * @param event - what happened.
123
+ * @param sessionId - the session it happened to.
124
+ * @param labels - the name and workspace short name, when the bridge holds them.
125
+ * @returns the exact payload an APNs delivery carries.
126
+ */
127
+ export declare function buildPushNotification(event: PushEvent, sessionId: string, labels?: PushLabels): PushNotification;
128
+ /**
129
+ * Which event one `turn-end` delta is.
130
+ * @param reason - the host's own reason for ending the turn.
131
+ * @returns the normal end for `completed`, the abnormal one for every other
132
+ * value — including `unknown`, which is what an unreadable reason reports.
133
+ */
134
+ export declare function pushEventOfTurnEnd(reason: string): PushEvent;
135
+ /**
136
+ * The bridge's outbound notification path.
137
+ *
138
+ * Deliberately inert when no sender is configured: {@link enabled} is false, no
139
+ * target is ever read and no clock is ever consulted, so an unconfigured bridge
140
+ * behaves — byte for byte, frame for frame — exactly as it did before this
141
+ * channel existed.
142
+ */
143
+ export declare class PushNotifier {
144
+ #private;
145
+ constructor(options: PushNotifierOptions);
146
+ /** @returns whether this bridge will actually deliver anything. */
147
+ get enabled(): boolean;
148
+ /**
149
+ * Remember the workspace each session belongs to, from a roster this bridge
150
+ * just served.
151
+ *
152
+ * A notification's `w` is the only label the bridge cannot read from the
153
+ * title service, and asking the host for a roster on every turn end would put
154
+ * a gateway call on the notification path. The rows are already in hand when a
155
+ * phone lists them, so the short name is picked up there and kept bounded; a
156
+ * session never listed simply gets a payload without `w`.
157
+ * @param rows - the roster rows that were just built for a client.
158
+ */
159
+ noteSessions(rows: readonly {
160
+ readonly id: string;
161
+ readonly cwd?: string;
162
+ }[]): void;
163
+ /**
164
+ * Announce one event to every registered device.
165
+ *
166
+ * Returns before anything is sent: delivery starts on a fresh microtask, so a
167
+ * caller on the delta path never awaits an APNs round trip and a sender that
168
+ * throws cannot reach it.
169
+ * @param event - what happened.
170
+ * @param sessionId - the session it happened to.
171
+ * @param onReport - receives how the announcement ended, once every attempt has
172
+ * settled. A caller that held something for a phone — an offline claim (§32) —
173
+ * needs to know whether any phone was actually told, and may not block the
174
+ * caller's own path on an APNs round trip to find out. Not called when nothing
175
+ * was attempted: no sender, no target, or a rate limit that dropped this event.
176
+ */
177
+ notify(event: PushEvent, sessionId: string, onReport?: (report: PushDeliveryReport) => void): void;
178
+ }
@@ -67,12 +67,59 @@ export interface QuestionAnswerItem {
67
67
  export interface QuestionAnswer {
68
68
  readonly answers: readonly QuestionAnswerItem[];
69
69
  }
70
+ /**
71
+ * The `question.request` payload for one claim, and the `payload` of every
72
+ * `question.list` entry.
73
+ *
74
+ * One function for both so the card a phone was handed and the card it reads back
75
+ * out of a list cannot drift apart: `expiresAt` appears only once the claim
76
+ * learned the host's own deadline, and a blocking ask publishes no such key at
77
+ * all rather than an empty or null one.
78
+ * @param state - whether the foreground ask still holds the question.
79
+ * @param question - the claim being published.
80
+ * @returns the frozen payload body.
81
+ */
82
+ export declare function questionPayload(state: QuestionState, question: ClaimedQuestionView): QuestionRequestPayload;
83
+ /**
84
+ * The identity a client knows one question card by.
85
+ *
86
+ * The same `sessionId/callId` pair the phone already derives for its own card,
87
+ * so a list entry and the card it describes are compared as one name instead of
88
+ * two fields that could be recombined differently on each side.
89
+ * @param sessionId - the session that asked.
90
+ * @param callId - the wire call id the client answers with.
91
+ * @returns the card key.
92
+ */
93
+ export declare function questionKey(sessionId: string, callId: string): string;
94
+ /** One question this bridge still holds, as `question.list` publishes it. */
95
+ export interface ListedQuestion {
96
+ /** {@link questionKey}: the card identity the client holds it under. */
97
+ readonly key: string;
98
+ readonly sessionId: string;
99
+ /** `open` or `continued`; a settled question is not held and never listed. */
100
+ readonly state: QuestionState;
101
+ /** The `question.request` payload, byte for byte the shape that channel froze. */
102
+ readonly payload: QuestionRequestPayload;
103
+ }
104
+ /**
105
+ * The body of one `question.list` answer.
106
+ *
107
+ * `complete` is what a client is allowed to act on: only a complete list may
108
+ * retire a card it does not carry, so a bridge that could answer only part of the
109
+ * set must say `false` rather than let the difference read as "the question is
110
+ * over".
111
+ */
112
+ export interface QuestionListPayload {
113
+ readonly questions: readonly ListedQuestion[];
114
+ readonly complete: boolean;
115
+ }
70
116
  /** Whether a question still holds the foreground ask, or only its late reply. */
71
117
  /**
72
118
  * `open` while the ask is still waiting, `continued` once the host's foreground
73
119
  * wait ended but a late answer can still be steered in, and `settled` as the
74
- * one-way notice that the phone's card is over — the host's own UI answered it or
75
- * the last paired client left. `settled` is published, never held.
120
+ * one-way notice that the phone's card is over — the host's own UI answered it, or
121
+ * none was left to answer it once the claim's grace window ended. `settled` is
122
+ * published, never held.
76
123
  */
77
124
  export type QuestionState = 'open' | 'continued' | 'settled';
78
125
  /** `question.request`'s payload, as frozen by the contract. */
@@ -260,13 +307,17 @@ export declare class QuestionClaims {
260
307
  */
261
308
  answer(sessionId: string, callId: string, answer: QuestionAnswer): Promise<QuestionReply>;
262
309
  /**
263
- * Every claim still waiting on an answer.
310
+ * Every question this bridge still holds, as `question.list` publishes it.
264
311
  *
265
- * A phone that connects after the question was raised never saw the original
266
- * broadcast, so it has to be handed the live claims again — otherwise the
267
- * question sits on the host with an answerable card nowhere.
312
+ * The claim registry IS the answer: a question leaves it the moment it is
313
+ * answered, settled by the host's own UI, withdrawn with the last paired phone
314
+ * or expired, so a card missing from this list is a card no one can answer any
315
+ * more. Both live states are listed — `continued` is still answerable through
316
+ * the host's late-answer path — and a settled question is never here, because
317
+ * it is never held.
318
+ * @returns one entry per held claim, in claim order.
268
319
  */
269
- openClaims(): readonly ClaimedQuestionView[];
320
+ listed(): readonly ListedQuestion[];
270
321
  /**
271
322
  * Withdraw the named questions, delegating each to the next answerer.
272
323
  * @returns how many were still open and therefore delegated.
@@ -274,8 +325,9 @@ export declare class QuestionClaims {
274
325
  withdraw(callIds: readonly string[]): number;
275
326
  /**
276
327
  * Withdraw every claim, delegating each open question to the next answerer.
277
- * Called when the last paired phone goes away and when the bridge unloads: a
278
- * question nobody can answer must not hold the agent until its own deadline.
328
+ * Called when the last paired phone has been gone long enough that no grace
329
+ * window is still running, and when the bridge unloads: a question nobody can
330
+ * answer must not hold the agent until its own deadline.
279
331
  * @returns how many questions were still open.
280
332
  */
281
333
  withdrawAll(): number;
@@ -32,18 +32,56 @@ export interface SessionTitleFace {
32
32
  export interface ArchiveSetFace {
33
33
  readonly archivedSessionIds: readonly string[];
34
34
  }
35
+ /**
36
+ * One workspace registration, as far as `workspace.list` publishes it.
37
+ *
38
+ * The host's entity carries more — its `sessionIds` account above all — and the
39
+ * face deliberately does not declare it: a row this bridge publishes must not be
40
+ * able to carry an array that grows with the session count.
41
+ */
42
+ export interface WorkspaceFace {
43
+ readonly id: string;
44
+ readonly path: string;
45
+ readonly title: string;
46
+ readonly createdAt?: string;
47
+ readonly updatedAt?: string;
48
+ }
49
+ /**
50
+ * The slice of `ctx.workspaceRegistry` `workspace.list` reads: the registry
51
+ * itself.
52
+ *
53
+ * Wider than {@link ArchiveSetFace} by the ordered projection and the pin set,
54
+ * because one method publishes all three: a client pins a session and reads
55
+ * both sets back in one frame. Every member is synchronous — `list()` answers a
56
+ * fresh array and both sets are getters over the durable registry — which is
57
+ * what lets the answer be built without awaiting anything.
58
+ */
59
+ export interface WorkspacesFace extends ArchiveSetFace {
60
+ list(): readonly WorkspaceFace[];
61
+ readonly pinnedSessionIds: readonly string[];
62
+ }
63
+ /** The body `workspace.list` answers. */
64
+ export interface WorkspaceListAnswer {
65
+ readonly workspaces: readonly WorkspaceFace[];
66
+ readonly archivedSessionIds: readonly string[];
67
+ readonly pinnedSessionIds: readonly string[];
68
+ }
35
69
  /**
36
70
  * The in-process services one metadata read may use.
37
71
  *
38
72
  * Every field is optional on purpose. The bridge does not require the title or
39
73
  * workspace plugins to be installed — the protocol's roster and title methods
40
74
  * stay answerable with them absent, and a field that is missing degrades one
41
- * key of one row instead of failing a method.
75
+ * key of one row instead of failing a method. `workspaces` is the member that
76
+ * breaks that rule on purpose: `workspace.list` exists only to publish the
77
+ * registry, so its absence is reported as a host without one rather than
78
+ * answered with an empty list.
42
79
  */
43
80
  export interface SessionMetaFaces {
44
81
  readonly sessions?: SessionStoreFace | undefined;
45
82
  readonly titles?: SessionTitleFace | undefined;
46
83
  readonly archive?: ArchiveSetFace | undefined;
84
+ readonly workspaces?: WorkspacesFace | undefined;
47
85
  }
48
86
  /** Largest id batch one `session.titles` call accepts. */
49
87
  export declare const TITLES_MAX_IDS = 100;
@@ -102,4 +140,20 @@ export declare class SessionMeta {
102
140
  * @returns the archived session ids, or undefined when the registry is unavailable.
103
141
  */
104
142
  archiveSet(): ReadonlySet<string> | undefined;
143
+ /**
144
+ * The host's workspaces and its two registry-global session sets.
145
+ *
146
+ * One synchronous projection and nothing more: `list()` already answers a
147
+ * fresh array in registry order, and both sets are getters over the durable
148
+ * registry, so this read awaits nothing, opens no follow stream and touches no
149
+ * persistence. Workspaces are neither sorted nor filtered — the registry's own
150
+ * order is the display order — and a row carries exactly the fields protocol
151
+ * v1 names, `sessionIds` never among them.
152
+ *
153
+ * An unmounted registry answers undefined instead of an empty list: "this host
154
+ * has no workspaces" and "this host has no registry to ask" are two different
155
+ * facts, and only the caller can say which one it must report.
156
+ * @returns the answer, or undefined when this host composes no workspace registry.
157
+ */
158
+ workspaceList(): WorkspaceListAnswer | undefined;
105
159
  }
@@ -0,0 +1,130 @@
1
+ /**
2
+ * The squads channel: the squad domain of the `dsh-agents` plugin — its
3
+ * definitions and the runs that launch sessions — as a phone reads and drives
4
+ * it.
5
+ *
6
+ * Nothing about a squad is modelled here. A squad is the plugin's own team row
7
+ * with the definition timestamps dropped, a run is the plugin's own run record
8
+ * with the goal it was given dropped, and a refusal the plugin raised crosses
9
+ * with the plugin's own code. What this module owns is the mapping onto the
10
+ * frozen `squads.v1` bodies plus the transport seam a Host half implements to
11
+ * reach the domain.
12
+ *
13
+ * The seam answers the plugin's rows unread (`unknown`), so one mapping serves
14
+ * both ways a Host can reach them: the plugin's HTTP routes over loopback, and
15
+ * the read-only ledger fallback. A row this build cannot read is refused rather
16
+ * than repaired, because a repaired squad is a squad the user never wrote.
17
+ * @module dsh-remote-bridge/core/squads
18
+ */
19
+ /**
20
+ * Every method the squads capability puts in a client's protocol. The gate in
21
+ * `connection.ts` reads this set once, so a method added beside these is gated
22
+ * by the same declaration rather than by a second list to keep in step.
23
+ */
24
+ export declare const SQUAD_METHODS: ReadonlySet<string>;
25
+ /** Sandbox modes a member may pin; the DSH permission presets, as the plugin spells them. */
26
+ export type SquadMemberPermission = 'read-only' | 'workspace-write' | 'danger-full-access';
27
+ /** One member of a squad: a display name and the pins its session is composed from. */
28
+ export interface SquadMember {
29
+ id: string;
30
+ name: string;
31
+ preset?: string;
32
+ permission?: SquadMemberPermission;
33
+ model?: string;
34
+ reasoningEffort?: string;
35
+ brief?: string;
36
+ }
37
+ /** One squad: an ordered set of member definitions sharing a workspace. */
38
+ export interface Squad {
39
+ id: string;
40
+ name: string;
41
+ description?: string;
42
+ workspaceId?: string;
43
+ leadPreset?: string;
44
+ order?: number;
45
+ members: SquadMember[];
46
+ }
47
+ /** One launched session: a member session, or the Lead session of a whole squad. */
48
+ export interface SquadRun {
49
+ id: string;
50
+ squadId: string;
51
+ kind: 'squad' | 'member';
52
+ memberId?: string;
53
+ sessionId: string;
54
+ createdAt: number;
55
+ status: 'running' | 'settled' | 'failed';
56
+ failure?: string;
57
+ }
58
+ /** The `squads.state` body: definitions, run history, the offered presets and the owning pid. */
59
+ export interface SquadsState {
60
+ squads: Squad[];
61
+ runs: SquadRun[];
62
+ presets?: string[];
63
+ host: {
64
+ ownerPid?: number;
65
+ };
66
+ }
67
+ /** What `squads.runMember` asks the domain to launch. */
68
+ export interface SquadMemberRunRequest {
69
+ squadId: string;
70
+ memberId: string;
71
+ firstMessage?: string;
72
+ }
73
+ /** What `squads.runSquad` asks the domain to launch. */
74
+ export interface SquadRunRequest {
75
+ squadId: string;
76
+ goal?: string;
77
+ }
78
+ /**
79
+ * A refusal this channel answers with. The transport raises it and the
80
+ * connection publishes its `code` and text unchanged, so a domain refusal
81
+ * (`team-not-found`, `preset-unknown`) and a capability refusal
82
+ * (`squads-unavailable`, `squads-run-unavailable`) reach the client the same way.
83
+ */
84
+ export declare class SquadRefusal extends Error {
85
+ /** Stable machine code the client switches on. */
86
+ readonly code: string;
87
+ constructor(code: string, message: string);
88
+ }
89
+ /** @returns whether a caught value is this channel's own refusal. */
90
+ export declare function isSquadRefusal(value: unknown): value is SquadRefusal;
91
+ /**
92
+ * How a Host reaches the squad domain. Every method answers the plugin's own
93
+ * body unread: `state` is one `{teams, runs, host, presets?}` document, and the
94
+ * two run methods answer one `{run}` document.
95
+ */
96
+ export interface SquadTransport {
97
+ /** Definitions, run history and the owning pid, as the domain publishes them. */
98
+ state(): Promise<unknown>;
99
+ /** Launch one member session. */
100
+ runMember(request: SquadMemberRunRequest): Promise<unknown>;
101
+ /** Launch the Lead session of one whole squad. */
102
+ runSquad(request: SquadRunRequest): Promise<unknown>;
103
+ }
104
+ /**
105
+ * Map one `squads.state` answer.
106
+ * @param source - the domain's `{teams, runs, host, presets?}` document, from
107
+ * either the plugin's route or its ledger.
108
+ * @returns the frozen state body.
109
+ */
110
+ export declare function squadsStateOf(source: unknown): SquadsState;
111
+ /**
112
+ * Map one run answer.
113
+ * @param source - the domain's `{run}` document.
114
+ * @returns the frozen run row.
115
+ */
116
+ export declare function squadRunOf(source: unknown): SquadRun;
117
+ /**
118
+ * Gate `squads.runMember`'s payload. Only the two names this command needs are
119
+ * required; the lengths the domain accepts are the domain's own, so an oversized
120
+ * message is forwarded and refused there instead of being cut here.
121
+ * @param payload - the request's `p`.
122
+ * @returns the request, or undefined when it does not name a squad and a member.
123
+ */
124
+ export declare function parseSquadMemberRun(payload: Readonly<Record<string, unknown>>): SquadMemberRunRequest | undefined;
125
+ /**
126
+ * Gate `squads.runSquad`'s payload.
127
+ * @param payload - the request's `p`.
128
+ * @returns the request, or undefined when it does not name a squad.
129
+ */
130
+ export declare function parseSquadRun(payload: Readonly<Record<string, unknown>>): SquadRunRequest | undefined;
@@ -0,0 +1,160 @@
1
+ /**
2
+ * `usage.stats` 的应答:宿主自己那份按天记的 token 台账的聚合。
3
+ *
4
+ * 这一半与 `usage.ts` 的两半有一个根本区别:那两半读的是本进程自己的事实,这一半
5
+ * 读的是另一个插件(`dsh-usage`)挂在这个宿主上的 HTTP 路由。所以它的缺席方式也
6
+ * 不同——宿主根本没挂那个插件是一件关于这台 Mac 的事实(`no-usage-plugin`),
7
+ * 不是错误;而路由取不到、形状不符、超时才是 `probe-failed`。
8
+ *
9
+ * 两条铁律贯穿本模块:
10
+ *
11
+ * - 永不编 0。五个桶在一行里恒在,但那说的是「这一行读到过」:一次没读到的聚合
12
+ * 回 `probe-failed` 并带上短原因,绝不拿上一轮的值冒充这一轮。日历上某一天宿主
13
+ * 台账里没有条目,是那一天确实没有用量——宿主自己的 `/day` 路由对这种日子答的
14
+ * 也是全 0,所以按 0 收是转述,不是编造。
15
+ * - 宿主侧 30 秒一次。同一份聚合数据在一个窗口内最多读一次,并发调用合并成一次:
16
+ * 台账是这台 Mac 的事实,一部手机重复问不该让宿主多读一遍。
17
+ *
18
+ * 读的是两条路由(都在那个插件的 `/api/dsh-usage` 前缀下):`GET /overview` 一次
19
+ * 给出今天、最近 30 个有记录的日子的台账、以及观测花费;`GET /day?date=YYYY-MM-DD`
20
+ * 补一天。所以一次聚合是 1 + K 次本机回环读,K 只在请求的窗口比 `/overview` 自带的
21
+ * 那一截更深、或本月台账被那一截截断时才不为 0。
22
+ * @module dsh-remote-bridge/core/usage-stats
23
+ */
24
+ /** 省略 `days` 时回多少天。 */
25
+ export declare const STATS_DAYS_DEFAULT = 14;
26
+ /** 一次最多回多少天:再往上按这个数收。 */
27
+ export declare const STATS_DAYS_MAX = 60;
28
+ /** 同一份聚合数据在这个窗口内最多读一次(本桥这一侧)。 */
29
+ export declare const STATS_CACHE_TTL_MS = 30000;
30
+ /** 最多记住几个不同窗口的聚合;一次开屏通常只问一个。 */
31
+ export declare const STATS_CACHE_LIMIT = 8;
32
+ /** 一次读数里的一行:五个互不重叠的 token 桶,未用即真实的 0。 */
33
+ export interface UsageBuckets {
34
+ /** 未命中缓存的输入 token。 */
35
+ readonly input: number;
36
+ /** 输出 token(含推理)。 */
37
+ readonly output: number;
38
+ /** 命中缓存的输入 token。 */
39
+ readonly cacheRead: number;
40
+ /** 写入缓存的 token。 */
41
+ readonly cacheWrite: number;
42
+ /** 推理 token,provider 报过才有。 */
43
+ readonly reasoning: number;
44
+ }
45
+ /** 按天的一行:日期键 `YYYY-MM-DD` 加上五个桶。 */
46
+ export interface UsageDayBucket extends UsageBuckets {
47
+ /** 本地日期键 `YYYY-MM-DD`。 */
48
+ readonly day: string;
49
+ }
50
+ /** 观测到的真实花费:官方账户余额的下降累计,CNY 口径。 */
51
+ export interface UsageObservedSpend {
52
+ /** 累计花费,元。 */
53
+ readonly cny: number;
54
+ /** 这次累计起点的那次余额观测时刻(epoch ms)。 */
55
+ readonly since: number;
56
+ }
57
+ /** `usage.stats` 读得到时回的那一份。 */
58
+ export interface UsageStatsView {
59
+ /** 宿主拼这份聚合的时刻(epoch ms),不是本桥答话的时刻。 */
60
+ readonly updatedAt: number;
61
+ /** 宿主本地的今天。 */
62
+ readonly today: UsageBuckets;
63
+ /** 宿主本地的本月,从 1 号到今天的累计。 */
64
+ readonly month: UsageBuckets;
65
+ /** 请求的窗口内按日期升序的一天一行,最多 `days` 条。 */
66
+ readonly days: UsageDayBucket[];
67
+ /** 宿主有观测花费时才有这个键。 */
68
+ readonly observedSpend?: UsageObservedSpend;
69
+ }
70
+ /** 读不到时回的那一份:为什么读不到,不是错误码。 */
71
+ export interface UsageStatsUnsupported {
72
+ /**
73
+ * `no-usage-plugin` —— 这台宿主没挂 `dsh-usage`(关于这台 Mac 的事实);
74
+ * `probe-failed` —— 路由取不到、形状不符或超时。
75
+ */
76
+ readonly unsupported: 'no-usage-plugin' | 'probe-failed';
77
+ /** 短原因,只给 `probe-failed`。 */
78
+ readonly reason?: string;
79
+ }
80
+ /** `usage.stats` 的应答体。 */
81
+ export type UsageStatsAnswer = UsageStatsView | UsageStatsUnsupported;
82
+ /**
83
+ * 一次宿主路由读数的结果。
84
+ *
85
+ * `missing` 单独一格,是因为「路由不存在」与「路由答了错」在协议里是两个答案:
86
+ * 前者说明那台宿主没挂插件,后者说明这次没读到。
87
+ */
88
+ export type UsageStatsOutcome = {
89
+ readonly kind: 'answer';
90
+ readonly body: unknown;
91
+ } | {
92
+ readonly kind: 'missing';
93
+ } | {
94
+ readonly kind: 'failed';
95
+ readonly reason: string;
96
+ };
97
+ /** 宿主那两条路由,按本模块需要的那一格给出来。 */
98
+ export interface UsageStatsTransport {
99
+ /** `GET /api/dsh-usage/overview`。 */
100
+ overview(): Promise<UsageStatsOutcome>;
101
+ /**
102
+ * `GET /api/dsh-usage/day?date=<day>`。
103
+ * @param day - 本地日期键 `YYYY-MM-DD`。
104
+ */
105
+ day(day: string): Promise<UsageStatsOutcome>;
106
+ }
107
+ /** 构造 {@link UsageStatsReader} 的全部输入。 */
108
+ export interface UsageStatsReaderOptions {
109
+ /** 每次读数都重新解析一次;晚挂载的宿主路由因此也能被读到。 */
110
+ readonly transport: () => UsageStatsTransport | undefined;
111
+ /** 缓存窗口读的时钟。 */
112
+ readonly now: () => number;
113
+ /** 读不到时的落点。 */
114
+ readonly log: (message: string) => void;
115
+ /** 缓存窗口;默认 {@link STATS_CACHE_TTL_MS}。 */
116
+ readonly ttlMs?: number;
117
+ }
118
+ /**
119
+ * `usage.stats` 背后的读服务,一个宿主一份、所有连接共享。
120
+ *
121
+ * 缓存与合并都按窗口值分开放:两个客户端问 14 天和问 30 天是两份不同的聚合,但
122
+ * 它们各自的窗口内都不会让宿主多读一遍。
123
+ */
124
+ export declare class UsageStatsReader {
125
+ #private;
126
+ /**
127
+ * @param options - 宿主路由的解析函数、时钟与日志。
128
+ */
129
+ constructor(options: UsageStatsReaderOptions);
130
+ /**
131
+ * 一个窗口的用量聚合。
132
+ *
133
+ * 窗口值先收进 `[1, 60]`:省下的天数与超出的天数都不是客户端能定的,而「问 1000
134
+ * 天」不该让本桥去翻 1000 个日历。
135
+ * @param days - 要多少天。
136
+ * @returns 读到的那一份,或者为什么读不到。
137
+ */
138
+ stats(days: number): Promise<UsageStatsAnswer>;
139
+ }
140
+ /**
141
+ * 把客户端给的天数收成合法的窗口。
142
+ * @param days - 客户端给的天数。
143
+ * @returns 一个 `[1, 60]` 间的整数;不是有限数时回默认的 14 天。
144
+ */
145
+ export declare function clampStatsDays(days: number): number;
146
+ /**
147
+ * 一个日期键加减天数。
148
+ *
149
+ * 走 UTC 是为了不让夏令时把「加一天」算成 23 或 25 小时:这里加的是日历天。
150
+ * @param day - 日期键 `YYYY-MM-DD`。
151
+ * @param delta - 加减多少天,负数向前。
152
+ * @returns 新的日期键。
153
+ */
154
+ export declare function shiftDay(day: string, delta: number): string;
155
+ /**
156
+ * `YYYY-MM-DD` 是不是一个真实存在的日子。
157
+ * @param value - 待判定的文本。
158
+ * @returns 格式对且日子存在时为 true。
159
+ */
160
+ export declare function isDayKey(value: string): boolean;