@yu_robotics/remote-cli-router 1.6.121 โ†’ 1.6.133

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.
@@ -0,0 +1,267 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MaintenanceCards = void 0;
4
+ exports.updateNoticeElements = updateNoticeElements;
5
+ const crypto_1 = require("crypto");
6
+ const ToolFormatter_1 = require("../utils/ToolFormatter");
7
+ // Add copy only when that backend's inspection semantics are supported.
8
+ const REMINDER_COPY = {
9
+ codex: {
10
+ title: '๐ŸŽฏ Codex Reset',
11
+ summary: '**Weekly quota reset: 100%**\n\nBackend: Codex CLI',
12
+ explanation: 'Without new Codex usage, the reset countdown may keep moving forward. Send Codex a normal task to start the next usage window.',
13
+ },
14
+ };
15
+ const UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i;
16
+ const VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
17
+ function version(value) { return typeof value === 'string' && value.length <= 100 && VERSION.test(value); }
18
+ function validOverview(value) {
19
+ if (!value || !Array.isArray(value.groups) || value.groups.length < 1 || value.groups.length > 6
20
+ || !Number.isSafeInteger(value.totalGroups) || value.totalGroups < value.groups.length
21
+ || !Number.isSafeInteger(value.totalItems) || value.totalItems < value.totalGroups)
22
+ return false;
23
+ if (!value.groups.every((group) => group && typeof group.topic === 'string' && /^[a-z][a-z0-9-]{0,39}$/.test(group.topic)
24
+ && typeof group.title === 'string' && group.title.trim() === group.title && group.title.length > 0
25
+ && Array.from(group.title).length <= 80 && !/[\r\n\[\]<>|*\x60]/.test(group.title)
26
+ && Array.isArray(group.items) && group.items.length >= 1 && group.items.length <= 12
27
+ && group.items.every((item) => typeof item === 'string' && item.trim() === item && item.length > 0
28
+ && !/[\r\n]/.test(item) && Buffer.byteLength(item) <= 2 * 1024)
29
+ && new Set(group.items).size === group.items.length))
30
+ return false;
31
+ const shown = value.groups.reduce((total, group) => total + group.items.length, 0);
32
+ return shown <= 12 && shown <= value.totalItems && new Set(value.groups.map((group) => group.topic)).size === value.groups.length
33
+ && Buffer.byteLength(JSON.stringify(value)) <= 6 * 1024;
34
+ }
35
+ function validPage(value) {
36
+ return value && ['complete', 'partial', 'unavailable'].includes(value.coverage) && Number.isSafeInteger(value.offset) && value.offset >= 0
37
+ && Number.isSafeInteger(value.totalSections) && value.totalSections >= value.offset && value.totalSections <= 10000
38
+ && Array.isArray(value.sections) && value.sections.length <= 10 && value.offset + value.sections.length <= value.totalSections
39
+ && value.sections.every((s) => version(s?.version) && typeof s.text === 'string'
40
+ && (s.details === undefined || typeof s.details === 'string'))
41
+ && (value.nextOffset === undefined || value.sections.length > 0 && value.nextOffset === value.offset + value.sections.length && value.nextOffset < value.totalSections)
42
+ && (value.overview === undefined || validOverview(value.overview))
43
+ && Buffer.byteLength(JSON.stringify(value)) <= 20 * 1024;
44
+ }
45
+ function validNotice(value) {
46
+ return UUID.test(value?.noticeKey) && version(value.fromVersion) && version(value.toVersion) && validPage(value.page);
47
+ }
48
+ function header(title, template = 'blue') { return { title: { tag: 'plain_text', content: title }, template }; }
49
+ function button(text, action, type = 'default') {
50
+ return { tag: 'button', text: { tag: 'plain_text', content: text }, type, behaviors: [{ type: 'callback', value: action }] };
51
+ }
52
+ function updateNoticeElements(notice, id) {
53
+ const page = notice.page;
54
+ const coverage = page.coverage === 'complete' ? 'Bundled release notes' : page.coverage === 'partial'
55
+ ? 'Some release notes are missing from this package.' : 'Release notes are unavailable in this package.';
56
+ const elements = [{ tag: 'markdown', content: `**${notice.fromVersion} โ†’ ${notice.toVersion}**\n\n${coverage}` }];
57
+ if (page.overview) {
58
+ for (const group of page.overview.groups)
59
+ elements.push((0, ToolFormatter_1.createMarkdownElement)(`**${group.title}**\n${group.items.map(item => `- ${item}`).join('\n')}`));
60
+ const shown = page.overview.groups.reduce((total, group) => total + group.items.length, 0);
61
+ if (shown < page.overview.totalItems)
62
+ elements.push({ tag: 'markdown', text_size: 'notation',
63
+ content: `Showing ${shown} of ${page.overview.totalItems} unique changes. Additional changes remain in version details.` });
64
+ const details = page.sections.flatMap(section => [(0, ToolFormatter_1.createMarkdownElement)(`**Version ${section.version}**\n\n${section.text}`),
65
+ ...(section.details === undefined ? [] : [(0, ToolFormatter_1.createMarkdownElement)(`**Technical details**\n\n${section.details}`)])]);
66
+ if (details.length)
67
+ elements.push({ tag: 'collapsible_panel', expanded: false,
68
+ header: { title: { tag: 'plain_text', content: 'Version details' } }, elements: details });
69
+ }
70
+ else {
71
+ for (const section of page.sections) {
72
+ if (section.details !== undefined)
73
+ elements.push((0, ToolFormatter_1.createMarkdownElement)(`**${section.version}**\n\n${section.text}`));
74
+ elements.push({ tag: 'collapsible_panel', expanded: false,
75
+ header: { title: { tag: 'plain_text', content: section.details === undefined ? `Version ${section.version}` : `Technical details ยท ${section.version}` } },
76
+ elements: [(0, ToolFormatter_1.createMarkdownElement)(section.details ?? section.text)] });
77
+ }
78
+ }
79
+ if (page.totalSections)
80
+ elements.push({ tag: 'markdown', text_size: 'notation',
81
+ content: `Showing ${page.offset + 1}โ€“${page.offset + page.sections.length} of ${page.totalSections} releases. Display paging does not change history coverage.` });
82
+ if (page.nextOffset !== undefined)
83
+ elements.push(button('View more', { action: 'maintenance_view', id, offset: page.nextOffset }));
84
+ if (page.offset > 0)
85
+ elements.push(button('Back to overview', { action: 'maintenance_view', id, offset: 0 }));
86
+ return elements;
87
+ }
88
+ function reminderHeader(reminder, dismissed = false) {
89
+ return header(REMINDER_COPY[reminder.backend ?? 'codex'].title, dismissed ? 'grey' : 'blue');
90
+ }
91
+ function reminderElements(reminder, dismissed = false) {
92
+ const copy = REMINDER_COPY[reminder.backend ?? 'codex'];
93
+ return [{ tag: 'markdown', content: `${copy.summary}\n\n${copy.explanation}` },
94
+ ...(dismissed ? [{ tag: 'markdown', content: 'Dismissed.' }] : [])];
95
+ }
96
+ /** Standalone maintenance cards never enter thread/output routing maps. */
97
+ class MaintenanceCards {
98
+ receipts;
99
+ deps;
100
+ now;
101
+ flights = new Map();
102
+ deliveredWithoutReceipt = new Map();
103
+ reminders = new Map();
104
+ pageRequests = new Map();
105
+ constructor(receipts, deps) {
106
+ this.receipts = receipts;
107
+ this.deps = deps;
108
+ this.now = deps.now ?? Date.now;
109
+ }
110
+ async receiveNotice(message, deviceId, current) {
111
+ if (!validNotice(message) || message.page.offset !== 0)
112
+ return;
113
+ const key = JSON.stringify([deviceId, message.noticeKey]);
114
+ const existing = this.flights.get(key);
115
+ if (existing) {
116
+ await existing;
117
+ if (current())
118
+ await this.acknowledge(message, deviceId);
119
+ return;
120
+ }
121
+ const operation = (async () => {
122
+ const openId = await this.deps.owner(deviceId);
123
+ if (!openId || !current())
124
+ return;
125
+ let receipt = this.deliveredWithoutReceipt.get(key) ?? await this.receipts.find(deviceId, message.noticeKey);
126
+ if (receipt && (receipt.openId !== openId || receipt.fromVersion !== message.fromVersion || receipt.toVersion !== message.toVersion))
127
+ return;
128
+ if (!receipt) {
129
+ const id = (0, crypto_1.randomUUID)();
130
+ const cardId = await this.deps.create(openId, updateNoticeElements(message, id), header('๐Ÿ“ฆ Remote CLI updated'));
131
+ if (!cardId)
132
+ return;
133
+ receipt = { id, deviceId, openId, noticeKey: message.noticeKey, fromVersion: message.fromVersion, toVersion: message.toVersion, cardId, deliveredAt: this.now() };
134
+ this.deliveredWithoutReceipt.set(key, receipt);
135
+ }
136
+ // A Feishu-success / storage-write crash gap cannot be made exactly once here.
137
+ await this.receipts.remember(receipt);
138
+ this.deliveredWithoutReceipt.delete(key);
139
+ if (current() && await this.deps.owner(deviceId) === openId)
140
+ await this.acknowledge(message, deviceId);
141
+ })();
142
+ this.flights.set(key, operation);
143
+ try {
144
+ await operation;
145
+ }
146
+ finally {
147
+ if (this.flights.get(key) === operation)
148
+ this.flights.delete(key);
149
+ }
150
+ }
151
+ async acknowledge(message, deviceId) {
152
+ const receipt = await this.receipts.find(deviceId, message.noticeKey);
153
+ if (!receipt || receipt.fromVersion !== message.fromVersion || receipt.toVersion !== message.toVersion
154
+ || await this.deps.owner(deviceId) !== receipt.openId)
155
+ return;
156
+ await this.deps.send(deviceId, { type: 'update_notice_ack', noticeKey: message.noticeKey, fromVersion: message.fromVersion, toVersion: message.toVersion });
157
+ }
158
+ async view(openId, id, cardId, offset, connection) {
159
+ this.prune();
160
+ const record = await this.receipts.findCard(id, cardId);
161
+ if (!record || record.openId !== openId || await this.deps.owner(record.deviceId) !== openId)
162
+ throw new Error('This update notice is no longer available.');
163
+ const current = connection(record.deviceId);
164
+ if (!Number.isSafeInteger(offset) || offset < 0 || offset > 10000 || !current?.())
165
+ throw new Error('Reconnect a compatible CLI to view more release notes.');
166
+ if ([...this.pageRequests.values()].some(p => p.record.id === id))
167
+ return 'Release notes are already loading.';
168
+ const requestId = (0, crypto_1.randomUUID)();
169
+ this.pageRequests.set(requestId, { record, offset, current, expiresAt: this.now() + 30_000 });
170
+ if (!await this.deps.send(record.deviceId, { type: 'update_notice_view', requestId, noticeKey: record.noticeKey,
171
+ fromVersion: record.fromVersion, toVersion: record.toVersion, offset })) {
172
+ this.pageRequests.delete(requestId);
173
+ throw new Error('This CLI is offline.');
174
+ }
175
+ return 'Loading bundled release notes...';
176
+ }
177
+ async receivePage(message, deviceId) {
178
+ this.prune();
179
+ const requestId = message?.requestId;
180
+ const pending = this.pageRequests.get(requestId);
181
+ if (!pending || !validNotice(message) || pending.record.deviceId !== deviceId || message.noticeKey !== pending.record.noticeKey
182
+ || message.fromVersion !== pending.record.fromVersion || message.toVersion !== pending.record.toVersion || message.page.offset !== pending.offset)
183
+ return;
184
+ this.pageRequests.delete(requestId);
185
+ if (!pending.current() || await this.deps.owner(deviceId) !== pending.record.openId)
186
+ return;
187
+ await this.deps.update(pending.record.cardId, updateNoticeElements(message, pending.record.id), header('๐Ÿ“ฆ Remote CLI updated'));
188
+ }
189
+ async receiveReminder(message, deviceId, current) {
190
+ this.prune();
191
+ const r = message?.reminder;
192
+ if (!r || !UUID.test(r.reminderId) || !UUID.test(r.generation) || r.activationAvailable !== false || !Number.isFinite(r.expiresAt)
193
+ || (r.backend !== undefined && (typeof r.backend !== 'string' || !Object.prototype.hasOwnProperty.call(REMINDER_COPY, r.backend)))
194
+ || r.expiresAt <= this.now() || r.expiresAt > this.now() + 2 * 3600_000)
195
+ return;
196
+ const key = JSON.stringify([deviceId, r.reminderId]);
197
+ const existing = this.flights.get(key);
198
+ if (existing) {
199
+ await existing;
200
+ return;
201
+ }
202
+ const operation = (async () => {
203
+ const openId = await this.deps.owner(deviceId);
204
+ if (!openId || !current())
205
+ return;
206
+ let record = this.reminders.get(key);
207
+ if (record && (record.openId !== openId || record.generation !== r.generation))
208
+ return;
209
+ if (!record) {
210
+ const cardId = await this.deps.create(openId, reminderElements(r), reminderHeader(r));
211
+ if (!cardId || !current())
212
+ return;
213
+ record = { ...r, deviceId, openId, cardId, current, dismissed: false };
214
+ this.reminders.set(key, record);
215
+ }
216
+ if (await this.deps.owner(deviceId) === openId && current())
217
+ await this.deps.send(deviceId, {
218
+ type: 'subscription_reminder_ack', reminderId: r.reminderId, generation: r.generation,
219
+ });
220
+ })();
221
+ this.flights.set(key, operation);
222
+ try {
223
+ await operation;
224
+ }
225
+ finally {
226
+ this.flights.delete(key);
227
+ }
228
+ }
229
+ async reply(openId, id, cardId, decision) {
230
+ this.prune();
231
+ const record = [...this.reminders.values()].find(r => r.reminderId === id && r.cardId === cardId);
232
+ if (!record || record.openId !== openId || await this.deps.owner(record.deviceId) !== openId || !record.current())
233
+ throw new Error('This reminder expired or its CLI reconnected.');
234
+ if (decision === 'send_hi')
235
+ throw new Error('Quota notices are notification-only. Model requests are not supported.');
236
+ if (decision !== 'not_now' && decision !== 'dismiss')
237
+ throw new Error('Invalid maintenance action.');
238
+ if (record.dismissed)
239
+ return 'This reminder was already dismissed.';
240
+ // Accept the former passive action from existing cards, without offering it on new cards.
241
+ if (decision === 'not_now')
242
+ return 'This notice will not be repeated. No model request was sent.';
243
+ record.dismissed = true;
244
+ await this.deps.send(record.deviceId, { type: 'subscription_action', reminderId: id, generation: record.generation, decision: 'dismiss' });
245
+ await this.deps.update(cardId, reminderElements(record, true), reminderHeader(record, true));
246
+ return 'Dismissed. No model request was sent.';
247
+ }
248
+ disconnect(deviceId) {
249
+ for (const [key, r] of this.reminders)
250
+ if (r.deviceId === deviceId)
251
+ this.reminders.delete(key);
252
+ for (const [key, r] of this.pageRequests)
253
+ if (r.record.deviceId === deviceId)
254
+ this.pageRequests.delete(key);
255
+ }
256
+ destroy() { this.reminders.clear(); this.pageRequests.clear(); }
257
+ prune() {
258
+ for (const [key, r] of this.reminders)
259
+ if (r.expiresAt <= this.now())
260
+ this.reminders.delete(key);
261
+ for (const [key, r] of this.pageRequests)
262
+ if (r.expiresAt <= this.now())
263
+ this.pageRequests.delete(key);
264
+ }
265
+ }
266
+ exports.MaintenanceCards = MaintenanceCards;
267
+ //# sourceMappingURL=MaintenanceCards.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MaintenanceCards.js","sourceRoot":"","sources":["../../src/maintenance/MaintenanceCards.ts"],"names":[],"mappings":";;;AA+DA,oDA2BC;AA1FD,mCAAoC;AAEpC,0DAAuF;AAMvF,wEAAwE;AACxE,MAAM,aAAa,GAAG;IACpB,KAAK,EAAE;QACL,KAAK,EAAE,gBAAgB;QACvB,OAAO,EAAE,oDAAoD;QAC7D,WAAW,EAAE,gIAAgI;KAC9I;CACO,CAAC;AAYX,MAAM,IAAI,GAAG,wEAAwE,CAAC;AACtF,MAAM,OAAO,GAAG,2HAA2H,CAAC;AAC5I,SAAS,OAAO,CAAC,KAAc,IAAqB,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,IAA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viceId: string;
4
+ openId: string;
5
+ noticeKey: string;
6
+ fromVersion: string;
7
+ toVersion: string;
8
+ cardId: string;
9
+ deliveredAt: number;
10
+ }
11
+ /** Delivery receipts survive Router restarts. This is not an exactly-once Feishu transaction. */
12
+ export declare class NoticeReceipts {
13
+ private readonly filename;
14
+ private readonly now;
15
+ private records;
16
+ private loading?;
17
+ private writes;
18
+ constructor(filename: string, now?: () => number);
19
+ private ready;
20
+ find(deviceId: string, noticeKey: string): Promise<NoticeReceipt | undefined>;
21
+ findCard(id: string, cardId: string): Promise<NoticeReceipt | undefined>;
22
+ remember(record: NoticeReceipt): Promise<void>;
23
+ }
24
+ //# sourceMappingURL=NoticeReceipts.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"NoticeReceipts.d.ts","sourceRoot":"","sources":["../../src/maintenance/NoticeReceipts.ts"],"names":[],"mappings":"AAIA,MAAM,WAAW,aAAa;IAC5B,EAAE,EAAE,MAAM,CAAC;IACX,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,MAAM,CAAC;CACrB;AAED,iGAAiG;AACjG,qBAAa,cAAc;IAIb,OAAO,CAAC,QAAQ,CAAC,QAAQ;IAAU,OAAO,CAAC,QAAQ,CAAC,GAAG;IAHnE,OAAO,CAAC,OAAO,CAAuB;IACtC,OAAO,CAAC,OAAO,CAAC,CAAgB;IAChC,OAAO,CAAC,MAAM,CAAqB;gBACN,QAAQ,EAAE,MAAM,EAAmB,GAAG,eAAW;IAE9E,OAAO,CAAC,KAAK;IAcP,IAAI,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,GAAG,SAAS,CAAC;IAK7E,QAAQ,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,GAAG,SAAS,CAAC;IAKxE,QAAQ,CAAC,MAAM,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC;CAkBrD"}
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.NoticeReceipts = void 0;
7
+ const promises_1 = __importDefault(require("fs/promises"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const crypto_1 = require("crypto");
10
+ /** Delivery receipts survive Router restarts. This is not an exactly-once Feishu transaction. */
11
+ class NoticeReceipts {
12
+ filename;
13
+ now;
14
+ records = [];
15
+ loading;
16
+ writes = Promise.resolve();
17
+ constructor(filename, now = Date.now) {
18
+ this.filename = filename;
19
+ this.now = now;
20
+ }
21
+ ready() {
22
+ return this.loading ??= (async () => {
23
+ try {
24
+ const stat = await promises_1.default.lstat(this.filename);
25
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 1024 * 1024)
26
+ throw new Error('Unsafe notice receipts.');
27
+ const value = JSON.parse(await promises_1.default.readFile(this.filename, 'utf8'));
28
+ if (!Array.isArray(value) || value.length > 1000 || value.some(r => !r ||
29
+ ['id', 'deviceId', 'openId', 'noticeKey', 'fromVersion', 'toVersion', 'cardId'].some(k => typeof r[k] !== 'string' || r[k].length > 200)
30
+ || !Number.isFinite(r.deliveredAt)))
31
+ throw new Error('Invalid notice receipts.');
32
+ this.records = value;
33
+ }
34
+ catch (error) {
35
+ if (error.code !== 'ENOENT')
36
+ throw new Error('Notice receipt storage is unavailable.');
37
+ }
38
+ })();
39
+ }
40
+ async find(deviceId, noticeKey) {
41
+ await this.ready();
42
+ return this.records.find(r => r.deviceId === deviceId && r.noticeKey === noticeKey && this.now() - r.deliveredAt < 30 * 86400_000);
43
+ }
44
+ async findCard(id, cardId) {
45
+ await this.ready();
46
+ return this.records.find(r => r.id === id && r.cardId === cardId && this.now() - r.deliveredAt < 30 * 86400_000);
47
+ }
48
+ async remember(record) {
49
+ await this.ready();
50
+ const operation = this.writes.then(async () => {
51
+ const records = this.records.filter(r => this.now() - r.deliveredAt < 30 * 86400_000
52
+ && !(r.deviceId === record.deviceId && r.noticeKey === record.noticeKey));
53
+ records.push(record);
54
+ const next = records.slice(-1000);
55
+ await promises_1.default.mkdir(path_1.default.dirname(this.filename), { recursive: true, mode: 0o700 });
56
+ const temporary = `${this.filename}.${(0, crypto_1.randomUUID)()}.tmp`;
57
+ try {
58
+ await promises_1.default.writeFile(temporary, JSON.stringify(next), { flag: 'wx', mode: 0o600 });
59
+ await promises_1.default.rename(temporary, this.filename);
60
+ this.records = next;
61
+ }
62
+ finally {
63
+ await promises_1.default.rm(temporary, { force: true });
64
+ }
65
+ });
66
+ this.writes = operation.catch(() => { });
67
+ return operation;
68
+ }
69
+ }
70
+ exports.NoticeReceipts = NoticeReceipts;
71
+ //# sourceMappingURL=NoticeReceipts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"NoticeReceipts.js","sourceRoot":"","sources":["../../src/maintenance/NoticeReceipts.ts"],"names":[],"mappings":";;;;;;AAAA,2DAA6B;AAC7B,gDAAwB;AACxB,mCAAoC;AAapC,iGAAiG;AACjG,MAAa,cAAc;IAII;IAAmC;IAHxD,OAAO,GAAoB,EAAE,CAAC;IAC9B,OAAO,CAAiB;IACxB,MAAM,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC;IACnC,YAA6B,QAAgB,EAAmB,MAAM,IAAI,CAAC,GAAG;QAAjD,aAAQ,GAAR,QAAQ,CAAQ;QAAmB,QAAG,GAAH,GAAG,CAAW;IAAG,CAAC;IAE1E,KAAK;QACX,OAAO,IAAI,CAAC,OAAO,KAAK,CAAC,KAAK,IAAI,EAAE;YAClC,IAAI,CAAC;gBACH,MAAM,IAAI,GAAG,MAAM,kBAAE,CAAC,KAAK,CAA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E,KAAK,EAAE,CAAC,CAAC;YAC9E,MAAM,SAAS,GAAG,GAAG,IAAI,CAAC,QAAQ,IAAI,IAAA,mBAAU,GAAE,MAAM,CAAC;YACzD,IAAI,CAAC;gBACH,MAAM,kBAAE,CAAC,SAAS,CAAC,SAAS,EAAE,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;gBACjF,MAAM,kBAAE,CAAC,MAAM,CAAC,SAAS,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC;gBAC1C,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;YACtB,CAAC;oBAAS,CAAC;gBAAC,MAAM,kBAAE,CAAC,EAAE,CAAC,SAAS,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;YAAC,CAAC;QACxD,CAAC,CAAC,CAAC;QACH,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;QACxC,OAAO,SAAS,CAAC;IACnB,CAAC;CACF;AAhDD,wCAgDC"}
package/dist/server.d.ts CHANGED
@@ -14,6 +14,8 @@ export declare class RouterServer {
14
14
  private connectionHub;
15
15
  private bindingManager;
16
16
  private approvalCards;
17
+ private readonly maintenanceCards;
18
+ private readonly maintenanceConnections;
17
19
  private cleanupInterval;
18
20
  private streamingMessages;
19
21
  private completedTasks;
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAYA,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACvD,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAmDhD;;;GAGG;AACH,qBAAa,YAAY;IACvB,OAAO,CAAC,GAAG,CAAM;IACjB,OAAO,CAAC,UAAU,CAA2B;IAC7C,OAAO,CAAC,GAAG,CAAgC;IAC3C,OAAO,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O,CAAC,mCAAmC;IA2B3C,OAAO,CAAC,2BAA2B;IAMnC,uFAAuF;YACzE,wBAAwB;IA6HtC;;;OAGG;YACW,sBAAsB;IAoCpC;;;;OAIG;YACW,cAAc;YAiCd,WAAW;IAkCzB,OAAO,CAAC,qBAAqB;IAS7B,OAAO,CAAC,eAAe;IAKvB,oFAAoF;IACpF,OAAO,CAAC,iBAAiB;IAYzB,kFAAkF;YACpE,gBAAgB;IAmF9B,2EAA2E;YAC7D,kBAAkB;IA+EhC;;;;;;;;OAQG;YACW,sBAAsB;IAuBpC;;OAEG;YACW,wBAAwB;IAiFtC;;;OAGG;IACH,OAAO,CAAC,6BAA6B;IAqCrC;;;OAGG;IACH,OAAO,CAAC,iCAAiC;IA6BzC;;OAEG;IACG,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAiE3B;;OAEG;IACH,QAAQ;;;;CAGT"}
package/dist/server.js CHANGED
@@ -5,11 +5,14 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.RouterServer = void 0;
7
7
  const ApprovalCards_1 = require("./feishu/ApprovalCards");
8
+ const MaintenanceCards_1 = require("./maintenance/MaintenanceCards");
9
+ const NoticeReceipts_1 = require("./maintenance/NoticeReceipts");
8
10
  const DeviceAuth_1 = require("./files/DeviceAuth");
9
11
  const FileTransfers_1 = require("./files/FileTransfers");
10
12
  const path_1 = __importDefault(require("path"));
11
13
  const os_1 = __importDefault(require("os"));
12
14
  const crypto_1 = require("crypto");
15
+ const ExecutionMetadata_1 = require("./utils/ExecutionMetadata");
13
16
  const koa_1 = __importDefault(require("koa"));
14
17
  const koa_bodyparser_1 = __importDefault(require("koa-bodyparser"));
15
18
  const router_1 = __importDefault(require("@koa/router"));
@@ -40,6 +43,8 @@ class RouterServer {
40
43
  connectionHub;
41
44
  bindingManager;
42
45
  approvalCards;
46
+ maintenanceCards;
47
+ maintenanceConnections = new Map();
43
48
  cleanupInterval = null;
44
49
  // Track streaming messages and coalesced Feishu card update state.
45
50
  streamingMessages = new Map();
@@ -120,6 +125,18 @@ class RouterServer {
120
125
  },
121
126
  });
122
127
  this.feishuLongConnHandler.onApprovalAction = (openId, requestId, cardId, decision) => this.approvalCards.click(openId, requestId, cardId, decision);
128
+ this.maintenanceCards = new MaintenanceCards_1.MaintenanceCards(new NoticeReceipts_1.NoticeReceipts(path_1.default.join(path_1.default.dirname(config.getConfigPath() || path_1.default.join(os_1.default.homedir(), '.remote-cli-router', 'config.json')), 'notice-receipts.json')), {
129
+ owner: async (deviceId) => (await this.bindingManager.getDeviceBinding(deviceId))?.openId,
130
+ send: (deviceId, message) => this.connectionHub.sendToDevice(deviceId, message),
131
+ create: (openId, elements, header) => this.feishuLongConnHandler.sendTaskNotificationCard(openId, elements, header),
132
+ update: (cardId, elements, header) => this.feishuLongConnHandler.updateApprovalCard(cardId, elements, header),
133
+ });
134
+ this.feishuLongConnHandler.onMaintenanceAction = (openId, id, cardId, action, offset) => action === 'view'
135
+ ? this.maintenanceCards.view(openId, id, cardId, offset, deviceId => {
136
+ const connection = this.maintenanceConnections.get(deviceId);
137
+ return connection?.updateNotice ? connection.current : undefined;
138
+ })
139
+ : this.maintenanceCards.reply(openId, id, cardId, action);
123
140
  // Register callback for streaming message start
124
141
  this.feishuLongConnHandler.setOnStartStreaming((messageId, openId, feishuMessageId, deviceId, threadId, pendingNewThread, queueCardId, threadName) => {
125
142
  console.log(`[RouterServer] Registering streaming session: msgId=${messageId}, feishuMsgId=${feishuMessageId}, deviceId=${deviceId}, threadId=${threadId}, pendingNewThread=${pendingNewThread}`);
@@ -320,6 +337,8 @@ class RouterServer {
320
337
  let delegationProgressEnabled = false;
321
338
  let delegationProgressTextEnabled = false;
322
339
  let streamingContextEnabled = false;
340
+ let updateNoticeEnabled = false;
341
+ let subscriptionInspectionEnabled = false;
323
342
  let authenticationPending = false;
324
343
  let challengeTimer;
325
344
  let heartbeatTimeout = null;
@@ -352,6 +371,18 @@ class RouterServer {
352
371
  await this.fileTransfers.handleStatus(deviceId, message);
353
372
  return;
354
373
  }
374
+ if (['update_notice', 'update_notice_page', 'subscription_reminder'].includes(message.type)) {
375
+ if (!deviceId)
376
+ return;
377
+ const current = () => this.connectionHub.isCurrentConnection(deviceId, ws);
378
+ if (message.type === 'update_notice' && updateNoticeEnabled)
379
+ await this.maintenanceCards.receiveNotice(message, deviceId, current);
380
+ if (message.type === 'update_notice_page' && updateNoticeEnabled)
381
+ await this.maintenanceCards.receivePage(message, deviceId);
382
+ if (message.type === 'subscription_reminder' && subscriptionInspectionEnabled)
383
+ await this.maintenanceCards.receiveReminder(message, deviceId, current);
384
+ return;
385
+ }
355
386
  if (message.type === 'approval_request' || message.type === 'approval_resolved') {
356
387
  if (!approvalCardsEnabled || !deviceId)
357
388
  return;
@@ -465,6 +496,7 @@ class RouterServer {
465
496
  break;
466
497
  }
467
498
  this.approvalCards.disconnect(deviceId);
499
+ this.maintenanceCards.disconnect(deviceId);
468
500
  if (message.data.capabilities?.queueStarted === true) {
469
501
  this.connectionHub.registerConnection(deviceId, ws, { queueStarted: true });
470
502
  }
@@ -478,6 +510,10 @@ class RouterServer {
478
510
  this.fileTransfers.disconnect(deviceId);
479
511
  taskRecoveryEnabled = message.data.capabilities?.taskRecovery === true;
480
512
  approvalCardsEnabled = message.data.capabilities?.approvalCards === true;
513
+ updateNoticeEnabled = message.data.capabilities?.updateNotice === true;
514
+ subscriptionInspectionEnabled = message.data.capabilities?.subscriptionInspection === true;
515
+ this.maintenanceConnections.set(deviceId, { updateNotice: updateNoticeEnabled,
516
+ current: () => ws.readyState === ws_1.WebSocket.OPEN && this.connectionHub.isCurrentConnection(requestedId, ws) });
481
517
  streamingContextEnabled = message.data.capabilities?.streamingContext === true;
482
518
  delegationProgressEnabled = message.data.capabilities?.delegationProgress === true;
483
519
  delegationProgressTextEnabled = delegationProgressEnabled
@@ -491,7 +527,9 @@ class RouterServer {
491
527
  success: true,
492
528
  routerVersion: types_1.ROUTER_VERSION,
493
529
  minCliVersion: types_1.MIN_SUPPORTED_CLI_VERSION,
494
- ...((taskRecoveryEnabled || approvalCardsEnabled || delegationProgressEnabled || streamingContextEnabled || filesEnabled) ? { capabilities: {
530
+ ...((taskRecoveryEnabled || approvalCardsEnabled || delegationProgressEnabled || streamingContextEnabled || filesEnabled || updateNoticeEnabled || subscriptionInspectionEnabled) ? { capabilities: {
531
+ ...(updateNoticeEnabled ? { updateNotice: true } : {}),
532
+ ...(subscriptionInspectionEnabled ? { subscriptionInspection: true } : {}),
495
533
  ...(filesEnabled ? { fileTransferV1: true } : {}),
496
534
  ...(taskRecoveryEnabled ? { taskRecovery: true } : {}),
497
535
  ...(approvalCardsEnabled ? { approvalCards: true } : {}),
@@ -531,6 +569,7 @@ class RouterServer {
531
569
  const responseThreadId = message.threadId || message.data?.threadId;
532
570
  const responseThreads = message.threads || message.data?.threads;
533
571
  const queueConfirmation = message.queueConfirmation || message.data?.queueConfirmation;
572
+ const executionMetadata = (0, ExecutionMetadata_1.parseExecutionMetadata)(message.executionMetadata ?? message.data?.executionMetadata);
534
573
  // If CLI reported a threadId and there is a streaming session for this message,
535
574
  // ensure the cardThreadMap is up to date (in case the CLI-reported threadId differs).
536
575
  if (responseThreadId && responseMessageId) {
@@ -564,7 +603,7 @@ class RouterServer {
564
603
  if (responseMessageId && responseOpenId) {
565
604
  // Check if this was a streaming message (stream chunks were sent)
566
605
  if (this.streamingMessages.has(responseMessageId)) {
567
- await this.finalizeStreamingMessage(responseMessageId, message.success ?? message.data?.success, message.output || message.data?.output, message.error || message.data?.error, sessionAbbr, cwd, queueConfirmation);
606
+ await this.finalizeStreamingMessage(responseMessageId, message.success ?? message.data?.success, message.output || message.data?.output, message.error || message.data?.error, sessionAbbr, cwd, queueConfirmation, executionMetadata);
568
607
  }
569
608
  else {
570
609
  // No streaming session found - session should have been created when command was sent
@@ -693,6 +732,8 @@ class RouterServer {
693
732
  this.fileTransfers.disconnect(deviceId);
694
733
  // Clean up any streaming sessions for this device
695
734
  this.approvalCards.disconnect(deviceId);
735
+ this.maintenanceCards.disconnect(deviceId);
736
+ this.maintenanceConnections.delete(deviceId);
696
737
  this.cleanupStreamingSessionsForDevice(deviceId);
697
738
  console.log('Device disconnected:', deviceId);
698
739
  }
@@ -934,6 +975,7 @@ class RouterServer {
934
975
  : undefined;
935
976
  const startedAt = typeof raw.startedAt === 'number' && Number.isFinite(raw.startedAt) && raw.startedAt >= 0
936
977
  ? raw.startedAt : undefined;
978
+ const executionMetadata = (0, ExecutionMetadata_1.parseExecutionMetadata)(raw.executionMetadata);
937
979
  return {
938
980
  taskId,
939
981
  backend,
@@ -945,6 +987,7 @@ class RouterServer {
945
987
  summary: this.boundedDelegationProgressText(raw.summary, 4000),
946
988
  error: this.boundedDelegationProgressText(raw.error, 4000),
947
989
  startedAt,
990
+ ...(executionMetadata?.backend === backend ? { executionMetadata } : {}),
948
991
  };
949
992
  }
950
993
  appendDelegationProgressEvent(state, label, isError = false, toolId) {
@@ -1059,6 +1102,8 @@ class RouterServer {
1059
1102
  }
1060
1103
  if (!state.objective && progress.objective)
1061
1104
  state.objective = progress.objective;
1105
+ if (progress.executionMetadata)
1106
+ state.executionMetadata = progress.executionMetadata;
1062
1107
  if (progress.phase === 'waiting_input')
1063
1108
  state.inputRequest = progress.summary;
1064
1109
  else
@@ -1336,7 +1381,7 @@ class RouterServer {
1336
1381
  this.cardThreadMap.set(cardId, { threadId, deviceId, expiresAt: Date.now() + this.CARD_THREAD_MAP_TTL_MS });
1337
1382
  }
1338
1383
  if (info.state !== 'running') {
1339
- await this.finalizeStreamingMessage(messageId, info.state === 'completed', undefined, info.error, undefined, info.cwd);
1384
+ await this.finalizeStreamingMessage(messageId, info.state === 'completed', undefined, info.error, undefined, info.cwd, undefined, (0, ExecutionMetadata_1.parseExecutionMetadata)(info.executionMetadata));
1340
1385
  if (!isCurrent())
1341
1386
  return false;
1342
1387
  this.rememberCompletedTask(messageId, deviceId);
@@ -1460,7 +1505,7 @@ class RouterServer {
1460
1505
  /**
1461
1506
  * Finalize streaming message
1462
1507
  */
1463
- async finalizeStreamingMessage(messageId, success, output, error, sessionAbbr, cwd, queueConfirmation) {
1508
+ async finalizeStreamingMessage(messageId, success, output, error, sessionAbbr, cwd, queueConfirmation, executionMetadata) {
1464
1509
  const streamData = this.streamingMessages.get(messageId);
1465
1510
  if (!streamData)
1466
1511
  return;
@@ -1481,7 +1526,7 @@ class RouterServer {
1481
1526
  streamData.elements.push((0, ToolFormatter_1.createMarkdownElement)(output));
1482
1527
  }
1483
1528
  if (success) {
1484
- const finalized = await this.feishuLongConnHandler.finalizeStreamingMessage(feishuMessageId, streamData.elements, sessionAbbr, openId, cwd, streamData.threadName, streamData.threads, streamData.threadId, queueConfirmation);
1529
+ const finalized = await this.feishuLongConnHandler.finalizeStreamingMessage(feishuMessageId, streamData.elements, sessionAbbr, openId, cwd, streamData.threadName, streamData.threads, streamData.threadId, queueConfirmation, executionMetadata);
1485
1530
  if (finalized === false)
1486
1531
  throw new Error('Failed to finalize task card');
1487
1532
  }
@@ -1492,7 +1537,7 @@ class RouterServer {
1492
1537
  const errorMsg = error || 'Command failed';
1493
1538
  finalElements.push((0, ToolFormatter_1.createMarkdownElement)(`\n\nโŒ **Error:** ${errorMsg}`));
1494
1539
  }
1495
- const finalized = await this.feishuLongConnHandler.finalizeStreamingMessage(feishuMessageId, finalElements, undefined, openId, cwd, streamData.threadName, streamData.threads, streamData.threadId, queueConfirmation);
1540
+ const finalized = await this.feishuLongConnHandler.finalizeStreamingMessage(feishuMessageId, finalElements, undefined, openId, cwd, streamData.threadName, streamData.threads, streamData.threadId, queueConfirmation, executionMetadata);
1496
1541
  if (finalized === false)
1497
1542
  throw new Error('Failed to finalize task card');
1498
1543
  }
@@ -1588,6 +1633,8 @@ class RouterServer {
1588
1633
  async stop() {
1589
1634
  console.log('Stopping router server...');
1590
1635
  this.approvalCards.destroy();
1636
+ this.maintenanceCards.destroy();
1637
+ this.maintenanceConnections.clear();
1591
1638
  await this.fileTransfers.destroy();
1592
1639
  // Stop cleanup interval
1593
1640
  if (this.cleanupInterval) {