@moxuli/moremote 0.1.6 → 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.
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  Optional, independent Apache-2.0 computer companion for MoRemote and an **unmodified Paseo 0.15.3** daemon. Existing official-only clients keep working without this project or its cloud.
4
4
 
5
5
  Canonical repository/command: `moremote-cli`; public npm package:
6
- **`@moxuli/moremote`** (published **0.1.2**); source entry: `bin/moremote-cli.js`.
6
+ **`@moxuli/moremote`** (release **0.1.7**); source entry: `bin/moremote-cli.js`.
7
7
  There is no unscoped npm alias or automatic adoption of foreign/old state.
8
8
 
9
9
  ## Install the published package
@@ -99,18 +99,19 @@ output. It installs no service. Existing custom origins and per-phone authority
99
99
  remain unchanged. Published 0.1.2 requires explicit origin/cloud configuration
100
100
  before using that legacy manual path.
101
101
 
102
- ## Notification-only cloud boundary — unreleased source
102
+ ## Cloud boundary
103
103
 
104
- Cloudflare supports native notifications and their explicit replies/approvals.
105
- Widgets, Live Activities and ordinary app/extension sends use official Paseo
106
- transport and shared device state; the companion no longer discovers activities,
107
- registers system-surface tokens or uploads usage/directory snapshots. Current
108
- notification forms retain exact occurrence bindings and immutable retry identity.
109
- See [configuration](docs/configuration.md#notification-only-cloud-use).
104
+ Cloudflare supports notifications, explicit replies/approvals and optional
105
+ phone-authorized remote updates to an already-started Live Activity. Notification
106
+ and activity changes share one bounded event POST; unchanged observations add no
107
+ Worker request. Widgets and ordinary app/extension reads and sends use official
108
+ Paseo transport and shared device state. No general directory or usage feed is
109
+ uploaded. See the [configuration](docs/configuration.md) and rollout evidence in
110
+ [STATE](docs/STATE.md).
110
111
 
111
112
  ## What leaves the computer
112
113
 
113
- The cloud sees pairing/operation/event identities, times, sizes, bounded transport states, scoped capability hashes and encrypted command/control/receipt/state/attention bodies. Attention routing includes a separately derived opaque conversation tag; default push text is generic. Endpoint-encrypted notification state includes only verified daemon identity and current occurrence-bound question/approval forms. Original supported question/approval forms are included only within strict bounds, to answer that exact request. No complete chat/history, code files, model keys or official Paseo passwords/local credentials are uploaded. The relay cannot decrypt or manufacture accepted commands. This is not forward secrecy.
114
+ The cloud sees pairing/operation/event identities, times, sizes, bounded transport states, scoped capability hashes and encrypted command/control/receipt/state/attention bodies. Attention routing includes a separately derived opaque conversation tag; provider fallback text is generic; supported native apps can decrypt the separately encrypted bounded alert preview. Endpoint-encrypted notification state includes only verified daemon identity and current occurrence-bound question/approval forms. Original supported question/approval forms are included only within strict bounds, to answer that exact request. No complete chat/history, code files, model keys or official Paseo passwords/local credentials are uploaded. The relay cannot decrypt or manufacture accepted commands. This is not forward secrecy.
114
115
 
115
116
  Only exact message sends and responses to an **actual current** question/approval are supported. Admission accepted is not task completion. Unknown official outcomes are reconciled, **never blindly resent**, even when the same message ID is available.
116
117
  Endpoint cancellation/revocation uses authenticated encrypted controls and durable local tombstones, not trust in a cloud DELETE result. An offline/withheld control is waiting/unknown, not endpoint-confirmed. A dispatched operation is too late to undo. Exact request-instance bindings retire on source/resolution/connection changes. Minimal revisioned encrypted receipts remain auditable for24h after original expiry, separately from short-lived user payloads; positive admission never regresses to unknown.
@@ -138,8 +139,27 @@ Default CLI state uses `LOCALAPPDATA/MoRemoteCLI` on Windows, `~/Library/Applica
138
139
  Public release prerequisites, existing-secret setup and exact verification commands:
139
140
  [releasing](docs/releasing.md). Checked-in workflows are not proof of a published package.
140
141
 
141
- Widgets, Live Activities and ordinary app/extension sends connect through Paseo
142
- and local device state. They do not use this Cloudflare notification service.
143
- Current request forms remain encrypted here only for notification replies and
144
- approvals; no task directory or usage feed is uploaded. Source changes are
145
- unreleased; existing production is unchanged until a separately authorized rollout.
142
+ Widgets and ordinary app/extension sends connect through Paseo and local device
143
+ state. Optional remote Live Activity delivery shares the notification service;
144
+ current request forms remain encrypted and exact-instance-bound. Full rollout
145
+ requires corresponding App and service versions; see STATE for actual availability.
146
+
147
+
148
+ ### Informative encrypted alerts
149
+
150
+ Task notifications can carry a bounded endpoint-encrypted session title, computer
151
+ name and current answer/question/approval/error excerpt. A native app notification
152
+ extension decrypts on device, preserving navigation and actions. The service
153
+ never receives plaintext, endpoint keys or full transcripts. This adds no cloud
154
+ requests, widget feed or Live Activity dependency. Older versions retain safe
155
+ fallback behavior; see the delivery/API contracts and current STATE for rollout.
156
+
157
+ ### Shared remote Live Activity updates
158
+
159
+ An optional phone-authorized v2 interest enables a separate owned Paseo directory
160
+ subscription. Semantic changes share one event request with pending notifications;
161
+ unchanged state adds no Worker request. The phone's already-started activity can
162
+ update/end through native APNs while the app is suspended. Each source computer
163
+ needs the corresponding CLI version. Local foreground behavior and direct Paseo
164
+ widgets remain available; push-to-start is not implemented. See
165
+ [[2026-11-15-remote-activity-and-shared-events]].
@@ -1,4 +1,5 @@
1
- import type { Envelope } from './crypto.js';
1
+ import { type Envelope } from './crypto.js';
2
+ import type { LiveContribution, LiveInterest } from './live-activity.js';
2
3
  import type { ReceiptState } from './journal.js';
3
4
  export declare class CloudError extends Error {
4
5
  readonly status: number;
@@ -19,6 +20,9 @@ export declare class CloudClient {
19
20
  private retryState;
20
21
  private cycleFence?;
21
22
  readonly origin: string;
23
+ notificationPreviews: boolean;
24
+ liveActivityV2: boolean;
25
+ liveActivityInterest?: LiveInterest;
22
26
  constructor(origin: string, pairId: string, token: string, allowLoopback?: boolean, fetcher?: typeof fetch, signal?: AbortSignal | undefined, retryState?: CloudRetryState, cycleFence?: CloudRetryState | undefined);
23
27
  request(method: string, path: string, body?: unknown, signal?: AbortSignal): Promise<Record<string, unknown>>;
24
28
  private path;
@@ -38,6 +42,11 @@ export declare class CloudClient {
38
42
  state(envelope: Envelope): Promise<Record<string, unknown>>;
39
43
  attention(body: unknown): Promise<Record<string, unknown>>;
40
44
  controls(): Promise<Envelope[]>;
45
+ events(attention: unknown[], activity?: LiveContribution): Promise<{
46
+ attention: Set<string>;
47
+ activity: boolean;
48
+ activityCode: string | undefined;
49
+ }>;
41
50
  controlReceipt(id: string, body: {
42
51
  envelope: Envelope;
43
52
  }): Promise<Record<string, unknown>>;
@@ -1,5 +1,7 @@
1
1
  import { validateOrigin } from './config.js';
2
2
  import { LIMITS, object } from './limits.js';
3
+ import { validateEnvelope } from './crypto.js';
4
+ import { UUID } from './limits.js';
3
5
  export class CloudError extends Error {
4
6
  status;
5
7
  retryAt;
@@ -53,6 +55,9 @@ export class CloudClient {
53
55
  retryState;
54
56
  cycleFence;
55
57
  origin;
58
+ notificationPreviews = false;
59
+ liveActivityV2 = false;
60
+ liveActivityInterest;
56
61
  constructor(origin, pairId, token, allowLoopback = false, fetcher = fetch, signal, retryState = {}, cycleFence) {
57
62
  this.pairId = pairId;
58
63
  this.token = token;
@@ -87,9 +92,13 @@ export class CloudClient {
87
92
  this.retryState.normalError = undefined;
88
93
  }
89
94
  const json = body === undefined ? undefined : JSON.stringify(body);
90
- if (json && Buffer.byteLength(json) > LIMITS.envelopeBytes)
95
+ if (json && Buffer.byteLength(json) > (method === 'POST' && path === this.path('/events') ? LIMITS.liveEventBytes : LIMITS.envelopeBytes))
91
96
  throw Error('REQUEST_LIMIT');
92
97
  const response = await this.fetcher(this.origin + '/v1' + path, { method, headers: { authorization: 'Bearer ' + this.token, ...(json ? { 'content-type': 'application/json' } : {}) }, body: json, signal: AbortSignal.any([AbortSignal.timeout(20000), ...(this.signal ? [this.signal] : []), ...(signal ? [signal] : [])]), redirect: 'error' });
98
+ if (response.ok) {
99
+ this.notificationPreviews = response.headers.get('x-moremote-notification-preview') === '1';
100
+ this.liveActivityV2 = response.headers.get('x-moremote-live-activity') === '2';
101
+ }
93
102
  const retryAt = retryDeadline(response.headers.get('Retry-After'), response.status, Date.now());
94
103
  const reader = response.body?.getReader();
95
104
  let size = 0;
@@ -161,8 +170,39 @@ export class CloudClient {
161
170
  receipt(id, body) { return this.request('POST', this.path('/commands/' + id + '/receipt'), body); }
162
171
  state(envelope) { return this.request('PUT', this.path('/state'), { envelope }); }
163
172
  attention(body) { return this.request('POST', this.path('/attention'), body); }
164
- async controls() { const result = await this.request('GET', this.path('/controls')); if (!Array.isArray(result.controls) || result.controls.length > 100)
165
- throw Error('INVALID_CONTROL_PAGE'); return result.controls.map(row => object(row).envelope).filter(Boolean); }
173
+ async controls() {
174
+ const result = await this.request('GET', this.path('/controls'));
175
+ if (!Array.isArray(result.controls) || result.controls.length > 100)
176
+ throw Error('INVALID_CONTROL_PAGE');
177
+ this.liveActivityInterest = undefined;
178
+ if (this.liveActivityV2 && result.liveActivity) {
179
+ const value = object(result.liveActivity);
180
+ if (typeof value.registrationId !== 'string' || !UUID.test(value.registrationId))
181
+ throw Error('INVALID_LIVE_ACTIVITY_REGISTRATION');
182
+ const interest = validateEnvelope(value.interest, Date.now());
183
+ if (interest.pairId !== this.pairId || interest.channel !== 'activityInterest')
184
+ throw Error('INVALID_LIVE_ACTIVITY_INTEREST');
185
+ this.liveActivityInterest = { registrationId: value.registrationId, interest };
186
+ }
187
+ return result.controls.map(row => object(row).envelope).filter(Boolean);
188
+ }
189
+ async events(attention, activity) {
190
+ const value = await this.request('POST', this.path('/events'), { attention, ...(activity ? { activity } : {}) });
191
+ if (!Array.isArray(value.attention) || value.attention.length !== attention.length)
192
+ throw Error('INVALID_EVENT_RESPONSE');
193
+ const accepted = new Set();
194
+ for (const item of value.attention) {
195
+ const row = object(item);
196
+ if (typeof row.id !== 'string' || typeof row.accepted !== 'boolean')
197
+ throw Error('INVALID_EVENT_RESPONSE');
198
+ if (row.accepted)
199
+ accepted.add(row.id);
200
+ }
201
+ const live = value.activity === undefined ? undefined : object(value.activity);
202
+ if (activity && typeof live?.accepted !== 'boolean')
203
+ throw Error('INVALID_ACTIVITY_RESPONSE');
204
+ return { attention: accepted, activity: live?.accepted === true, activityCode: typeof live?.code === 'string' ? live.code : undefined };
205
+ }
166
206
  controlReceipt(id, body) { return this.request('POST', this.path('/controls/' + id + '/receipt'), body); }
167
207
  resolveAttention(id, resolvedAt) { return this.request('POST', this.path('/attention/' + id + '/resolve'), { resolvedAt }); }
168
208
  }
@@ -0,0 +1,6 @@
1
+ import type { Pair } from './config.js';
2
+ import { CloudClient } from './cloud-client.js';
3
+ import type { OperationJournal } from './journal.js';
4
+ import { LiveActivityPublisher, type LiveSnapshot } from './live-activity.js';
5
+ /** Independent durable acknowledgements sharing one transport request. */
6
+ export declare function publishEvents(pair: Pair, cloud: CloudClient, journal: OperationJournal, publisher: LiveActivityPublisher, snapshot: LiveSnapshot | null, detailsCurrent: boolean): Promise<void>;
@@ -0,0 +1,48 @@
1
+ import { LIMITS } from './limits.js';
2
+ /** Independent durable acknowledgements sharing one transport request. */
3
+ export async function publishEvents(pair, cloud, journal, publisher, snapshot, detailsCurrent) {
4
+ const pending = journal.attention(pair.pairId, Date.now()).filter(item => detailsCurrent || !['question', 'permission'].includes(item.body.kind));
5
+ if (!cloud.liveActivityV2) {
6
+ for (const item of pending) {
7
+ await cloud.attention(item.body);
8
+ journal.attentionSent(pair.pairId, item.id);
9
+ }
10
+ return;
11
+ }
12
+ let failure;
13
+ const activity = cloud.liveActivityInterest && snapshot
14
+ ? await publisher.prepare(pair, cloud.liveActivityInterest, snapshot).catch(error => { failure = error; return undefined; }) : undefined;
15
+ // Never let an oversize optional display update block the notification outbox.
16
+ const live = activity && Buffer.byteLength(JSON.stringify({ attention: [], activity })) <= LIMITS.liveEventBytes ? activity : undefined;
17
+ if (activity && !live)
18
+ failure = Error('LIVE_ACTIVITY_BATCH_LIMIT');
19
+ const batch = [];
20
+ for (const item of pending.slice(0, 8)) {
21
+ if (Buffer.byteLength(JSON.stringify({ attention: [...batch.map(row => row.body), item.body], ...(live ? { activity: live } : {}) })) > LIMITS.liveEventBytes)
22
+ break;
23
+ batch.push(item);
24
+ }
25
+ if (batch.length || live) {
26
+ const result = await cloud.events(batch.map(item => item.body), live);
27
+ for (const item of batch)
28
+ if (result.attention.has(item.id))
29
+ journal.attentionSent(pair.pairId, item.id);
30
+ else
31
+ failure = Error('ATTENTION_NOT_ACCEPTED');
32
+ if (live) {
33
+ if (result.activity)
34
+ publisher.acknowledge(pair.pairId, live.registrationId, live.sequence);
35
+ else if (['live_activity_not_registered', 'live_activity_retired', 'live_activity_generation_changed'].includes(result.activityCode ?? ''))
36
+ publisher.stop(pair.pairId, live.registrationId, live.sequence);
37
+ else
38
+ failure = Error('LIVE_ACTIVITY_NOT_ACCEPTED');
39
+ }
40
+ }
41
+ // A single large legacy notification can still use its original bounded route.
42
+ if (pending.length && !batch.length) {
43
+ await cloud.attention(pending[0].body);
44
+ journal.attentionSent(pair.pairId, pending[0].id);
45
+ }
46
+ if (failure)
47
+ throw failure;
48
+ }
package/dist/journal.d.ts CHANGED
@@ -29,6 +29,9 @@ export declare function canonical(value: unknown): string;
29
29
  export declare class OperationJournal {
30
30
  private db;
31
31
  constructor(path: string);
32
+ livePublication<T>(pairId: string): T | undefined;
33
+ saveLivePublication(pairId: string, deadline: number, value: unknown): void;
34
+ removeLivePublication(pairId: string): void;
32
35
  get(pairId: string, id: string): JournalRecord | undefined;
33
36
  prepare(e: Envelope): {
34
37
  record: JournalRecord;
package/dist/journal.js CHANGED
@@ -18,13 +18,18 @@ export class OperationJournal {
18
18
  CREATE TABLE IF NOT EXISTS cancellations(pairId TEXT NOT NULL,id TEXT NOT NULL,at INTEGER NOT NULL,expiresAt INTEGER NOT NULL,PRIMARY KEY(pairId,id));
19
19
  CREATE TABLE IF NOT EXISTS occurrences(occurrenceId TEXT PRIMARY KEY,serverId TEXT NOT NULL,agentId TEXT NOT NULL,requestId TEXT NOT NULL,generation TEXT NOT NULL,fingerprint TEXT NOT NULL,active INTEGER NOT NULL,createdAt INTEGER NOT NULL);
20
20
  CREATE INDEX IF NOT EXISTS occurrence_current ON occurrences(serverId,agentId,requestId,active);
21
- CREATE TABLE IF NOT EXISTS resolutions(occurrenceId TEXT PRIMARY KEY,response TEXT NOT NULL,at INTEGER NOT NULL);`);
21
+ CREATE TABLE IF NOT EXISTS resolutions(occurrenceId TEXT PRIMARY KEY,response TEXT NOT NULL,at INTEGER NOT NULL);
22
+ CREATE TABLE IF NOT EXISTS live_publications(pairId TEXT PRIMARY KEY,deadline INTEGER NOT NULL,data TEXT NOT NULL);`);
22
23
  }
23
24
  catch (error) {
24
25
  this.db.close();
25
26
  throw error;
26
27
  }
27
28
  }
29
+ livePublication(pairId) { const row = this.db.prepare('SELECT data FROM live_publications WHERE pairId=?').get(pairId); return row ? JSON.parse(row.data) : undefined; }
30
+ saveLivePublication(pairId, deadline, value) { const data = JSON.stringify(value); if (Buffer.byteLength(data) > LIMITS.liveEventBytes * 2)
31
+ throw Error('LIVE_PUBLICATION_LIMIT'); this.db.prepare('INSERT INTO live_publications VALUES(?,?,?) ON CONFLICT(pairId) DO UPDATE SET deadline=excluded.deadline,data=excluded.data').run(pairId, deadline, data); }
32
+ removeLivePublication(pairId) { this.db.prepare('DELETE FROM live_publications WHERE pairId=?').run(pairId); }
28
33
  get(pairId, id) { const r = this.db.prepare('SELECT * FROM operations WHERE pairId=? AND id=?').get(pairId, id); return r ? { ...r, envelope: r.envelope ? JSON.parse(r.envelope) : null, receipt: r.receipt ? JSON.parse(r.receipt) : null, evidence: r.evidence ? JSON.parse(r.evidence) : null } : undefined; }
29
34
  prepare(e) { const old = this.get(e.pairId, e.id); if (old) {
30
35
  if (old.digest !== digest(e))
@@ -120,6 +125,7 @@ export class OperationJournal {
120
125
  attentionResolutions(pairId) { return this.db.prepare('SELECT id,resolvedAt FROM attention WHERE pairId=? AND resolvedAt IS NOT NULL AND resolveSent=0 LIMIT 100').all(pairId); }
121
126
  attentionResolutionSent(pairId, id) { this.db.prepare('UPDATE attention SET resolveSent=1 WHERE pairId=? AND id=?').run(pairId, id); }
122
127
  cleanup(now) {
128
+ this.db.prepare('DELETE FROM live_publications WHERE deadline<=?').run(now);
123
129
  this.db.prepare('UPDATE operations SET envelope=NULL WHERE expiresAt<=?').run(now);
124
130
  this.db.prepare('DELETE FROM operations WHERE expiresAt<?').run(now - LIMITS.retentionMs);
125
131
  this.db.prepare("UPDATE attention SET body='' WHERE expiresAt<=?").run(now);
package/dist/limits.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export declare const LIMITS: Readonly<{
2
2
  envelopeBytes: 131072;
3
+ liveEventBytes: 524288;
3
4
  responseBytes: number;
4
5
  receiptBytes: 8192;
5
6
  plainBytes: 65536;
package/dist/limits.js CHANGED
@@ -1,4 +1,4 @@
1
- export const LIMITS = Object.freeze({ envelopeBytes: 131072, responseBytes: 5 * 1024 * 1024, receiptBytes: 8192, plainBytes: 65536, commandMs: 300000, enrollmentMs: 600000, snapshotMs: 600000, futureMs: 120000, retentionMs: 86400000, tasks: 100, operations: 1000, attention: 1000, revocations: 4096, pollMs: 3000, maxBackoffMs: 30000 });
1
+ export const LIMITS = Object.freeze({ envelopeBytes: 131072, liveEventBytes: 524288, responseBytes: 5 * 1024 * 1024, receiptBytes: 8192, plainBytes: 65536, commandMs: 300000, enrollmentMs: 600000, snapshotMs: 600000, futureMs: 120000, retentionMs: 86400000, tasks: 100, operations: 1000, attention: 1000, revocations: 4096, pollMs: 3000, maxBackoffMs: 30000 });
2
2
  export const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
3
3
  export function object(value) { if (!value || typeof value !== 'object' || Array.isArray(value))
4
4
  throw Error('INVALID_OBJECT'); return value; }
@@ -0,0 +1,60 @@
1
+ import type { Pair } from './config.js';
2
+ import { type Envelope } from './crypto.js';
3
+ import { type OperationJournal } from './journal.js';
4
+ export interface LiveAgent {
5
+ id: string;
6
+ title: string | null;
7
+ status: string;
8
+ createdAt: string;
9
+ lastUserMessageAt: string | null;
10
+ activeTurn?: {
11
+ turnId: string;
12
+ startedAt: string | null;
13
+ } | null;
14
+ pendingPermissions: readonly {
15
+ id: string;
16
+ kind?: string;
17
+ }[];
18
+ requiresAttention?: boolean;
19
+ attentionReason?: string | null;
20
+ attentionTimestamp?: string | null;
21
+ internal?: boolean;
22
+ labels?: Record<string, string>;
23
+ archivedAt?: string | null;
24
+ }
25
+ export interface LiveSnapshot {
26
+ daemonServerId: string;
27
+ hostName: string;
28
+ agents: LiveAgent[];
29
+ }
30
+ export interface LiveInterest {
31
+ registrationId: string;
32
+ interest: Envelope;
33
+ }
34
+ type Phase = 'running' | 'waiting' | 'finished' | 'error' | 'idle';
35
+ interface Candidate {
36
+ topic: string;
37
+ cycle: string;
38
+ phase: Phase;
39
+ lastUserAt: number;
40
+ eventId?: string;
41
+ payload: Envelope;
42
+ }
43
+ export interface LiveContribution {
44
+ subscriptionId: string;
45
+ generation: string;
46
+ registrationId: string;
47
+ sequence: number;
48
+ measuredAt: number;
49
+ expiresAt: number;
50
+ candidates: Candidate[];
51
+ }
52
+ /** Durable display publication only. No command execution or remote tracking authority. */
53
+ export declare class LiveActivityPublisher {
54
+ private journal;
55
+ constructor(journal: OperationJournal);
56
+ prepare(pair: Pair, raw: LiveInterest, snapshot: LiveSnapshot, now?: number): Promise<LiveContribution | undefined>;
57
+ stop(pairId: string, registrationId: string, sequence: number): void;
58
+ acknowledge(pairId: string, registrationId: string, sequence: number): void;
59
+ }
60
+ export {};
@@ -0,0 +1,131 @@
1
+ import { createHmac, randomBytes, randomUUID, webcrypto } from 'node:crypto';
2
+ import { decode, openEnvelope, presenceTopic, validateEnvelope } from './crypto.js';
3
+ import { canonical } from './journal.js';
4
+ import { LIMITS, UUID, exact, object } from './limits.js';
5
+ /** Durable display publication only. No command execution or remote tracking authority. */
6
+ export class LiveActivityPublisher {
7
+ journal;
8
+ constructor(journal) {
9
+ this.journal = journal;
10
+ }
11
+ async prepare(pair, raw, snapshot, now = Date.now()) {
12
+ if (!pair.active || pair.revokedAt !== undefined || pair.relayRetiredAt !== undefined
13
+ || this.journal.pairRevoked(pair.pairId) || !UUID.test(raw.registrationId)
14
+ || raw.interest.channel !== 'activityInterest')
15
+ throw Error('INVALID_LIVE_ACTIVITY_SOURCE');
16
+ const value = object(await openEnvelope(decode(pair.rootKey, 32), raw.interest, now));
17
+ exact(value, ['version', 'subscriptionId', 'generation', 'hostID', 'hostLifetime', 'daemonServerId', 'displayKey', 'createdAt', 'deadline', 'hostName']);
18
+ if (value.version !== 2 || value.subscriptionId !== raw.interest.id || !UUID.test(String(value.generation))
19
+ || !UUID.test(String(value.hostLifetime)) || !identifier(value.hostID) || !identifier(value.daemonServerId)
20
+ || value.daemonServerId !== snapshot.daemonServerId || pair.daemonServerId && value.daemonServerId !== pair.daemonServerId
21
+ || !Number.isSafeInteger(value.createdAt) || Number(value.createdAt) < 0 || Number(value.createdAt) > now + LIMITS.futureMs
22
+ || Number(value.deadline) <= Number(value.createdAt)
23
+ || value.deadline !== raw.interest.expiresAt || Number(value.deadline) > Number(value.createdAt) + 28_800_000
24
+ || value.hostName !== undefined && (typeof value.hostName !== 'string' || Buffer.byteLength(value.hostName) > 240))
25
+ throw Error('INVALID_LIVE_ACTIVITY_INTEREST');
26
+ const interest = value, key = decode(interest.displayKey, 32);
27
+ let old = this.journal.livePublication(pair.pairId);
28
+ if (old?.registrationId !== raw.registrationId || old.deadline <= now)
29
+ old = undefined;
30
+ if (old?.stopped)
31
+ return;
32
+ if (old && !old.acknowledged && old.contribution.expiresAt > now)
33
+ return old.contribution;
34
+ const agents = snapshot.agents.filter(agent => !agent.internal && !agent.archivedAt && !agent.labels?.['paseo.parent-agent-id']?.trim());
35
+ if (new Set(agents.map(agent => agent.id)).size !== agents.length)
36
+ throw Error('DUPLICATE_LIVE_ACTIVITY_TARGET');
37
+ if (agents.length > 100)
38
+ throw Error('LIVE_ACTIVITY_CANDIDATE_LIMIT');
39
+ const cycles = {};
40
+ const projected = await Promise.all(agents.map(async (agent) => {
41
+ if (!identifier(agent.id) || (time(agent.lastUserMessageAt) ?? 0) > now)
42
+ throw Error('INVALID_LIVE_ACTIVITY_TARGET');
43
+ const lastUserAt = time(agent.lastUserMessageAt) ?? time(agent.createdAt) ?? 0;
44
+ const previous = old?.cycles[agent.id], turnId = agent.activeTurn?.turnId ?? null;
45
+ const cycle = !turnId && previous?.lastUserAt === lastUserAt ? previous.cycle
46
+ : tag(key, [interest.hostLifetime, agent.id, lastUserAt, turnId ?? '']);
47
+ cycles[agent.id] = { lastUserAt, turnId, cycle };
48
+ const phase = phaseFor(agent, now);
49
+ const topic = await presenceTopic(decode(pair.rootKey, 32), pair.pairId, agent.id);
50
+ const eventId = ['waiting', 'finished', 'error'].includes(phase)
51
+ ? tag(key, [cycle, phase, phase === 'waiting' ? canonical(agent.pendingPermissions) : agent.attentionTimestamp ?? '']) : undefined;
52
+ return { topic, cycle, phase, lastUserAt, ...(eventId ? { eventId } : {}),
53
+ state: { version: 1, subscriptionId: interest.subscriptionId, daemonServerId: snapshot.daemonServerId,
54
+ agentId: agent.id, title: bounded(agent.title || '会话', 160, 480),
55
+ hostName: bounded(interest.hostName ?? snapshot.hostName, 80, 240), phase, startedAt: null,
56
+ requiresAttention: phase === 'waiting', isTerminal: phase === 'finished' || phase === 'error' } };
57
+ }));
58
+ projected.sort((a, b) => a.topic.localeCompare(b.topic));
59
+ const fingerprint = canonical(projected);
60
+ if (old?.acknowledged && old.fingerprint === fingerprint && old.contribution.expiresAt - now > 120_000)
61
+ return;
62
+ const sequence = (old?.sequence ?? 0) + 1, measuredAt = Math.max(now, (old?.contribution.measuredAt ?? -1) + 1);
63
+ const expiresAt = Math.min(interest.deadline, measuredAt + 600_000);
64
+ const candidates = await Promise.all(projected.map(async (candidate) => {
65
+ const { state, ...routing } = candidate;
66
+ const plain = { version: 2, subscriptionId: interest.subscriptionId, generation: interest.generation,
67
+ hostID: interest.hostID, hostLifetime: interest.hostLifetime, topic: candidate.topic,
68
+ state: { ...state, measuredAt, expiresAt } };
69
+ const payload = await sealDisplay(key, { version: 1, pairId: pair.pairId, id: randomUUID(), channel: 'activityState',
70
+ issuedAt: measuredAt, expiresAt }, plain);
71
+ if (Buffer.byteLength(JSON.stringify(payload)) > 2700)
72
+ throw Error('LIVE_ACTIVITY_PAYLOAD_LIMIT');
73
+ return { ...routing, payload };
74
+ }));
75
+ const contribution = { subscriptionId: interest.subscriptionId, generation: interest.generation,
76
+ registrationId: raw.registrationId, sequence, measuredAt, expiresAt, candidates };
77
+ this.journal.saveLivePublication(pair.pairId, interest.deadline, { registrationId: raw.registrationId, fingerprint,
78
+ sequence, acknowledged: false, deadline: interest.deadline, contribution, cycles });
79
+ return contribution;
80
+ }
81
+ stop(pairId, registrationId, sequence) {
82
+ const publication = this.journal.livePublication(pairId);
83
+ if (!publication || publication.registrationId !== registrationId || publication.sequence !== sequence)
84
+ return;
85
+ publication.stopped = true;
86
+ this.journal.saveLivePublication(pairId, publication.deadline, publication);
87
+ }
88
+ acknowledge(pairId, registrationId, sequence) {
89
+ const publication = this.journal.livePublication(pairId);
90
+ if (!publication || publication.registrationId !== registrationId || publication.sequence !== sequence)
91
+ return;
92
+ publication.acknowledged = true;
93
+ this.journal.saveLivePublication(pairId, publication.deadline, publication);
94
+ }
95
+ }
96
+ function identifier(value) { return typeof value === 'string' && value.length > 0 && Buffer.byteLength(value) <= 512 && !/[\s/\\\x00-\x1f]/u.test(value); }
97
+ function time(value) { const parsed = value ? Date.parse(value) : NaN; return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : null; }
98
+ function tag(key, value) { return createHmac('sha256', key).update(JSON.stringify(value)).digest('base64url'); }
99
+ function phaseFor(agent, now) {
100
+ if (agent.status === 'error')
101
+ return 'error';
102
+ if (agent.status === 'closed')
103
+ return 'finished';
104
+ if (agent.pendingPermissions.length || agent.requiresAttention && agent.attentionReason === 'permission')
105
+ return 'waiting';
106
+ if (agent.activeTurn || ['running', 'initializing'].includes(agent.status))
107
+ return 'running';
108
+ const event = time(agent.attentionTimestamp), user = time(agent.lastUserMessageAt);
109
+ const current = event === null ? agent.requiresAttention : event <= now && (user === null || event >= user);
110
+ if (current && agent.attentionReason === 'error')
111
+ return 'error';
112
+ if (current && agent.attentionReason === 'finished')
113
+ return 'finished';
114
+ return 'idle';
115
+ }
116
+ function bounded(value, characters, bytes) {
117
+ let result = '', count = 0;
118
+ for (const { segment } of new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(value)) {
119
+ if (++count > characters || Buffer.byteLength(result) + Buffer.byteLength(segment) > bytes)
120
+ break;
121
+ result += segment;
122
+ }
123
+ return result;
124
+ }
125
+ async function sealDisplay(key, metadata, value) {
126
+ const nonce = randomBytes(12), cryptoKey = await webcrypto.subtle.importKey('raw', Uint8Array.from(key), 'AES-GCM', false, ['encrypt']);
127
+ const aad = Buffer.from(JSON.stringify([1, metadata.pairId, metadata.id, metadata.channel, metadata.issuedAt, metadata.expiresAt]));
128
+ const encrypted = await webcrypto.subtle.encrypt({ name: 'AES-GCM', iv: nonce, additionalData: aad }, cryptoKey, Buffer.from(JSON.stringify(value)));
129
+ const envelope = { ...metadata, nonce: nonce.toString('base64url'), ciphertext: Buffer.from(encrypted).toString('base64url') };
130
+ return validateEnvelope(envelope, metadata.issuedAt);
131
+ }
@@ -0,0 +1,16 @@
1
+ import type { DaemonClient } from '@getpaseo/client/internal/daemon-client';
2
+ import type { AgentSnapshotPayload } from '@getpaseo/protocol/messages';
3
+ /** A separately owned read interest, acquired only for an active phone activity. */
4
+ export declare class LiveDirectory {
5
+ private sdk;
6
+ private owner?;
7
+ private detach?;
8
+ private agents;
9
+ private ready;
10
+ private generation?;
11
+ private head;
12
+ constructor(sdk: DaemonClient);
13
+ setEnabled(enabled: boolean): void;
14
+ snapshot(): AgentSnapshotPayload[] | null;
15
+ stop(): void;
16
+ }
@@ -0,0 +1,78 @@
1
+ /** A separately owned read interest, acquired only for an active phone activity. */
2
+ export class LiveDirectory {
3
+ sdk;
4
+ owner;
5
+ detach;
6
+ agents = new Map();
7
+ ready = false;
8
+ generation;
9
+ head = -1;
10
+ constructor(sdk) {
11
+ this.sdk = sdk;
12
+ }
13
+ setEnabled(enabled) {
14
+ if (!enabled) {
15
+ this.stop();
16
+ return;
17
+ }
18
+ if (this.owner)
19
+ return;
20
+ const owner = this.sdk.observeAgents({ page: { limit: 100 }, filter: { includeArchived: false, includeInternal: false },
21
+ sort: [{ key: 'updated_at', direction: 'desc' }], timeout: 15000 });
22
+ this.owner = owner;
23
+ this.detach = owner.subscribe({
24
+ snapshot: value => {
25
+ if (this.owner !== owner)
26
+ return;
27
+ this.agents.clear();
28
+ this.generation = value.sync?.generation;
29
+ this.head = value.sync?.headSeq ?? -1;
30
+ for (const entry of value.entries.slice(0, 100))
31
+ this.agents.set(entry.agent.id, entry.agent);
32
+ this.ready = true;
33
+ },
34
+ update: message => {
35
+ if (this.owner !== owner || !this.ready || message.type !== 'agent_update')
36
+ return;
37
+ const value = message.payload;
38
+ if (this.generation && value.generation && value.generation !== this.generation) {
39
+ this.stop();
40
+ return;
41
+ }
42
+ const id = value.kind === 'upsert' ? value.agent.id : value.agentId;
43
+ if (value.seq !== undefined && value.seq <= this.head)
44
+ return;
45
+ if (value.seq !== undefined)
46
+ this.head = value.seq;
47
+ if (value.kind === 'remove')
48
+ this.agents.delete(id);
49
+ else if (value.agent.archivedAt || value.agent.internal)
50
+ this.agents.delete(id);
51
+ else
52
+ this.agents.set(id, value.agent);
53
+ // Keep active and waiting targets before older idle history within the bounded directory.
54
+ if (this.agents.size > 100) {
55
+ const ranked = [...this.agents.values()].sort((a, b) => Number(active(b)) - Number(active(a)) || b.updatedAt.localeCompare(a.updatedAt));
56
+ this.agents = new Map(ranked.slice(0, 100).map(agent => [agent.id, agent]));
57
+ }
58
+ },
59
+ error: () => { if (this.owner === owner)
60
+ this.stop(); },
61
+ });
62
+ void owner.ready.catch(() => { if (this.owner === owner)
63
+ this.stop(); });
64
+ }
65
+ snapshot() { return this.ready ? structuredClone([...this.agents.values()]) : null; }
66
+ stop() {
67
+ const owner = this.owner;
68
+ this.owner = undefined;
69
+ this.detach?.();
70
+ this.detach = undefined;
71
+ this.agents.clear();
72
+ this.ready = false;
73
+ this.generation = undefined;
74
+ this.head = -1;
75
+ void owner?.release().catch(() => { });
76
+ }
77
+ }
78
+ function active(agent) { return !!agent.activeTurn || agent.pendingPermissions.length > 0 || ['running', 'initializing'].includes(agent.status); }
@@ -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 {};