@moxuli/moremote 0.1.5 → 0.1.7

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 (38) hide show
  1. package/README.md +40 -15
  2. package/dist/cli.js +2 -1
  3. package/dist/cloud-client.d.ts +10 -1
  4. package/dist/cloud-client.js +43 -3
  5. package/dist/event-publication.d.ts +6 -0
  6. package/dist/event-publication.js +48 -0
  7. package/dist/journal.d.ts +3 -0
  8. package/dist/journal.js +7 -1
  9. package/dist/limits.d.ts +1 -0
  10. package/dist/limits.js +1 -1
  11. package/dist/live-activity.d.ts +60 -0
  12. package/dist/live-activity.js +131 -0
  13. package/dist/live-directory.d.ts +16 -0
  14. package/dist/live-directory.js +78 -0
  15. package/dist/local-enrollment.d.ts +1 -1
  16. package/dist/local-enrollment.js +1 -1
  17. package/dist/notification-preview.d.ts +29 -0
  18. package/dist/notification-preview.js +75 -0
  19. package/dist/official-client.d.ts +71 -0
  20. package/dist/official-client.js +63 -12
  21. package/dist/runtime.d.ts +2 -1
  22. package/dist/runtime.js +14 -13
  23. package/docs/STATE.md +70 -503
  24. package/docs/configuration.md +21 -1
  25. package/docs/journal/2026-11-14-state-before-0.1.6-part-1.md +400 -0
  26. package/docs/journal/2026-11-14-state-before-0.1.6-part-2.md +115 -0
  27. package/docs/journal/2026-11-15-custom-origin-release.md +35 -0
  28. package/docs/journal/2026-11-15-informative-notifications-and-settings.md +41 -0
  29. package/docs/journal/2026-11-15-remote-activity-local-acceptance.md +85 -0
  30. package/docs/plans/2026-11-10-notification-delivery.md +8 -0
  31. package/docs/plans/2026-11-14-custom-api-origin.md +69 -0
  32. package/docs/plans/2026-11-15-remote-activity-and-shared-events.md +99 -0
  33. package/docs/specs/01-architecture.md +3 -2
  34. package/docs/specs/02-encrypted-delivery.md +25 -0
  35. package/docs/specs/03-api-contract.md +47 -6
  36. package/docs/specs/05-endpoint-and-lifecycle.md +9 -1
  37. package/package.json +2 -2
  38. package/vectors/remote-activity-v2.json +30 -0
