@moxuli/moremote 0.1.6 → 0.1.8
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 +34 -14
- package/dist/activity-capabilities.d.ts +21 -0
- package/dist/activity-capabilities.js +107 -0
- package/dist/cloud-client.d.ts +10 -1
- package/dist/cloud-client.js +43 -3
- package/dist/enrollment-files.d.ts +1 -0
- package/dist/enrollment-files.js +7 -0
- package/dist/event-publication.d.ts +6 -0
- package/dist/event-publication.js +48 -0
- package/dist/journal.d.ts +3 -0
- package/dist/journal.js +7 -1
- package/dist/limits.d.ts +1 -0
- package/dist/limits.js +1 -1
- package/dist/live-activity-titles.d.ts +20 -0
- package/dist/live-activity-titles.js +34 -0
- package/dist/live-activity.d.ts +64 -0
- package/dist/live-activity.js +143 -0
- package/dist/live-directory.d.ts +19 -0
- package/dist/live-directory.js +87 -0
- package/dist/live-workspaces.d.ts +26 -0
- package/dist/live-workspaces.js +217 -0
- package/dist/notification-preview.d.ts +29 -0
- package/dist/notification-preview.js +75 -0
- package/dist/official-client.d.ts +74 -1
- package/dist/official-client.js +63 -12
- package/dist/resources.js +20 -2
- package/dist/runtime.d.ts +2 -1
- package/dist/runtime.js +14 -13
- package/docs/STATE.md +110 -515
- package/docs/configuration.md +33 -0
- package/docs/journal/2026-11-14-state-before-0.1.6-part-1.md +400 -0
- package/docs/journal/2026-11-14-state-before-0.1.6-part-2.md +115 -0
- package/docs/journal/2026-11-15-custom-origin-release.md +35 -0
- package/docs/journal/2026-11-15-informative-notifications-activity-release.md +31 -0
- package/docs/journal/2026-11-15-informative-notifications-and-settings.md +41 -0
- package/docs/journal/2026-11-15-live-activity-title-provenance.md +88 -0
- package/docs/journal/2026-11-15-remote-activity-local-acceptance.md +85 -0
- package/docs/journal/2026-11-15-title-provenance-release.md +86 -0
- package/docs/plans/2026-11-10-notification-delivery.md +8 -0
- package/docs/plans/2026-11-15-remote-activity-and-shared-events.md +99 -0
- package/docs/specs/01-architecture.md +15 -2
- package/docs/specs/02-encrypted-delivery.md +44 -0
- package/docs/specs/03-api-contract.md +54 -6
- package/docs/specs/04-control-and-receipt-lifecycle.md +5 -0
- package/docs/specs/05-endpoint-and-lifecycle.md +19 -0
- package/package.json +2 -2
- package/vectors/remote-activity-v2.json +30 -0
|
@@ -0,0 +1,143 @@
|
|
|
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
|
+
import { liveIdentifier as identifier, liveTitle, parseLiveTitleHints } from './live-activity-titles.js';
|
|
6
|
+
/** Durable display publication only. No command execution or remote tracking authority. */
|
|
7
|
+
export class LiveActivityPublisher {
|
|
8
|
+
journal;
|
|
9
|
+
constructor(journal) {
|
|
10
|
+
this.journal = journal;
|
|
11
|
+
}
|
|
12
|
+
async prepare(pair, raw, snapshot, now = Date.now()) {
|
|
13
|
+
if (!pair.active || pair.revokedAt !== undefined || pair.relayRetiredAt !== undefined
|
|
14
|
+
|| this.journal.pairRevoked(pair.pairId) || !UUID.test(raw.registrationId)
|
|
15
|
+
|| raw.interest.channel !== 'activityInterest')
|
|
16
|
+
throw Error('INVALID_LIVE_ACTIVITY_SOURCE');
|
|
17
|
+
const value = object(await openEnvelope(decode(pair.rootKey, 32), raw.interest, now));
|
|
18
|
+
exact(value, ['version', 'subscriptionId', 'generation', 'hostID', 'hostLifetime', 'daemonServerId', 'displayKey', 'createdAt', 'deadline', 'hostName', 'titleHints']);
|
|
19
|
+
const titleHints = parseLiveTitleHints(value.titleHints);
|
|
20
|
+
if (value.version !== 2 || value.subscriptionId !== raw.interest.id || !UUID.test(String(value.generation))
|
|
21
|
+
|| !UUID.test(String(value.hostLifetime)) || !identifier(value.hostID) || !identifier(value.daemonServerId)
|
|
22
|
+
|| value.daemonServerId !== snapshot.daemonServerId || pair.daemonServerId && value.daemonServerId !== pair.daemonServerId
|
|
23
|
+
|| !Number.isSafeInteger(value.createdAt) || Number(value.createdAt) < 0 || Number(value.createdAt) > now + LIMITS.futureMs
|
|
24
|
+
|| Number(value.deadline) <= Number(value.createdAt)
|
|
25
|
+
|| value.deadline !== raw.interest.expiresAt || Number(value.deadline) > Number(value.createdAt) + 28_800_000
|
|
26
|
+
|| value.hostName !== undefined && (typeof value.hostName !== 'string' || Buffer.byteLength(value.hostName) > 240))
|
|
27
|
+
throw Error('INVALID_LIVE_ACTIVITY_INTEREST');
|
|
28
|
+
const interest = value, key = decode(interest.displayKey, 32);
|
|
29
|
+
let old = this.journal.livePublication(pair.pairId);
|
|
30
|
+
if (old?.registrationId !== raw.registrationId || old.deadline <= now)
|
|
31
|
+
old = undefined;
|
|
32
|
+
if (old?.stopped)
|
|
33
|
+
return;
|
|
34
|
+
if (old && !old.acknowledged && old.contribution.expiresAt > now)
|
|
35
|
+
return old.contribution;
|
|
36
|
+
const agents = snapshot.agents.filter(agent => !agent.internal && !agent.archivedAt && !agent.labels?.['paseo.parent-agent-id']?.trim());
|
|
37
|
+
if (new Set(agents.map(agent => agent.id)).size !== agents.length)
|
|
38
|
+
throw Error('DUPLICATE_LIVE_ACTIVITY_TARGET');
|
|
39
|
+
if (agents.length > 100)
|
|
40
|
+
throw Error('LIVE_ACTIVITY_CANDIDATE_LIMIT');
|
|
41
|
+
for (const hint of titleHints) {
|
|
42
|
+
if (hint.source === 'workspace' && agents.some(agent => agent.id === hint.agentId && agent.workspaceId === hint.workspaceId)) {
|
|
43
|
+
try {
|
|
44
|
+
snapshot.requestWorkspace?.(hint.workspaceId);
|
|
45
|
+
}
|
|
46
|
+
catch { /* Metadata reads cannot block attention publication. */ }
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
const titles = agents.map(agent => liveTitle(agent, titleHints, snapshot.agents, snapshot.workspaces ?? []));
|
|
50
|
+
if (titles.some(title => title === undefined))
|
|
51
|
+
return;
|
|
52
|
+
const cycles = {};
|
|
53
|
+
const projected = await Promise.all(agents.map(async (agent, index) => {
|
|
54
|
+
if (!identifier(agent.id) || (time(agent.lastUserMessageAt) ?? 0) > now)
|
|
55
|
+
throw Error('INVALID_LIVE_ACTIVITY_TARGET');
|
|
56
|
+
const lastUserAt = time(agent.lastUserMessageAt) ?? time(agent.createdAt) ?? 0;
|
|
57
|
+
const previous = old?.cycles[agent.id], turnId = agent.activeTurn?.turnId ?? null;
|
|
58
|
+
const cycle = !turnId && previous?.lastUserAt === lastUserAt ? previous.cycle
|
|
59
|
+
: tag(key, [interest.hostLifetime, agent.id, lastUserAt, turnId ?? '']);
|
|
60
|
+
cycles[agent.id] = { lastUserAt, turnId, cycle };
|
|
61
|
+
const phase = phaseFor(agent, now);
|
|
62
|
+
const topic = await presenceTopic(decode(pair.rootKey, 32), pair.pairId, agent.id);
|
|
63
|
+
const eventId = ['waiting', 'finished', 'error'].includes(phase)
|
|
64
|
+
? tag(key, [cycle, phase, phase === 'waiting' ? canonical(agent.pendingPermissions) : agent.attentionTimestamp ?? '']) : undefined;
|
|
65
|
+
return { topic, cycle, phase, lastUserAt, ...(eventId ? { eventId } : {}),
|
|
66
|
+
state: { version: 1, subscriptionId: interest.subscriptionId, daemonServerId: snapshot.daemonServerId,
|
|
67
|
+
agentId: agent.id, title: bounded(titles[index], 160, 480),
|
|
68
|
+
hostName: bounded(interest.hostName ?? snapshot.hostName, 80, 240), phase, startedAt: null,
|
|
69
|
+
requiresAttention: phase === 'waiting', isTerminal: phase === 'finished' || phase === 'error' } };
|
|
70
|
+
}));
|
|
71
|
+
projected.sort((a, b) => a.topic.localeCompare(b.topic));
|
|
72
|
+
const fingerprint = canonical(projected);
|
|
73
|
+
if (old?.acknowledged && old.fingerprint === fingerprint && old.contribution.expiresAt - now > 120_000)
|
|
74
|
+
return;
|
|
75
|
+
const sequence = (old?.sequence ?? 0) + 1, measuredAt = Math.max(now, (old?.contribution.measuredAt ?? -1) + 1);
|
|
76
|
+
const expiresAt = Math.min(interest.deadline, measuredAt + 600_000);
|
|
77
|
+
const candidates = await Promise.all(projected.map(async (candidate) => {
|
|
78
|
+
const { state, ...routing } = candidate;
|
|
79
|
+
const plain = { version: 2, subscriptionId: interest.subscriptionId, generation: interest.generation,
|
|
80
|
+
hostID: interest.hostID, hostLifetime: interest.hostLifetime, topic: candidate.topic,
|
|
81
|
+
state: { ...state, measuredAt, expiresAt } };
|
|
82
|
+
const payload = await sealDisplay(key, { version: 1, pairId: pair.pairId, id: randomUUID(), channel: 'activityState',
|
|
83
|
+
issuedAt: measuredAt, expiresAt }, plain);
|
|
84
|
+
if (Buffer.byteLength(JSON.stringify(payload)) > 2700)
|
|
85
|
+
throw Error('LIVE_ACTIVITY_PAYLOAD_LIMIT');
|
|
86
|
+
return { ...routing, payload };
|
|
87
|
+
}));
|
|
88
|
+
const contribution = { subscriptionId: interest.subscriptionId, generation: interest.generation,
|
|
89
|
+
registrationId: raw.registrationId, sequence, measuredAt, expiresAt, candidates };
|
|
90
|
+
this.journal.saveLivePublication(pair.pairId, interest.deadline, { registrationId: raw.registrationId, fingerprint,
|
|
91
|
+
sequence, acknowledged: false, deadline: interest.deadline, contribution, cycles });
|
|
92
|
+
return contribution;
|
|
93
|
+
}
|
|
94
|
+
stop(pairId, registrationId, sequence) {
|
|
95
|
+
const publication = this.journal.livePublication(pairId);
|
|
96
|
+
if (!publication || publication.registrationId !== registrationId || publication.sequence !== sequence)
|
|
97
|
+
return;
|
|
98
|
+
publication.stopped = true;
|
|
99
|
+
this.journal.saveLivePublication(pairId, publication.deadline, publication);
|
|
100
|
+
}
|
|
101
|
+
acknowledge(pairId, registrationId, sequence) {
|
|
102
|
+
const publication = this.journal.livePublication(pairId);
|
|
103
|
+
if (!publication || publication.registrationId !== registrationId || publication.sequence !== sequence)
|
|
104
|
+
return;
|
|
105
|
+
publication.acknowledged = true;
|
|
106
|
+
this.journal.saveLivePublication(pairId, publication.deadline, publication);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
function time(value) { const parsed = value ? Date.parse(value) : NaN; return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : null; }
|
|
110
|
+
function tag(key, value) { return createHmac('sha256', key).update(JSON.stringify(value)).digest('base64url'); }
|
|
111
|
+
function phaseFor(agent, now) {
|
|
112
|
+
if (agent.status === 'error')
|
|
113
|
+
return 'error';
|
|
114
|
+
if (agent.status === 'closed')
|
|
115
|
+
return 'finished';
|
|
116
|
+
if (agent.pendingPermissions.length || agent.requiresAttention && agent.attentionReason === 'permission')
|
|
117
|
+
return 'waiting';
|
|
118
|
+
if (agent.activeTurn || ['running', 'initializing'].includes(agent.status))
|
|
119
|
+
return 'running';
|
|
120
|
+
const event = time(agent.attentionTimestamp), user = time(agent.lastUserMessageAt);
|
|
121
|
+
const current = event === null ? agent.requiresAttention : event <= now && (user === null || event >= user);
|
|
122
|
+
if (current && agent.attentionReason === 'error')
|
|
123
|
+
return 'error';
|
|
124
|
+
if (current && agent.attentionReason === 'finished')
|
|
125
|
+
return 'finished';
|
|
126
|
+
return 'idle';
|
|
127
|
+
}
|
|
128
|
+
function bounded(value, characters, bytes) {
|
|
129
|
+
let result = '', count = 0;
|
|
130
|
+
for (const { segment } of new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(value)) {
|
|
131
|
+
if (++count > characters || Buffer.byteLength(result) + Buffer.byteLength(segment) > bytes)
|
|
132
|
+
break;
|
|
133
|
+
result += segment;
|
|
134
|
+
}
|
|
135
|
+
return result;
|
|
136
|
+
}
|
|
137
|
+
async function sealDisplay(key, metadata, value) {
|
|
138
|
+
const nonce = randomBytes(12), cryptoKey = await webcrypto.subtle.importKey('raw', Uint8Array.from(key), 'AES-GCM', false, ['encrypt']);
|
|
139
|
+
const aad = Buffer.from(JSON.stringify([1, metadata.pairId, metadata.id, metadata.channel, metadata.issuedAt, metadata.expiresAt]));
|
|
140
|
+
const encrypted = await webcrypto.subtle.encrypt({ name: 'AES-GCM', iv: nonce, additionalData: aad }, cryptoKey, Buffer.from(JSON.stringify(value)));
|
|
141
|
+
const envelope = { ...metadata, nonce: nonce.toString('base64url'), ciphertext: Buffer.from(encrypted).toString('base64url') };
|
|
142
|
+
return validateEnvelope(envelope, metadata.issuedAt);
|
|
143
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
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
|
+
private workspaceDirectory;
|
|
13
|
+
constructor(sdk: DaemonClient);
|
|
14
|
+
setEnabled(enabled: boolean): void;
|
|
15
|
+
snapshot(): AgentSnapshotPayload[] | null;
|
|
16
|
+
workspaces(): import("./live-activity-titles.js").LiveWorkspace[];
|
|
17
|
+
requestWorkspace(id: string): void;
|
|
18
|
+
stop(): void;
|
|
19
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { LiveWorkspaces } from './live-workspaces.js';
|
|
2
|
+
/** A separately owned read interest, acquired only for an active phone activity. */
|
|
3
|
+
export class LiveDirectory {
|
|
4
|
+
sdk;
|
|
5
|
+
owner;
|
|
6
|
+
detach;
|
|
7
|
+
agents = new Map();
|
|
8
|
+
ready = false;
|
|
9
|
+
generation;
|
|
10
|
+
head = -1;
|
|
11
|
+
workspaceDirectory;
|
|
12
|
+
constructor(sdk) {
|
|
13
|
+
this.sdk = sdk;
|
|
14
|
+
this.workspaceDirectory = new LiveWorkspaces(sdk);
|
|
15
|
+
}
|
|
16
|
+
setEnabled(enabled) {
|
|
17
|
+
if (!enabled) {
|
|
18
|
+
this.stop();
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
if (this.owner) {
|
|
22
|
+
this.workspaceDirectory.setEnabled(true);
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
const owner = this.sdk.observeAgents({ page: { limit: 100 }, filter: { includeArchived: false, includeInternal: false },
|
|
26
|
+
sort: [{ key: 'updated_at', direction: 'desc' }], timeout: 15000 });
|
|
27
|
+
this.owner = owner;
|
|
28
|
+
this.detach = owner.subscribe({
|
|
29
|
+
snapshot: value => {
|
|
30
|
+
if (this.owner !== owner)
|
|
31
|
+
return;
|
|
32
|
+
this.agents.clear();
|
|
33
|
+
this.generation = value.sync?.generation;
|
|
34
|
+
this.head = value.sync?.headSeq ?? -1;
|
|
35
|
+
for (const entry of value.entries.slice(0, 100))
|
|
36
|
+
this.agents.set(entry.agent.id, entry.agent);
|
|
37
|
+
this.ready = true;
|
|
38
|
+
},
|
|
39
|
+
update: message => {
|
|
40
|
+
if (this.owner !== owner || !this.ready || message.type !== 'agent_update')
|
|
41
|
+
return;
|
|
42
|
+
const value = message.payload;
|
|
43
|
+
if (this.generation && value.generation && value.generation !== this.generation) {
|
|
44
|
+
this.stop();
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
const id = value.kind === 'upsert' ? value.agent.id : value.agentId;
|
|
48
|
+
if (value.seq !== undefined && value.seq <= this.head)
|
|
49
|
+
return;
|
|
50
|
+
if (value.seq !== undefined)
|
|
51
|
+
this.head = value.seq;
|
|
52
|
+
if (value.kind === 'remove')
|
|
53
|
+
this.agents.delete(id);
|
|
54
|
+
else if (value.agent.archivedAt || value.agent.internal)
|
|
55
|
+
this.agents.delete(id);
|
|
56
|
+
else
|
|
57
|
+
this.agents.set(id, value.agent);
|
|
58
|
+
// Keep active and waiting targets before older idle history within the bounded directory.
|
|
59
|
+
if (this.agents.size > 100) {
|
|
60
|
+
const ranked = [...this.agents.values()].sort((a, b) => Number(active(b)) - Number(active(a)) || b.updatedAt.localeCompare(a.updatedAt));
|
|
61
|
+
this.agents = new Map(ranked.slice(0, 100).map(agent => [agent.id, agent]));
|
|
62
|
+
}
|
|
63
|
+
},
|
|
64
|
+
error: () => { if (this.owner === owner)
|
|
65
|
+
this.stop(); },
|
|
66
|
+
});
|
|
67
|
+
void owner.ready.catch(() => { if (this.owner === owner)
|
|
68
|
+
this.stop(); });
|
|
69
|
+
this.workspaceDirectory.setEnabled(true);
|
|
70
|
+
}
|
|
71
|
+
snapshot() { return this.ready ? structuredClone([...this.agents.values()]) : null; }
|
|
72
|
+
workspaces() { return this.workspaceDirectory.snapshot(); }
|
|
73
|
+
requestWorkspace(id) { this.workspaceDirectory.request(id); }
|
|
74
|
+
stop() {
|
|
75
|
+
this.workspaceDirectory.stop();
|
|
76
|
+
const owner = this.owner;
|
|
77
|
+
this.owner = undefined;
|
|
78
|
+
this.detach?.();
|
|
79
|
+
this.detach = undefined;
|
|
80
|
+
this.agents.clear();
|
|
81
|
+
this.ready = false;
|
|
82
|
+
this.generation = undefined;
|
|
83
|
+
this.head = -1;
|
|
84
|
+
void owner?.release().catch(() => { });
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
function active(agent) { return !!agent.activeTurn || agent.pendingPermissions.length > 0 || ['running', 'initializing'].includes(agent.status); }
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { DaemonClient } from '@getpaseo/client/internal/daemon-client';
|
|
2
|
+
import { type LiveWorkspace } from './live-activity-titles.js';
|
|
3
|
+
/** Unknown metadata is distinct from an authoritative empty title. */
|
|
4
|
+
export declare class LiveWorkspaces {
|
|
5
|
+
private sdk;
|
|
6
|
+
private enabled;
|
|
7
|
+
private page?;
|
|
8
|
+
private exact;
|
|
9
|
+
private pageIDs;
|
|
10
|
+
private titles;
|
|
11
|
+
private readOrder;
|
|
12
|
+
private generation?;
|
|
13
|
+
private generationOrder;
|
|
14
|
+
private retiredGenerations;
|
|
15
|
+
constructor(sdk: DaemonClient);
|
|
16
|
+
setEnabled(enabled: boolean): void;
|
|
17
|
+
snapshot(): LiveWorkspace[];
|
|
18
|
+
request(id: string): void;
|
|
19
|
+
private observeExact;
|
|
20
|
+
private observe;
|
|
21
|
+
private acceptGeneration;
|
|
22
|
+
private remember;
|
|
23
|
+
private store;
|
|
24
|
+
private release;
|
|
25
|
+
stop(): void;
|
|
26
|
+
}
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
import { liveIdentifier } from './live-activity-titles.js';
|
|
2
|
+
/** Unknown metadata is distinct from an authoritative empty title. */
|
|
3
|
+
export class LiveWorkspaces {
|
|
4
|
+
sdk;
|
|
5
|
+
enabled = false;
|
|
6
|
+
page;
|
|
7
|
+
exact = new Map();
|
|
8
|
+
pageIDs = new Set();
|
|
9
|
+
titles = new Map();
|
|
10
|
+
readOrder = 0;
|
|
11
|
+
generation;
|
|
12
|
+
generationOrder = -1;
|
|
13
|
+
retiredGenerations = new Set();
|
|
14
|
+
constructor(sdk) {
|
|
15
|
+
this.sdk = sdk;
|
|
16
|
+
}
|
|
17
|
+
setEnabled(enabled) {
|
|
18
|
+
if (!enabled) {
|
|
19
|
+
this.stop();
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
this.enabled = true;
|
|
23
|
+
if (!this.page?.owner)
|
|
24
|
+
this.observe();
|
|
25
|
+
for (const [id, read] of this.exact)
|
|
26
|
+
if (!read.owner && !read.pending && !read.complete)
|
|
27
|
+
this.observeExact(id);
|
|
28
|
+
}
|
|
29
|
+
snapshot() { return structuredClone([...this.titles.values()].map(row => row.value).filter(value => value.title !== undefined)); }
|
|
30
|
+
request(id) {
|
|
31
|
+
if (!this.enabled || !liveIdentifier(id))
|
|
32
|
+
return;
|
|
33
|
+
if (this.pageIDs.has(id) && this.titles.get(id)?.value.title !== undefined)
|
|
34
|
+
return;
|
|
35
|
+
const previous = this.exact.get(id);
|
|
36
|
+
if (previous) {
|
|
37
|
+
this.exact.delete(id);
|
|
38
|
+
this.exact.set(id, previous);
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
if (this.exact.size >= 32) {
|
|
42
|
+
const oldest = this.exact.keys().next().value;
|
|
43
|
+
this.release(this.exact.get(oldest));
|
|
44
|
+
this.exact.delete(oldest);
|
|
45
|
+
}
|
|
46
|
+
this.observeExact(id);
|
|
47
|
+
}
|
|
48
|
+
observeExact(id) {
|
|
49
|
+
if (this.sdk.getLastServerInfoMessage()?.features?.ownedSubscriptions === true) {
|
|
50
|
+
this.observe(id);
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
// Legacy directory subscriptions share one last-query-wins server slot.
|
|
54
|
+
// A non-subscribing seed preserves the broad stream for every target.
|
|
55
|
+
const read = { order: ++this.readOrder, priority: 0, ready: false, head: -1, pending: true, abort: new AbortController() }, page = this.page, previous = this.titles.get(id);
|
|
56
|
+
this.exact.set(id, read);
|
|
57
|
+
void this.sdk.fetchWorkspaces({ page: { limit: 1 }, filter: { idPrefix: id, includeInternal: false, includeBackground: false }, signal: read.abort.signal })
|
|
58
|
+
.then(value => {
|
|
59
|
+
if (!this.enabled || this.exact.get(id) !== read || this.page !== page)
|
|
60
|
+
return;
|
|
61
|
+
read.generation = value.sync?.generation;
|
|
62
|
+
read.head = value.sync?.headSeq ?? -1;
|
|
63
|
+
if (this.titles.get(id) === previous && this.acceptGeneration(read)) {
|
|
64
|
+
for (const workspace of value.entries.slice(0, 1))
|
|
65
|
+
if (workspace.id === id)
|
|
66
|
+
this.remember(workspace, read, read.head, true);
|
|
67
|
+
}
|
|
68
|
+
read.complete = true;
|
|
69
|
+
}).catch(() => { }).finally(() => { read.pending = false; });
|
|
70
|
+
}
|
|
71
|
+
observe(id) {
|
|
72
|
+
const owner = this.sdk.observeWorkspaces({ page: { limit: id ? 1 : 100 }, filter: { includeInternal: false, includeBackground: false, ...(id ? { idPrefix: id } : {}) } });
|
|
73
|
+
const read = { order: ++this.readOrder, priority: id ? 2 : 1, owner, ready: false, head: -1 };
|
|
74
|
+
if (id)
|
|
75
|
+
this.exact.set(id, read);
|
|
76
|
+
else
|
|
77
|
+
this.page = read;
|
|
78
|
+
const current = () => this.enabled && read.owner === owner && (id ? this.exact.get(id) === read : this.page === read);
|
|
79
|
+
// Subscription snapshots arrive asynchronously; publishing never awaits their RPC.
|
|
80
|
+
read.detach = owner.subscribe({
|
|
81
|
+
snapshot: value => {
|
|
82
|
+
if (!current())
|
|
83
|
+
return;
|
|
84
|
+
read.generation = value.sync?.generation;
|
|
85
|
+
read.head = value.sync?.headSeq ?? -1;
|
|
86
|
+
read.ready = true;
|
|
87
|
+
if (!this.acceptGeneration(read)) {
|
|
88
|
+
this.release(read);
|
|
89
|
+
if (!id)
|
|
90
|
+
this.pageIDs.clear();
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
const entries = value.entries.slice(0, id ? 1 : 100).filter(workspace => !id || workspace.id === id);
|
|
94
|
+
if (!id) {
|
|
95
|
+
this.pageIDs = new Set(entries.map(workspace => workspace.id));
|
|
96
|
+
for (const exact of this.exact.values())
|
|
97
|
+
exact.complete = false;
|
|
98
|
+
}
|
|
99
|
+
for (const workspace of entries)
|
|
100
|
+
this.remember(workspace, read, read.head);
|
|
101
|
+
},
|
|
102
|
+
update: message => {
|
|
103
|
+
if (!current() || !read.ready || message.type !== 'workspace_update')
|
|
104
|
+
return;
|
|
105
|
+
const value = message.payload;
|
|
106
|
+
if (read.generation && value.generation && read.generation !== value.generation) {
|
|
107
|
+
this.release(read);
|
|
108
|
+
if (!id)
|
|
109
|
+
this.pageIDs.clear();
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
if (value.generation)
|
|
113
|
+
read.generation = value.generation;
|
|
114
|
+
if (value.seq !== undefined && value.seq <= read.head)
|
|
115
|
+
return;
|
|
116
|
+
if (value.seq !== undefined)
|
|
117
|
+
read.head = value.seq;
|
|
118
|
+
if (!this.acceptGeneration(read)) {
|
|
119
|
+
this.release(read);
|
|
120
|
+
if (!id)
|
|
121
|
+
this.pageIDs.clear();
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
const workspaceID = value.kind === 'remove' ? value.id : value.workspace.id;
|
|
125
|
+
if (id && workspaceID !== id)
|
|
126
|
+
return;
|
|
127
|
+
if (value.kind === 'remove') {
|
|
128
|
+
this.store({ id: workspaceID }, read, value.seq ?? -1);
|
|
129
|
+
this.pageIDs.delete(workspaceID);
|
|
130
|
+
}
|
|
131
|
+
else
|
|
132
|
+
this.remember(value.workspace, read, value.seq ?? -1);
|
|
133
|
+
},
|
|
134
|
+
error: () => { if (current()) {
|
|
135
|
+
this.release(read);
|
|
136
|
+
if (!id)
|
|
137
|
+
this.pageIDs.clear();
|
|
138
|
+
} },
|
|
139
|
+
});
|
|
140
|
+
void owner.ready.catch(() => { if (current()) {
|
|
141
|
+
this.release(read);
|
|
142
|
+
if (!id)
|
|
143
|
+
this.pageIDs.clear();
|
|
144
|
+
} });
|
|
145
|
+
return read;
|
|
146
|
+
}
|
|
147
|
+
acceptGeneration(read) {
|
|
148
|
+
if (!read.generation)
|
|
149
|
+
return true;
|
|
150
|
+
if (read.generation === this.generation) {
|
|
151
|
+
this.generationOrder = Math.max(this.generationOrder, read.order);
|
|
152
|
+
return true;
|
|
153
|
+
}
|
|
154
|
+
if (this.retiredGenerations.has(read.generation) || read.order < this.generationOrder)
|
|
155
|
+
return false;
|
|
156
|
+
if (this.generation)
|
|
157
|
+
this.retiredGenerations.add(this.generation);
|
|
158
|
+
while (this.retiredGenerations.size > 32)
|
|
159
|
+
this.retiredGenerations.delete(this.retiredGenerations.values().next().value);
|
|
160
|
+
this.generation = read.generation;
|
|
161
|
+
this.generationOrder = read.order;
|
|
162
|
+
return true;
|
|
163
|
+
}
|
|
164
|
+
remember(workspace, read, head, seed = false) {
|
|
165
|
+
const value = workspace.internal || workspace.background ? { id: workspace.id } : { id: workspace.id, title: workspace.title ?? null };
|
|
166
|
+
this.store(value, read, head, seed);
|
|
167
|
+
}
|
|
168
|
+
store(value, read, head, seed = false) {
|
|
169
|
+
const previous = this.titles.get(value.id);
|
|
170
|
+
if (previous) {
|
|
171
|
+
if (previous.generation && !read.generation)
|
|
172
|
+
return;
|
|
173
|
+
const sameGeneration = previous.generation === read.generation;
|
|
174
|
+
if (sameGeneration && head >= 0 && previous.head >= 0) {
|
|
175
|
+
if (head <= previous.head)
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
else if (sameGeneration && !seed && previous.read !== read) {
|
|
179
|
+
if (previous.read.priority > read.priority && (previous.read.owner || previous.read.order >= read.order)
|
|
180
|
+
|| previous.read.priority === read.priority && previous.read.order > read.order)
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
this.titles.delete(value.id);
|
|
185
|
+
this.titles.set(value.id, { value, read, generation: read.generation, head });
|
|
186
|
+
// Retained recovery rows and exact targets share a fixed memory budget.
|
|
187
|
+
while (this.titles.size > 132) {
|
|
188
|
+
const oldest = [...this.titles.keys()].find(id => !this.exact.has(id));
|
|
189
|
+
if (oldest === undefined)
|
|
190
|
+
break;
|
|
191
|
+
this.titles.delete(oldest);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
release(read) {
|
|
195
|
+
const owner = read.owner;
|
|
196
|
+
read.owner = undefined;
|
|
197
|
+
read.detach?.();
|
|
198
|
+
read.detach = undefined;
|
|
199
|
+
read.ready = false;
|
|
200
|
+
read.abort?.abort();
|
|
201
|
+
void owner?.release().catch(() => { });
|
|
202
|
+
}
|
|
203
|
+
stop() {
|
|
204
|
+
this.enabled = false;
|
|
205
|
+
if (this.page)
|
|
206
|
+
this.release(this.page);
|
|
207
|
+
this.page = undefined;
|
|
208
|
+
for (const read of this.exact.values())
|
|
209
|
+
this.release(read);
|
|
210
|
+
this.exact.clear();
|
|
211
|
+
this.pageIDs.clear();
|
|
212
|
+
this.titles.clear();
|
|
213
|
+
this.generation = undefined;
|
|
214
|
+
this.generationOrder = -1;
|
|
215
|
+
this.retiredGenerations.clear();
|
|
216
|
+
}
|
|
217
|
+
}
|
|
@@ -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
|
+
}
|