@moxuli/moremote 0.1.4 → 0.1.5
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 +15 -27
- package/dist/cloud-client.d.ts +1 -8
- package/dist/cloud-client.js +2 -7
- package/dist/notification-state.d.ts +10 -0
- package/dist/notification-state.js +36 -0
- package/dist/official-client.d.ts +16 -70
- package/dist/official-client.js +21 -14
- package/dist/projection.d.ts +3 -17
- package/dist/projection.js +11 -21
- package/dist/runtime.js +10 -53
- package/docs/STATE.md +36 -5
- package/docs/configuration.md +10 -49
- package/docs/native-enrollment-acceptance.md +21 -0
- package/docs/specs/01-architecture.md +14 -1
- package/docs/specs/02-encrypted-delivery.md +4 -4
- package/docs/specs/03-api-contract.md +18 -123
- package/package.json +29 -6
- package/dist/activity.d.ts +0 -79
- package/dist/activity.js +0 -193
package/dist/activity.js
DELETED
|
@@ -1,193 +0,0 @@
|
|
|
1
|
-
import { randomUUID } from 'node:crypto';
|
|
2
|
-
import { decode, openEnvelope, presenceTopic, sealEnvelope, validateEnvelope } from './crypto.js';
|
|
3
|
-
import { exact, LIMITS, object, text, UUID } from './limits.js';
|
|
4
|
-
import { CloudError } from './cloud-client.js';
|
|
5
|
-
/** Do not make absence from a bounded recent-task list a terminal event. */
|
|
6
|
-
export function taskActivityState(snapshot, task, subscriptionId, expiresAt) {
|
|
7
|
-
let phase = 'idle';
|
|
8
|
-
// A running turn supersedes an old attention flag retained by the daemon.
|
|
9
|
-
if (task.status === 'error')
|
|
10
|
-
phase = 'error';
|
|
11
|
-
else if (task.status === 'closed')
|
|
12
|
-
phase = 'finished';
|
|
13
|
-
else if (task.requiresAttention && task.attentionReason === 'permission')
|
|
14
|
-
phase = 'waiting';
|
|
15
|
-
else if (task.status === 'running' || task.status === 'initializing')
|
|
16
|
-
phase = 'running';
|
|
17
|
-
else if (task.requiresAttention && task.attentionReason === 'error')
|
|
18
|
-
phase = 'error';
|
|
19
|
-
else if (task.requiresAttention && task.attentionReason === 'finished')
|
|
20
|
-
phase = 'finished';
|
|
21
|
-
const candidate = Date.parse(task.activeTurnStartedAt || task.lastUserMessageAt || '');
|
|
22
|
-
const startedAt = Number.isSafeInteger(candidate) && candidate >= 0 && candidate <= snapshot.measuredAt ? candidate : null;
|
|
23
|
-
return { version: 1, subscriptionId, daemonServerId: snapshot.daemonServerId, agentId: task.agentId,
|
|
24
|
-
title: (task.title || '').slice(0, 160), hostName: snapshot.hostName.slice(0, 80), phase, startedAt,
|
|
25
|
-
measuredAt: snapshot.measuredAt, expiresAt, requiresAttention: task.requiresAttention, isTerminal: phase === 'finished' || phase === 'error' };
|
|
26
|
-
}
|
|
27
|
-
function semanticState(state) { const { measuredAt, expiresAt, ...semantic } = state; return JSON.stringify(semantic); }
|
|
28
|
-
function usageValues(value) {
|
|
29
|
-
if (Array.isArray(value))
|
|
30
|
-
return value.map(usageValues);
|
|
31
|
-
if (value && typeof value === 'object')
|
|
32
|
-
return Object.fromEntries(Object.entries(value).filter(([key]) => key !== 'fetchedAt').map(([key, item]) => [key, usageValues(item)]));
|
|
33
|
-
return value;
|
|
34
|
-
}
|
|
35
|
-
/** Keyed opaque equality token; no raw task, usage, or title enters cloud metadata. */
|
|
36
|
-
export async function widgetFingerprint(pair, snapshot) {
|
|
37
|
-
const tasks = snapshot.tasks.map(task => ({ agentId: task.agentId, provider: task.provider ?? null, createdAt: task.createdAt ?? null, title: task.title, status: task.status,
|
|
38
|
-
requiresAttention: task.requiresAttention, attentionReason: task.attentionReason,
|
|
39
|
-
lastUserMessageAt: task.lastUserMessageAt ?? null, activeTurnStartedAt: task.activeTurnStartedAt ?? null,
|
|
40
|
-
cwd: task.cwd ?? null, pendingRequestIds: task.pendingRequests?.map(p => p.requestId).sort() ?? [] })).sort((a, b) => a.agentId.localeCompare(b.agentId));
|
|
41
|
-
return presenceTopic(decode(pair.rootKey, 32), pair.pairId, JSON.stringify(['widgetSnapshot', { daemonServerId: snapshot.daemonServerId, hostName: snapshot.hostName, tasks, usage: usageValues(snapshot.usage) }]));
|
|
42
|
-
}
|
|
43
|
-
export async function openActivityInterest(pair, value, daemonServerId, now) {
|
|
44
|
-
const row = object(value);
|
|
45
|
-
exact(row, ['id', 'registrationId', 'topic', 'interest', 'expiresAt']);
|
|
46
|
-
if (Object.keys(row).length !== 5 || typeof row.id !== 'string' || !UUID.test(row.id) || typeof row.registrationId !== 'string' || !UUID.test(row.registrationId) || typeof row.topic !== 'string' || !Number.isSafeInteger(row.expiresAt))
|
|
47
|
-
throw Error('INVALID_ACTIVITY_SUBSCRIPTION');
|
|
48
|
-
decode(row.topic, 32);
|
|
49
|
-
const interest = validateEnvelope(row.interest, now);
|
|
50
|
-
if (interest.pairId !== pair.pairId || interest.id !== row.id || interest.channel !== 'activityInterest' || row.expiresAt !== interest.expiresAt)
|
|
51
|
-
throw Error('ACTIVITY_INTEREST_CONTEXT');
|
|
52
|
-
const plain = object(await openEnvelope(decode(pair.rootKey, 32), interest, now));
|
|
53
|
-
exact(plain, ['version', 'subscriptionId', 'daemonServerId', 'agentId']);
|
|
54
|
-
if (Object.keys(plain).length !== 4 || plain.version !== 1 || plain.subscriptionId !== row.id || plain.daemonServerId !== daemonServerId)
|
|
55
|
-
throw Error('ACTIVITY_INTEREST_CONTEXT');
|
|
56
|
-
const agentId = text(plain.agentId, 256);
|
|
57
|
-
if (await presenceTopic(decode(pair.rootKey, 32), pair.pairId, agentId) !== row.topic)
|
|
58
|
-
throw Error('ACTIVITY_TOPIC_MISMATCH');
|
|
59
|
-
return { id: row.id, registrationId: row.registrationId, topic: row.topic, interest, expiresAt: interest.expiresAt, agentId };
|
|
60
|
-
}
|
|
61
|
-
/** One bounded pass on the existing snapshot cadence. Never sends official mutations.
|
|
62
|
-
* Lost acknowledgements retry the same ciphertext; no alert/presence precondition.
|
|
63
|
-
*/
|
|
64
|
-
export class ActivityPublisher {
|
|
65
|
-
pairs = new Map();
|
|
66
|
-
retain(pairIds) { const retained = new Set(pairIds); for (const id of this.pairs.keys())
|
|
67
|
-
if (!retained.has(id))
|
|
68
|
-
this.pairs.delete(id); }
|
|
69
|
-
async publish(pair, cloud, snapshot, now = Date.now(), readTask, options = {}) {
|
|
70
|
-
const context = JSON.stringify([snapshot.daemonServerId, pair.rootKey]);
|
|
71
|
-
let state = this.pairs.get(pair.pairId);
|
|
72
|
-
if (!state || state.context !== context) {
|
|
73
|
-
state = { lastPoll: -Infinity, lastTerminalMeasurement: -Infinity, context, cursor: 0, subscriptions: [], publications: new Map() };
|
|
74
|
-
this.pairs.set(pair.pairId, state);
|
|
75
|
-
}
|
|
76
|
-
const current = () => { options.signal?.throwIfAborted(); if (this.pairs.get(pair.pairId) !== state)
|
|
77
|
-
throw Error('ACTIVITY_PAIR_RETIRED'); };
|
|
78
|
-
current();
|
|
79
|
-
if (options.terminalOnly) {
|
|
80
|
-
if (state.lastTerminalMeasurement >= snapshot.measuredAt)
|
|
81
|
-
return;
|
|
82
|
-
state.lastTerminalMeasurement = snapshot.measuredAt;
|
|
83
|
-
}
|
|
84
|
-
if (!options.terminalOnly) {
|
|
85
|
-
if (now - state.lastPoll < 30000)
|
|
86
|
-
return;
|
|
87
|
-
state.lastPoll = now;
|
|
88
|
-
const rows = await cloud.activities(options.signal);
|
|
89
|
-
current();
|
|
90
|
-
if (rows.length > 8)
|
|
91
|
-
throw Error('ACTIVITY_SUBSCRIPTION_LIMIT');
|
|
92
|
-
const subscriptions = [];
|
|
93
|
-
for (const row of rows) {
|
|
94
|
-
try {
|
|
95
|
-
subscriptions.push(await openActivityInterest(pair, row, snapshot.daemonServerId, now));
|
|
96
|
-
}
|
|
97
|
-
catch { /* Unauthenticated read-only interests never become authority. */ }
|
|
98
|
-
current();
|
|
99
|
-
}
|
|
100
|
-
state.subscriptions = subscriptions;
|
|
101
|
-
}
|
|
102
|
-
const subscriptions = state.subscriptions.filter(row => row.expiresAt > now);
|
|
103
|
-
const ids = new Set(subscriptions.map(row => row.id));
|
|
104
|
-
for (const id of state.publications.keys())
|
|
105
|
-
if (!ids.has(id))
|
|
106
|
-
state.publications.delete(id);
|
|
107
|
-
let failure;
|
|
108
|
-
const ordered = [...subscriptions.slice(state.cursor), ...subscriptions.slice(0, state.cursor)];
|
|
109
|
-
for (const subscription of ordered) {
|
|
110
|
-
try {
|
|
111
|
-
current();
|
|
112
|
-
state.cursor = (subscriptions.indexOf(subscription) + 1) % Math.max(1, subscriptions.length);
|
|
113
|
-
let publication = state.publications.get(subscription.id);
|
|
114
|
-
if (publication && (publication.body.registrationId !== subscription.registrationId || !publication.acknowledged && publication.body.envelope.expiresAt <= now))
|
|
115
|
-
publication = undefined;
|
|
116
|
-
let task = snapshot.tasks.find(task => task.agentId === subscription.agentId);
|
|
117
|
-
// Terminal recovery uses only cached authenticated interests and fresh source
|
|
118
|
-
// facts. Normal discovery/fallback work cannot consume its reserved path.
|
|
119
|
-
if (!task && readTask && !options.terminalOnly)
|
|
120
|
-
task = await readTask(subscription.agentId, options.signal) ?? undefined;
|
|
121
|
-
current();
|
|
122
|
-
if (!task || task.agentId !== subscription.agentId)
|
|
123
|
-
continue;
|
|
124
|
-
const expiresAt = Math.min(snapshot.measuredAt + LIMITS.snapshotMs, subscription.expiresAt);
|
|
125
|
-
if (expiresAt <= now)
|
|
126
|
-
continue;
|
|
127
|
-
const payload = taskActivityState(snapshot, task, subscription.id, expiresAt), fingerprint = semanticState(payload);
|
|
128
|
-
if (options.terminalOnly && !payload.isTerminal)
|
|
129
|
-
continue;
|
|
130
|
-
const renew = publication?.acknowledged && !payload.isTerminal && publication.body.envelope.expiresAt - now <= 120000 && snapshot.measuredAt > publication.body.envelope.issuedAt;
|
|
131
|
-
if (publication?.fingerprint === fingerprint && publication.acknowledged && !renew)
|
|
132
|
-
continue;
|
|
133
|
-
// Unknown admissions preserve immutable bytes. Fresh acknowledged running
|
|
134
|
-
// state renews at most once per eight minutes, before the ten-minute expiry.
|
|
135
|
-
if (!publication || publication.fingerprint !== fingerprint || renew) {
|
|
136
|
-
const envelope = await sealEnvelope(decode(pair.rootKey, 32), { version: 1, pairId: pair.pairId, id: randomUUID(), channel: 'activityState', issuedAt: snapshot.measuredAt, expiresAt }, payload);
|
|
137
|
-
current();
|
|
138
|
-
if (Buffer.byteLength(JSON.stringify(envelope)) > 3000)
|
|
139
|
-
throw Error('ACTIVITY_PAYLOAD_LIMIT');
|
|
140
|
-
publication = { fingerprint, body: { registrationId: subscription.registrationId, topic: subscription.topic, event: payload.isTerminal ? 'end' : 'update', envelope }, acknowledged: false };
|
|
141
|
-
state.publications.set(subscription.id, publication);
|
|
142
|
-
}
|
|
143
|
-
current();
|
|
144
|
-
if (!publication.acknowledged) {
|
|
145
|
-
await cloud.activityState(subscription.id, publication.body, options.signal);
|
|
146
|
-
current();
|
|
147
|
-
publication.acknowledged = true;
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
catch (error) {
|
|
151
|
-
if (options.signal?.aborted)
|
|
152
|
-
throw error;
|
|
153
|
-
// An authenticated rejection invalidates this cached target, not a new
|
|
154
|
-
// registration. Do not repeatedly consume recovery on a retired interest.
|
|
155
|
-
if (error instanceof CloudError && [404, 409].includes(error.status)) {
|
|
156
|
-
state.subscriptions = state.subscriptions.filter(row => row.id !== subscription.id);
|
|
157
|
-
state.publications.delete(subscription.id);
|
|
158
|
-
}
|
|
159
|
-
failure ??= error;
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
if (failure)
|
|
163
|
-
throw failure;
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
/** One owned optional lane, independent of the critical command/control loop.
|
|
167
|
-
* Network requests receive cancellation; SDK fallback reads have a 250ms timeout.
|
|
168
|
-
* close joins the real work rather than abandoning a raced promise.
|
|
169
|
-
*/
|
|
170
|
-
export class ActivityWorkLane {
|
|
171
|
-
running;
|
|
172
|
-
controller;
|
|
173
|
-
closed = false;
|
|
174
|
-
start(work, onError, parentSignal) {
|
|
175
|
-
if (this.closed || this.running || parentSignal?.aborted)
|
|
176
|
-
return false;
|
|
177
|
-
const controller = new AbortController();
|
|
178
|
-
this.controller = controller;
|
|
179
|
-
const signal = AbortSignal.any([controller.signal, ...(parentSignal ? [parentSignal] : [])]);
|
|
180
|
-
const timer = setTimeout(() => controller.abort(Error('ACTIVITY_PASS_DEADLINE')), 2000);
|
|
181
|
-
timer.unref();
|
|
182
|
-
this.running = Promise.resolve().then(() => work(signal)).catch(error => { if (!signal.aborted)
|
|
183
|
-
onError(error); }).finally(() => {
|
|
184
|
-
clearTimeout(timer);
|
|
185
|
-
if (this.controller === controller) {
|
|
186
|
-
this.running = undefined;
|
|
187
|
-
this.controller = undefined;
|
|
188
|
-
}
|
|
189
|
-
});
|
|
190
|
-
return true;
|
|
191
|
-
}
|
|
192
|
-
async close() { this.closed = true; this.controller?.abort(Error('ACTIVITY_LANE_CLOSED')); await this.running; }
|
|
193
|
-
}
|