@@ -0,0 +1,29 @@
1
+ import { type NotificationPermissionRequest } from '@getpaseo/protocol/agent-attention-notification';
2
+ import type { AgentSnapshotPayload } from '@getpaseo/protocol/messages';
3
+ import { type Envelope } from './crypto.js';
4
+ import type { Pair } from './config.js';
5
+ export interface NotificationPreview {
6
+ title: string;
7
+ hostName: string;
8
+ body: string;
9
+ }
10
+ type Kind = 'finished' | 'question' | 'permission' | 'error';
11
+ type Entry = {
12
+ timestamp: string;
13
+ item: {
14
+ type: string;
15
+ text?: string;
16
+ message?: string;
17
+ };
18
+ };
19
+ /** Bound UTF-8, retaining whole graphemes and removing invisible directional controls. */
20
+ export declare function notificationText(value: string, bytes: number): string;
21
+ /** Only current-turn assistant prose or the exact pending request; never reasoning/tool output. */
22
+ export declare function buildNotificationPreview(agent: AgentSnapshotPayload, hostName: string, kind: Kind, request?: NotificationPermissionRequest, entries?: readonly Entry[]): NotificationPreview;
23
+ /** Separate ciphertext keeps legacy navigation plaintext byte-for-byte compatible. */
24
+ export declare function encryptNotificationPreview(pair: Pair, route: Envelope, identity: {
25
+ agentId: string;
26
+ kind: Kind;
27
+ timestamp: number;
28
+ }, preview: NotificationPreview): Promise<Envelope | undefined>;
29
+ export {};
@@ -0,0 +1,75 @@
1
+ import { buildAgentAttentionNotificationPayload, findLatestAssistantMessageFromTimeline } from '@getpaseo/protocol/agent-attention-notification';
2
+ import { sealEnvelope, decode } from './crypto.js';
3
+ const segmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
4
+ /** Bound UTF-8, retaining whole graphemes and removing invisible directional controls. */
5
+ export function notificationText(value, bytes) {
6
+ const clean = value.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, '').replace(/\s+/g, ' ').trim();
7
+ if (Buffer.byteLength(clean) <= bytes)
8
+ return clean;
9
+ let result = '', size = 0;
10
+ for (const { segment } of segmenter.segment(clean)) {
11
+ const n = Buffer.byteLength(segment);
12
+ if (size + n > bytes - 3)
13
+ break;
14
+ result += segment;
15
+ size += n;
16
+ }
17
+ return result.trimEnd() + '…';
18
+ }
19
+ function plain(value) {
20
+ // Generated documents are not readable notification prose and may contain executable-looking source.
21
+ const prose = value.replace(/```(?:paseo-openui|paseo-html|html)\b[^\n]*\n[\s\S]*?(?:```|$)/gi, '');
22
+ if (!prose.trim())
23
+ return '';
24
+ return buildAgentAttentionNotificationPayload({ reason: 'finished', serverId: '', workspaceId: '', agentId: '', assistantMessage: prose }).body;
25
+ }
26
+ function question(request) {
27
+ const rows = request.input?.questions;
28
+ if (!Array.isArray(rows))
29
+ return request.description || request.title || '';
30
+ return rows.slice(0, 3).map(row => {
31
+ if (!row || typeof row !== 'object')
32
+ return '';
33
+ const text = typeof row.question === 'string' ? row.question : '';
34
+ const options = Array.isArray(row.options) ? row.options.slice(0, 4).flatMap((o) => o && typeof o === 'object' && 'label' in o && typeof o.label === 'string' ? [o.label] : []) : [];
35
+ return text + (options.length ? ' ' + options.join(' / ') : '');
36
+ }).filter(Boolean).join(' ');
37
+ }
38
+ /** Only current-turn assistant prose or the exact pending request; never reasoning/tool output. */
39
+ export function buildNotificationPreview(agent, hostName, kind, request, entries = []) {
40
+ let body = '';
41
+ if (kind === 'finished') {
42
+ const start = agent.lastUserMessageAt ? Date.parse(agent.lastUserMessageAt) : NaN;
43
+ const lastUser = entries.findLastIndex(e => e.item.type === 'user_message');
44
+ const current = entries.slice(lastUser + 1).filter(e => !Number.isFinite(start) || Date.parse(e.timestamp) >= start).map(e => e.item);
45
+ body = plain(findLatestAssistantMessageFromTimeline(current) || '');
46
+ }
47
+ else if (kind === 'error')
48
+ body = plain(agent.lastError || '');
49
+ else if (request) {
50
+ body = plain(kind === 'question' ? question(request) : [request.title, request.description, typeof request.input?.plan === 'string' ? request.input.plan : undefined].filter(Boolean).join(' — ') || request.name);
51
+ }
52
+ return { title: notificationText(agent.title || '', 256), hostName: notificationText(hostName, 128), body: notificationText(body, 960) };
53
+ }
54
+ /** Separate ciphertext keeps legacy navigation plaintext byte-for-byte compatible. */
55
+ export async function encryptNotificationPreview(pair, route, identity, preview) {
56
+ let body = notificationText(preview.body, 960), title = notificationText(preview.title, 256), hostName = notificationText(preview.hostName, 128);
57
+ for (let attempt = 0; attempt < 4; attempt++) {
58
+ const payload = { type: 'notificationPreview', version: 1, ...identity, title, hostName, body };
59
+ // Size before encryption; GCM overhead and unpadded base64 lengths are deterministic.
60
+ const length = Math.ceil((Buffer.byteLength(JSON.stringify(payload)) + 16) * 4 / 3);
61
+ const candidate = { ...route, nonce: 'A'.repeat(16), ciphertext: 'A'.repeat(length) };
62
+ const push = { aps: { alert: { title: 'MoRemote', body: '一项任务需要你的回复。' }, sound: 'default', category: 'moremote.enhancement.permission', 'mutable-content': 1 }, pairId: route.pairId, eventId: route.id, kind: identity.kind, route, preview: candidate };
63
+ if (Buffer.byteLength(JSON.stringify(push)) <= 4096) {
64
+ return sealEnvelope(decode(pair.rootKey, 32), { version: 1, pairId: route.pairId, id: route.id, channel: 'attention', issuedAt: route.issuedAt, expiresAt: route.expiresAt }, payload);
65
+ }
66
+ if (body)
67
+ body = attempt === 0 ? notificationText(body, 240) : '';
68
+ else {
69
+ title = notificationText(title, 64);
70
+ hostName = notificationText(hostName, 32);
71
+ }
72
+ }
73
+ // Preserve the original valid notification when unusually large identifiers consume the budget.
74
+ return undefined;
75
+ }
@@ -3,8 +3,10 @@ import type { ServerInfoStatusPayload, AgentSnapshotPayload } from '@getpaseo/pr
3
3
  import type { Config, Pair } from './config.js';
4
4
  import type { Command, OfficialOperations } from './operations.js';
5
5
  import { type ReceiptState, type OperationJournal, type Occurrence } from './journal.js';
6
+ import { type NotificationPreview } from './notification-preview.js';
6
7
  import { type Evidence } from './evidence.js';
7
8
  export interface Attention {
9
+ preview?: NotificationPreview;
8
10
  agentId: string;
9
11
  requestId?: string;
10
12
  requestBinding?: string;
@@ -26,19 +28,88 @@ export declare class OfficialClient implements OfficialOperations {
26
28
  private journal?;
27
29
  readonly sdk: DaemonClient;
28
30
  private subscription;
31
+ private liveDirectory;
29
32
  readonly generation: `${string}-${string}-${string}-${string}-${string}`;
30
33
  private serverId;
31
34
  private callbacks;
32
35
  private unlisten;
36
+ private terminalPublished;
33
37
  private terminalReads;
38
+ private previewLanes;
39
+ private previewLane;
34
40
  private requestReads;
35
41
  private observationOrder;
42
+ private previewAgents;
36
43
  private pendingTasks;
37
44
  constructor(config: Config, journal?: OperationJournal | undefined);
38
45
  connect(): Promise<void>;
46
+ setLiveActivityEnabled(enabled: boolean): void;
47
+ liveActivitySnapshot(): {
48
+ daemonServerId: string;
49
+ hostName: string;
50
+ agents: {
51
+ id: string;
52
+ provider: string;
53
+ cwd: string;
54
+ model: string | null;
55
+ createdAt: string;
56
+ updatedAt: string;
57
+ lastUserMessageAt: string | null;
58
+ status: "error" | "initializing" | "idle" | "running" | "closed";
59
+ capabilities: import("@getpaseo/protocol/agent-types").AgentCapabilityFlags;
60
+ currentModeId: string | null;
61
+ availableModes: import("@getpaseo/protocol/agent-types").AgentMode[];
62
+ pendingPermissions: import("@getpaseo/protocol/agent-types").AgentPermissionRequest[];
63
+ persistence: import("@getpaseo/protocol/agent-types").AgentPersistenceHandle | null;
64
+ title: string | null;
65
+ labels: Record<string, string>;
66
+ workspaceId?: string | undefined;
67
+ features?: ({
68
+ type: "toggle";
69
+ id: string;
70
+ label: string;
71
+ value: boolean;
72
+ description?: string | undefined;
73
+ tooltip?: string | undefined;
74
+ icon?: string | undefined;
75
+ } | {
76
+ type: "select";
77
+ id: string;
78
+ label: string;
79
+ value: string | null;
80
+ options: {
81
+ id: string;
82
+ label: string;
83
+ description?: string | undefined;
84
+ isDefault?: boolean | undefined;
85
+ metadata?: Record<string, unknown> | undefined;
86
+ }[];
87
+ description?: string | undefined;
88
+ tooltip?: string | undefined;
89
+ icon?: string | undefined;
90
+ desktopTrigger?: "label" | "icon" | undefined;
91
+ })[] | undefined;
92
+ thinkingOptionId?: string | null | undefined;
93
+ effectiveThinkingOptionId?: string | null | undefined;
94
+ activeTurn?: {
95
+ turnId: string;
96
+ startedAt: string | null;
97
+ } | null | undefined;
98
+ runtimeInfo?: import("@getpaseo/protocol/agent-types").AgentRuntimeInfo | undefined;
99
+ lastUsage?: import("@getpaseo/protocol/agent-types").AgentUsage | undefined;
100
+ lastError?: string | undefined;
101
+ requiresAttention?: boolean | undefined;
102
+ attentionReason?: "permission" | "error" | "finished" | null | undefined;
103
+ attentionTimestamp?: string | null | undefined;
104
+ archivedAt?: string | null | undefined;
105
+ providerUnavailable?: boolean | undefined;
106
+ internal?: boolean | undefined;
107
+ }[];
108
+ } | null;
39
109
  info(): ServerInfoStatusPayload | null;
40
110
  private emit;
41
111
  private emitRequest;
112
+ private withPreviewSlot;
42
113
  private readTerminal;
43
114
  private terminalTimestamp;
44
115
  private fenceTerminalRead;
@@ -10,6 +10,8 @@ import { createHostClient, parseHostTarget } from '@getpaseo/client/node';
10
10
  import { normalizeLoopbackToLocalhost, parseConnectionUri } from '@getpaseo/protocol/daemon-endpoints';
11
11
  import { occurrenceBinding } from './bindings.js';
12
12
  import { LIMITS } from './limits.js';
13
+ import { buildNotificationPreview } from './notification-preview.js';
14
+ import { LiveDirectory } from './live-directory.js';
13
15
  import { evidenceForCommand, contentDigest } from './evidence.js';
14
16
  function boundedFile(path, max) { if (statSync(path).size > max)
15
17
  throw Error('OFFICIAL_FILE_LIMIT'); const raw = readFileSync(path, 'utf8'); if (Buffer.byteLength(raw) > max)
@@ -51,13 +53,18 @@ export class OfficialClient {
51
53
  journal;
52
54
  sdk;
53
55
  subscription;
56
+ liveDirectory;
54
57
  generation = randomUUID();
55
58
  serverId = '';
56
59
  callbacks = new Set();
57
60
  unlisten;
61
+ terminalPublished = new Map();
58
62
  terminalReads = new Map();
63
+ previewLanes = [Promise.resolve(), Promise.resolve()];
64
+ previewLane = 0;
59
65
  requestReads = new Set();
60
66
  observationOrder = 0;
67
+ previewAgents = new Map();
61
68
  pendingTasks = new Map();
62
69
  constructor(config, journal) {
63
70
  this.config = config;
@@ -65,6 +72,7 @@ export class OfficialClient {
65
72
  const target = config.target || localListen(config.paseoHome);
66
73
  const password = parseHostTarget(target).password || process.env.PASEO_PASSWORD;
67
74
  this.sdk = createHostClient(target, { clientId: config.clientId, clientType: 'cli', appVersion: 'moremote-cli/0.1.0', ...(password ? { password } : { localCredential: () => readLocalCredentialForTarget(config.paseoHome, target) }), reconnect: { enabled: false }, connectTimeoutMs: 15000, logger: { debug() { }, info() { }, warn() { }, error() { } } });
75
+ this.liveDirectory = new LiveDirectory(this.sdk);
68
76
  }
69
77
  async connect() {
70
78
  await this.sdk.connect();
@@ -118,6 +126,8 @@ export class OfficialClient {
118
126
  this.subscription = this.sdk.observeEvents(['agent_attention_required', 'agent_permission_request', 'agent_permission_resolved', 'status.server_info'], { notifications: false });
119
127
  await this.subscription.ready;
120
128
  }
129
+ setLiveActivityEnabled(enabled) { this.liveDirectory.setEnabled(enabled); }
130
+ liveActivitySnapshot() { const agents = this.liveDirectory.snapshot(); return agents ? { daemonServerId: this.serverId, hostName: this.info()?.hostname || hostname(), agents } : null; }
121
131
  info() { return this.sdk.getLastServerInfoMessage(); }
122
132
  emit(event) { if (Number.isSafeInteger(event.timestamp) && event.timestamp >= 0)
123
133
  for (const cb of this.callbacks)
@@ -129,12 +139,38 @@ export class OfficialClient {
129
139
  // Pending requests have independent lifetimes. The global attention clock can
130
140
  // still describe an older finished turn; never use it to expire a new request.
131
141
  // Runtime journals retain one observation clock per exact current occurrence.
132
- this.emit({ agentId, requestId: request.id, occurrence, kind: request.kind === 'question' ? 'question' : 'permission', timestamp: occurrence?.createdAt ?? Date.now() });
142
+ const agent = this.previewAgents.get(agentId);
143
+ this.emit({ agentId, requestId: request.id, occurrence, kind: request.kind === 'question' ? 'question' : 'permission', timestamp: occurrence?.createdAt ?? Date.now(), ...(agent ? { preview: buildNotificationPreview(agent, this.info()?.hostname || hostname(), request.kind === 'question' ? 'question' : 'permission', request) } : {}) });
133
144
  }
134
- readTerminal(event) {
145
+ async withPreviewSlot(body) {
146
+ const lane = this.previewLane++ % this.previewLanes.length;
147
+ const pending = this.previewLanes[lane].then(body);
148
+ this.previewLanes[lane] = pending.then(() => { }, () => { });
149
+ return pending;
150
+ }
151
+ readTerminal(event, initialAgent) {
135
152
  const read = { event, valid: true, next: null };
136
153
  this.terminalReads.set(event.agentId, read);
137
- const complete = (agent) => {
154
+ const complete = async (agent) => {
155
+ if (this.terminalReads.get(event.agentId) !== read)
156
+ return;
157
+ let entries = [];
158
+ const canonical = agent ? this.terminalTimestamp(agent, event) : null;
159
+ const published = canonical !== null && this.terminalPublished.get(event.agentId) === event.kind + ':' + canonical;
160
+ if (!published && read.valid && !read.next && agent && canonical !== null && event.kind === 'finished') {
161
+ try {
162
+ const timeline = await this.withPreviewSlot(async () => {
163
+ if (!read.valid || read.next || this.terminalReads.get(event.agentId) !== read || event.timestamp + LIMITS.snapshotMs <= Date.now())
164
+ return null;
165
+ return this.sdk.fetchAgentTimeline(event.agentId, { direction: 'tail', projection: 'canonical', limit: 30, timeout: 5000 });
166
+ });
167
+ if (!timeline || timeline.agentId !== event.agentId || this.terminalTimestamp(timeline.agent, event) !== canonical)
168
+ read.valid = false;
169
+ else if (!timeline.staleCursor && !timeline.gap)
170
+ entries = timeline.entries;
171
+ }
172
+ catch { /* Title/host remain useful when an optional read fails; never delay beyond five seconds. */ }
173
+ }
138
174
  if (this.terminalReads.get(event.agentId) !== read)
139
175
  return;
140
176
  this.terminalReads.delete(event.agentId);
@@ -142,15 +178,21 @@ export class OfficialClient {
142
178
  this.readTerminal(read.next);
143
179
  return;
144
180
  }
145
- if (!read.valid)
181
+ if (!read.valid || published)
146
182
  return;
147
183
  const timestamp = this.terminalTimestamp(agent, event);
148
- if (timestamp !== null)
149
- this.emit({ agentId: event.agentId, kind: event.kind, timestamp });
184
+ if (timestamp !== null && agent) {
185
+ if (this.terminalPublished.size >= LIMITS.attention && !this.terminalPublished.has(event.agentId))
186
+ this.terminalPublished.delete(this.terminalPublished.keys().next().value);
187
+ this.terminalPublished.set(event.agentId, event.kind + ':' + timestamp);
188
+ this.emit({ agentId: event.agentId, kind: event.kind, timestamp, preview: buildNotificationPreview(agent, this.info()?.hostname || hostname(), event.kind, undefined, entries) });
189
+ }
150
190
  };
151
- // At most one read and one latest event per agent; no retry without a new event.
152
- // Terminal hydration is read-only; stale replies must not resync requests.
153
- void this.sdk.fetchAgent({ agentId: event.agentId, timeout: 15000 }).then(value => complete(value?.agent || null)).catch(() => complete(null));
191
+ // One bounded optional canonical tail, never an additional live subscription or write.
192
+ if (initialAgent)
193
+ void complete(initialAgent);
194
+ else
195
+ void this.sdk.fetchAgent({ agentId: event.agentId, timeout: 15000 }).then(value => complete(value?.agent || null)).catch(() => complete(null));
154
196
  }
155
197
  terminalTimestamp(agent, event) {
156
198
  if (!agent || agent.id !== event.agentId || !agent.requiresAttention || agent.attentionReason !== event.kind || agent.activeTurn)
@@ -210,6 +252,10 @@ export class OfficialClient {
210
252
  }
211
253
  async current(agentId) { return this.readCurrent(agentId); }
212
254
  rememberRequests(agentId, agent) {
255
+ if (agent?.pendingPermissions.length)
256
+ this.previewAgents.set(agentId, agent);
257
+ else
258
+ this.previewAgents.delete(agentId);
213
259
  if (agent?.pendingPermissions.length)
214
260
  this.pendingTasks.set(agentId, projectTask(agent));
215
261
  else
@@ -259,8 +305,13 @@ export class OfficialClient {
259
305
  for (const a of agents) {
260
306
  for (const request of a.pendingPermissions)
261
307
  this.emitRequest(a.id, request);
262
- if (a.requiresAttention && a.attentionReason && a.attentionReason !== 'permission' && a.attentionTimestamp)
263
- this.emit({ agentId: a.id, kind: a.attentionReason, timestamp: Date.parse(a.attentionTimestamp) });
308
+ if (a.attentionReason && a.attentionReason !== 'permission' && a.attentionTimestamp && !this.terminalReads.has(a.id)) {
309
+ const event = { agentId: a.id, kind: a.attentionReason, timestamp: Date.parse(a.attentionTimestamp), observedOrder: read.observedOrder };
310
+ // Recovery uses the same fenced preview read as live events, without blocking
311
+ // directory/control polling or reading expired history. At most two tails run.
312
+ if (this.terminalTimestamp(a, event) !== null && event.timestamp + LIMITS.snapshotMs > Date.now() && this.terminalPublished.get(a.id) !== event.kind + ':' + event.timestamp)
313
+ this.readTerminal(event, a);
314
+ }
264
315
  }
265
316
  return { ...this.notificationSnapshot(), hostName: (info.hostname || hostname()).slice(0, 256), measuredAt: Date.now() };
266
317
  }
@@ -268,5 +319,5 @@ export class OfficialClient {
268
319
  this.requestReads.delete(read);
269
320
  }
270
321
  }
271
- async close() { this.pendingTasks.clear(); this.terminalReads.clear(); this.requestReads.clear(); this.unlisten?.(); await this.subscription?.release().catch(() => { }); await this.sdk.close(); }
322
+ async close() { this.liveDirectory.stop(); this.callbacks.clear(); this.terminalPublished.clear(); this.previewAgents.clear(); this.pendingTasks.clear(); this.terminalReads.clear(); this.requestReads.clear(); this.unlisten?.(); await this.subscription?.release().catch(() => { }); await this.sdk.close(); }
272
323
  }
package/dist/runtime.d.ts CHANGED
@@ -4,11 +4,12 @@ import { OperationJournal, type Occurrence } from './journal.js';
4
4
  export declare function queueAttention(journal: OperationJournal, pair: Pair, event: Attention & {
5
5
  sourceFingerprint?: string;
6
6
  occurrence?: Occurrence;
7
- }, now?: number): Promise<void>;
7
+ }, now?: number, includePreview?: boolean): Promise<void>;
8
8
  export declare function boundAttention(journal: OperationJournal, pair: Pair, event: Attention, official: Pick<OfficialClient, 'requestContext' | 'generation'>): Promise<Attention | {
9
9
  occurrence: Occurrence;
10
10
  sourceFingerprint: string;
11
11
  requestBinding: string;
12
+ preview?: import("./notification-preview.js").NotificationPreview;
12
13
  agentId: string;
13
14
  requestId?: string;
14
15
  kind: "finished" | "question" | "permission" | "error";
package/dist/runtime.js CHANGED
@@ -16,8 +16,11 @@ import { LIMITS, object } from './limits.js';
16
16
  import { NotificationStatePublisher } from './notification-state.js';
17
17
  import { LocalEnrollment } from './local-enrollment.js';
18
18
  import { inspectResource } from './resources.js';
19
+ import { LiveActivityPublisher } from './live-activity.js';
20
+ import { publishEvents } from './event-publication.js';
21
+ import { encryptNotificationPreview } from './notification-preview.js';
19
22
  function stableId(value) { const h = createHash('sha256').update(JSON.stringify(value)).digest('hex').slice(0, 32); return h.slice(0, 8) + '-' + h.slice(8, 12) + '-' + h.slice(12, 16) + '-' + h.slice(16, 20) + '-' + h.slice(20); }
20
- export async function queueAttention(journal, pair, event, now = Date.now()) {
23
+ export async function queueAttention(journal, pair, event, now = Date.now(), includePreview = true) {
21
24
  if (event.timestamp + LIMITS.snapshotMs <= now || event.timestamp > now + LIMITS.futureMs)
22
25
  return;
23
26
  const payload = { agentId: event.agentId, kind: event.kind, timestamp: event.timestamp, ...(event.requestId ? { requestId: event.requestId } : {}), ...(event.requestBinding ? { requestBinding: event.requestBinding } : {}) };
@@ -26,10 +29,11 @@ export async function queueAttention(journal, pair, event, now = Date.now()) {
26
29
  const id = event.requestId && event.occurrence ? stableId([pair.pairId, event.agentId, event.kind, event.requestId, 'occurrence', event.occurrence.occurrenceId]) : stableId([pair.pairId, event.agentId, event.kind, event.requestId || '', event.sourceFingerprint || '', event.requestId && !event.sourceFingerprint ? null : event.timestamp]);
27
30
  const issuedAt = event.timestamp;
28
31
  const envelope = await sealEnvelope(decode(pair.rootKey, 32), { version: 1, pairId: pair.pairId, id, channel: 'attention', issuedAt, expiresAt: issuedAt + LIMITS.snapshotMs }, payload);
32
+ const preview = includePreview && event.preview ? await encryptNotificationPreview(pair, envelope, { agentId: event.agentId, kind: event.kind, timestamp: event.timestamp }, event.preview) : undefined;
29
33
  const topic = await presenceTopic(decode(pair.rootKey, 32), pair.pairId, event.agentId);
30
34
  if (event.occurrence && !journal.isCurrent(event.occurrence))
31
35
  return;
32
- journal.queueAttention(pair.pairId, id, envelope.expiresAt, { id, kind: event.kind, topic, envelope }, payload);
36
+ journal.queueAttention(pair.pairId, id, envelope.expiresAt, { id, kind: event.kind, topic, envelope, ...(preview ? { preview } : {}) }, payload);
33
37
  }
34
38
  export async function boundAttention(journal, pair, event, official) {
35
39
  if (!event.requestId)
@@ -115,6 +119,7 @@ export async function runRuntime(dir, version) {
115
119
  let measuredAt = 0;
116
120
  let snapshot;
117
121
  const statePublisher = new NotificationStatePublisher();
122
+ const livePublisher = new LiveActivityPublisher(journal);
118
123
  const retryStates = new Map();
119
124
  const pollOrigins = new Set();
120
125
  process.once('SIGINT', stop);
@@ -252,6 +257,7 @@ export async function runRuntime(dir, version) {
252
257
  lastError = 'ATTENTION_QUEUE_LIMIT'; });
253
258
  measuredAt = 0;
254
259
  }
260
+ official.setLiveActivityEnabled(config.cloudEnabled && config.pairs.some(pair => pair.active && !journal.pairRevoked(pair.pairId) && !!clouds.get(pair.pairId)?.liveActivityInterest));
255
261
  try {
256
262
  await enrollment.cycle(config, official.info().serverId, pair => {
257
263
  const origin = pair.apiOrigin || config.apiOrigin;
@@ -285,7 +291,7 @@ export async function runRuntime(dir, version) {
285
291
  for (const event of events) {
286
292
  const bound = await boundAttention(journal, pair, event, official);
287
293
  if (bound)
288
- await queueAttention(journal, pair, bound);
294
+ await queueAttention(journal, pair, bound, Date.now(), clouds.get(pair.pairId)?.notificationPreviews === true);
289
295
  }
290
296
  for (const pair of config.pairs) {
291
297
  if (stopped)
@@ -329,16 +335,11 @@ export async function runRuntime(dir, version) {
329
335
  catch (error) {
330
336
  failure = error;
331
337
  }
332
- for (const item of journal.attention(pair.pairId, Date.now())) {
333
- if (!detailsCurrent && ['question', 'permission'].includes(item.body.kind))
334
- continue;
335
- try {
336
- await cloud.attention(item.body);
337
- journal.attentionSent(pair.pairId, item.id);
338
- }
339
- catch (error) {
340
- failure = error;
341
- }
338
+ try {
339
+ await publishEvents(pair, cloud, journal, livePublisher, official.liveActivitySnapshot(), detailsCurrent);
340
+ }
341
+ catch (error) {
342
+ failure = error;
342
343
  }
343
344
  // Publication failures are independent from acquisition. Preserve the normal
344
345
  // three-second command/control cadence while still surfacing degraded status.