@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 CHANGED
@@ -94,36 +94,18 @@ output. It installs no service. Existing custom origins and per-phone authority
94
94
  remain unchanged. Published 0.1.2 requires explicit origin/cloud configuration
95
95
  before using that legacy manual path.
96
96
 
97
- ## Optional activities and widget reloads — unreleased source
98
-
99
- Local source adds per-task encrypted Live Activity state and keyed widget-change
100
- fingerprints. These changes are **not in published 0.1.1**; the package version
101
- has not changed. They require a compatible native app and separately configured
102
- relay/APNs capabilities; installing the CLI alone enables neither surface.
103
- Cloud remains off by default.
104
-
105
- The phone owns task selection, encrypted read-only interest and native push
106
- tokens; the companion authenticates that interest against the pinned daemon and
107
- publishes bounded official task measurements. Up to eight interests per pairing
108
- expire within eight hours; activity states expire within ten minutes. Missing
109
- tasks are not reported finished. Acknowledged ongoing state renews from fresh
110
- measurements around every eight minutes; lost acknowledgements preserve exact
111
- ciphertext until expiry. Commands and controls do not await the optional activity
112
- lane. Widget reloads depend on meaningful snapshot changes, use the existing
113
- encrypted snapshot and are opportunistic, not realtime delivery.
114
-
115
- The relay sees opaque routing/equality tags, registration identities, tokens,
116
- environment, envelope metadata and ciphertext—not decrypted task titles or
117
- usage. Apple receives the token and push payload: encrypted activity content or
118
- a generic widget-change signal. Device rendering, widget freshness/offline
119
- behavior and APNs delivery for these new surfaces remain **pending acceptance**;
120
- APNs HTTP 200 means provider admission only. See [operator limits and failure
121
- semantics](docs/configuration.md#optional-activity-and-widget-surfaces-unreleased)
122
- and the [living wire contract](docs/specs/03-api-contract.md#opt-in-task-activities-and-widget-reloads).
97
+ ## Notification-only cloud boundary — unreleased source
98
+
99
+ Cloudflare supports native notifications and their explicit replies/approvals.
100
+ Widgets, Live Activities and ordinary app/extension sends use official Paseo
101
+ transport and shared device state; the companion no longer discovers activities,
102
+ registers system-surface tokens or uploads usage/directory snapshots. Current
103
+ notification forms retain exact occurrence bindings and immutable retry identity.
104
+ See [configuration](docs/configuration.md#notification-only-cloud-use).
123
105
 
124
106
  ## What leaves the computer
125
107
 
126
- 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 snapshots include verified daemon identity, host name, bounded task/title/current raw request metadata and actual available usage. 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.
108
+ 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.
127
109
 
128
110
  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.
129
111
  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.
@@ -150,3 +132,9 @@ Default CLI state uses `LOCALAPPDATA/MoRemoteCLI` on Windows, `~/Library/Applica
150
132
 
151
133
  Public release prerequisites, existing-secret setup and exact verification commands:
152
134
  [releasing](docs/releasing.md). Checked-in workflows are not proof of a published package.
135
+
136
+ Widgets, Live Activities and ordinary app/extension sends connect through Paseo
137
+ and local device state. They do not use this Cloudflare notification service.
138
+ Current request forms remain encrypted here only for notification replies and
139
+ approvals; no task directory or usage feed is uploaded. Source changes are
140
+ unreleased; existing production is unchanged until a separately authorized rollout.
@@ -35,18 +35,11 @@ export declare class CloudClient {
35
35
  revision: number;
36
36
  envelope: Envelope;
37
37
  }): Promise<Record<string, unknown>>;
38
- state(envelope: Envelope, widgetFingerprint?: string): Promise<Record<string, unknown>>;
38
+ state(envelope: Envelope): Promise<Record<string, unknown>>;
39
39
  attention(body: unknown): Promise<Record<string, unknown>>;
40
40
  controls(): Promise<Envelope[]>;
41
41
  controlReceipt(id: string, body: {
42
42
  envelope: Envelope;
43
43
  }): Promise<Record<string, unknown>>;
44
44
  resolveAttention(id: string, resolvedAt: number): Promise<Record<string, unknown>>;
45
- activities(signal?: AbortSignal): Promise<unknown[]>;
46
- activityState(id: string, body: {
47
- registrationId: string;
48
- topic: string;
49
- event: 'update' | 'end';
50
- envelope: Envelope;
51
- }, signal?: AbortSignal): Promise<Record<string, unknown>>;
52
45
  }
@@ -43,9 +43,7 @@ function recoveryRequest(method, path) {
43
43
  return suffix.length === 1 && ['GET', 'POST'].includes(method) || suffix.length === 2 && method === 'GET' || suffix.length === 3 && suffix[2] === 'receipt' && method === 'POST';
44
44
  if (suffix[0] === 'commands')
45
45
  return suffix.length === 2 && method === 'GET' || suffix.length === 3 && suffix[2] === 'receipt' && method === 'POST';
46
- return suffix[0] === 'attention' && suffix.length === 3 && suffix[2] === 'resolve' && method === 'POST'
47
- || suffix[0] === 'activities' && (suffix.length === 2 && method === 'DELETE' || suffix.length === 3 && suffix[2] === 'end' && method === 'PUT')
48
- || suffix[0] === 'widget-device' && suffix.length === 2 && method === 'DELETE';
46
+ return suffix[0] === 'attention' && suffix.length === 3 && suffix[2] === 'resolve' && method === 'POST';
49
47
  }
50
48
  export class CloudClient {
51
49
  pairId;
@@ -161,13 +159,10 @@ export class CloudClient {
161
159
  async dispatch(id) { const r = await this.request('POST', this.path('/commands/' + id + '/dispatch'), {}); if (typeof r.dispatchAllowed !== 'boolean')
162
160
  throw Error('INVALID_DISPATCH_RESPONSE'); return { dispatchAllowed: r.dispatchAllowed }; }
163
161
  receipt(id, body) { return this.request('POST', this.path('/commands/' + id + '/receipt'), body); }
164
- state(envelope, widgetFingerprint) { return this.request('PUT', this.path('/state'), { envelope, ...(widgetFingerprint ? { widgetFingerprint } : {}) }); }
162
+ state(envelope) { return this.request('PUT', this.path('/state'), { envelope }); }
165
163
  attention(body) { return this.request('POST', this.path('/attention'), body); }
166
164
  async controls() { const result = await this.request('GET', this.path('/controls')); if (!Array.isArray(result.controls) || result.controls.length > 100)
167
165
  throw Error('INVALID_CONTROL_PAGE'); return result.controls.map(row => object(row).envelope).filter(Boolean); }
168
166
  controlReceipt(id, body) { return this.request('POST', this.path('/controls/' + id + '/receipt'), body); }
169
167
  resolveAttention(id, resolvedAt) { return this.request('POST', this.path('/attention/' + id + '/resolve'), { resolvedAt }); }
170
- async activities(signal) { const result = await this.request('GET', this.path('/activities'), undefined, signal); if (!Array.isArray(result.subscriptions) || result.subscriptions.length > 8)
171
- throw Error('INVALID_ACTIVITY_PAGE'); return result.subscriptions; }
172
- activityState(id, body, signal) { return this.request('PUT', this.path('/activities/' + id + (body.event === 'end' ? '/end' : '/state')), body, signal); }
173
168
  }
@@ -0,0 +1,10 @@
1
+ import type { Pair } from './config.js';
2
+ import type { CloudClient } from './cloud-client.js';
3
+ import type { projectSnapshot } from './projection.js';
4
+ type NotificationState = Awaited<ReturnType<typeof projectSnapshot>>;
5
+ export declare class NotificationStatePublisher {
6
+ private publications;
7
+ retain(ids: string[]): void;
8
+ publish(pair: Pick<Pair, 'pairId' | 'rootKey'>, cloud: Pick<CloudClient, 'state'>, payload: NotificationState, now?: number): Promise<boolean>;
9
+ }
10
+ export {};
@@ -0,0 +1,36 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { decode, sealEnvelope } from './crypto.js';
3
+ import { canonical, digest } from './journal.js';
4
+ import { LIMITS } from './limits.js';
5
+ // State is encrypted notification hydration, never a general system-surface feed.
6
+ // Callers serialize publication per pair. Unknown acknowledgements retain bytes.
7
+ export class NotificationStatePublisher {
8
+ publications = new Map();
9
+ retain(ids) { const keep = new Set(ids); for (const id of this.publications.keys())
10
+ if (!keep.has(id))
11
+ this.publications.delete(id); }
12
+ async publish(pair, cloud, payload, now = Date.now()) {
13
+ const fingerprint = digest(canonical(payload));
14
+ let publication = this.publications.get(pair.pairId);
15
+ if (!payload.tasks.length && (!publication || publication.acknowledged && publication.fingerprint === fingerprint))
16
+ return true;
17
+ // An earlier unknown attempt is retried before publishing a newer observation.
18
+ for (let attempt = 0; attempt < 2; attempt++) {
19
+ const changed = !publication || publication.fingerprint !== fingerprint;
20
+ const renewal = payload.tasks.length > 0 && !!publication && publication.envelope.expiresAt - now <= 120000;
21
+ if (!publication || publication.envelope.expiresAt <= now || publication.acknowledged && (changed || renewal)) {
22
+ const issuedAt = Math.max(now, (publication?.envelope.issuedAt ?? -1) + 1);
23
+ const envelope = await sealEnvelope(decode(pair.rootKey, 32), { version: 1, pairId: pair.pairId, id: randomUUID(), channel: 'state', issuedAt, expiresAt: issuedAt + LIMITS.snapshotMs }, payload);
24
+ publication = { envelope, fingerprint, acknowledged: false };
25
+ this.publications.set(pair.pairId, publication);
26
+ }
27
+ if (!publication.acknowledged) {
28
+ await cloud.state(publication.envelope);
29
+ publication.acknowledged = true;
30
+ }
31
+ if (publication.fingerprint === fingerprint)
32
+ return true;
33
+ }
34
+ return false;
35
+ }
36
+ }
@@ -1,5 +1,5 @@
1
1
  import type { DaemonClient } from '@getpaseo/client/internal/daemon-client';
2
- import type { ServerInfoStatusPayload, AgentSnapshotPayload, ProviderUsage } from '@getpaseo/protocol/messages';
2
+ import type { ServerInfoStatusPayload, AgentSnapshotPayload } from '@getpaseo/protocol/messages';
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';
@@ -16,50 +16,11 @@ export declare function localListen(home: string): string;
16
16
  export declare function readLocalCredentialForTarget(home: string, target: string): string | undefined;
17
17
  export declare function projectTask(a: AgentSnapshotPayload): {
18
18
  agentId: string;
19
- provider: string;
20
- title: string | null;
21
- status: "error" | "running" | "idle" | "closed" | "initializing";
22
- createdAt: string;
23
- updatedAt: string;
24
- lastUserMessageAt: string | null;
25
- activeTurnStartedAt: string | null;
26
- cwd: string | null;
27
- requiresAttention: boolean;
28
- attentionReason: "permission" | "error" | "finished" | null;
29
19
  pendingRequests: {
30
20
  requestId: string;
31
21
  request: import("@getpaseo/protocol/agent-types").AgentPermissionRequest;
32
22
  }[];
33
23
  };
34
- export interface OfficialUsage {
35
- fetchedAt: string;
36
- providers: ProviderUsage[];
37
- }
38
- export declare function projectUsage(u: OfficialUsage): {
39
- fetchedAt: string;
40
- providers: {
41
- providerId: string;
42
- displayName: string;
43
- status: "error" | "unavailable" | "available";
44
- fetchedAt: string;
45
- windows: {
46
- id: string;
47
- label: string;
48
- usedPct: number | null;
49
- remainingPct: number | null;
50
- resetsAt: string | null;
51
- }[];
52
- balances: {
53
- id: string;
54
- label: string;
55
- used: number | null;
56
- remaining: number | null;
57
- limit: number | null;
58
- unit: "tokens" | "usd" | "credits" | "requests";
59
- resetsAt: string | null;
60
- }[] | undefined;
61
- }[];
62
- };
63
24
  export declare class OfficialClient implements OfficialOperations {
64
25
  readonly config: Config;
65
26
  private journal?;
@@ -72,6 +33,7 @@ export declare class OfficialClient implements OfficialOperations {
72
33
  private terminalReads;
73
34
  private requestReads;
74
35
  private observationOrder;
36
+ private pendingTasks;
75
37
  constructor(config: Config, journal?: OperationJournal | undefined);
76
38
  connect(): Promise<void>;
77
39
  info(): ServerInfoStatusPayload | null;
@@ -98,7 +60,7 @@ export declare class OfficialClient implements OfficialOperations {
98
60
  createdAt: string;
99
61
  updatedAt: string;
100
62
  lastUserMessageAt: string | null;
101
- status: "error" | "running" | "idle" | "closed" | "initializing";
63
+ status: "error" | "initializing" | "idle" | "running" | "closed";
102
64
  capabilities: import("@getpaseo/protocol/agent-types").AgentCapabilityFlags;
103
65
  currentModeId: string | null;
104
66
  availableModes: import("@getpaseo/protocol/agent-types").AgentMode[];
@@ -148,23 +110,18 @@ export declare class OfficialClient implements OfficialOperations {
148
110
  providerUnavailable?: boolean | undefined;
149
111
  internal?: boolean | undefined;
150
112
  } | null>;
151
- activityTask(agentId: string, signal?: AbortSignal): Promise<{
152
- agentId: string;
153
- provider: string;
154
- title: string | null;
155
- status: "error" | "running" | "idle" | "closed" | "initializing";
156
- createdAt: string;
157
- updatedAt: string;
158
- lastUserMessageAt: string | null;
159
- activeTurnStartedAt: string | null;
160
- cwd: string | null;
161
- requiresAttention: boolean;
162
- attentionReason: "permission" | "error" | "finished" | null;
163
- pendingRequests: {
164
- requestId: string;
165
- request: import("@getpaseo/protocol/agent-types").AgentPermissionRequest;
113
+ private rememberRequests;
114
+ notificationSnapshot(): {
115
+ version: number;
116
+ daemonServerId: string;
117
+ tasks: {
118
+ agentId: string;
119
+ pendingRequests: {
120
+ requestId: string;
121
+ request: import("@getpaseo/protocol/agent-types").AgentPermissionRequest;
122
+ }[];
166
123
  }[];
167
- } | null>;
124
+ };
168
125
  send(command: Extract<Command, {
169
126
  type: 'send';
170
127
  }>): Promise<void>;
@@ -174,28 +131,17 @@ export declare class OfficialClient implements OfficialOperations {
174
131
  reconcile(command: Command, pair?: Pick<Pair, 'pairId' | 'rootKey'>): Promise<ReceiptState | null>;
175
132
  reconcileEvidence(evidence: Evidence, pair?: Pick<Pair, 'pairId' | 'rootKey'>): Promise<ReceiptState | null>;
176
133
  snapshot(): Promise<{
177
- version: number;
178
- daemonServerId: string;
179
134
  hostName: string;
180
135
  measuredAt: number;
136
+ version: number;
137
+ daemonServerId: string;
181
138
  tasks: {
182
139
  agentId: string;
183
- provider: string;
184
- title: string | null;
185
- status: "error" | "running" | "idle" | "closed" | "initializing";
186
- createdAt: string;
187
- updatedAt: string;
188
- lastUserMessageAt: string | null;
189
- activeTurnStartedAt: string | null;
190
- cwd: string | null;
191
- requiresAttention: boolean;
192
- attentionReason: "permission" | "error" | "finished" | null;
193
140
  pendingRequests: {
194
141
  requestId: string;
195
142
  request: import("@getpaseo/protocol/agent-types").AgentPermissionRequest;
196
143
  }[];
197
144
  }[];
198
- usage: unknown;
199
145
  }>;
200
146
  close(): Promise<void>;
201
147
  }
@@ -45,8 +45,7 @@ export function readLocalCredentialForTarget(home, target) { try {
45
45
  catch {
46
46
  return undefined;
47
47
  } }
48
- export function projectTask(a) { return { agentId: a.id, provider: a.provider, title: a.title?.slice(0, 160) || null, status: a.status, createdAt: a.createdAt, updatedAt: a.updatedAt, lastUserMessageAt: a.lastUserMessageAt, activeTurnStartedAt: a.activeTurn?.startedAt ?? null, cwd: a.cwd?.slice(0, 1024) || null, requiresAttention: a.requiresAttention || false, attentionReason: a.attentionReason || null, pendingRequests: a.pendingPermissions.slice(0, 10).map(request => ({ requestId: request.id, request })) }; }
49
- export function projectUsage(u) { return { fetchedAt: u.fetchedAt, providers: u.providers.slice(0, 16).map(p => ({ providerId: p.providerId.slice(0, 128), displayName: p.displayName.slice(0, 128), status: p.status, fetchedAt: p.fetchedAt || u.fetchedAt, windows: p.windows.slice(0, 8).map(w => ({ id: w.id.slice(0, 128), label: w.label.slice(0, 128), usedPct: w.usedPct ?? null, remainingPct: w.remainingPct ?? null, resetsAt: w.resetsAt ?? null })), balances: p.balances?.slice(0, 8).map(b => ({ id: b.id.slice(0, 128), label: b.label.slice(0, 128), used: b.used ?? null, remaining: b.remaining ?? null, limit: b.limit ?? null, unit: b.unit, resetsAt: b.resetsAt ?? null })) })) }; }
48
+ export function projectTask(a) { return { agentId: a.id, pendingRequests: a.pendingPermissions.map(request => ({ requestId: request.id, request })) }; }
50
49
  export class OfficialClient {
51
50
  config;
52
51
  journal;
@@ -59,6 +58,7 @@ export class OfficialClient {
59
58
  terminalReads = new Map();
60
59
  requestReads = new Set();
61
60
  observationOrder = 0;
61
+ pendingTasks = new Map();
62
62
  constructor(config, journal) {
63
63
  this.config = config;
64
64
  this.journal = journal;
@@ -107,6 +107,12 @@ export class OfficialClient {
107
107
  const p = message.payload;
108
108
  this.fenceRequestReads(p.agentId, ++this.observationOrder);
109
109
  this.journal?.resolution(this.serverId, p.agentId, p.requestId, this.generation, p.resolution);
110
+ const task = this.pendingTasks.get(p.agentId);
111
+ if (task) {
112
+ task.pendingRequests = task.pendingRequests.filter(r => r.requestId !== p.requestId);
113
+ if (!task.pendingRequests.length)
114
+ this.pendingTasks.delete(p.agentId);
115
+ }
110
116
  }
111
117
  });
112
118
  this.subscription = this.sdk.observeEvents(['agent_attention_required', 'agent_permission_request', 'agent_permission_resolved', 'status.server_info'], { notifications: false });
@@ -193,6 +199,7 @@ export class OfficialClient {
193
199
  const agent = value?.agent || null;
194
200
  this.fenceTerminalRead(agentId, agent, read.observedOrder);
195
201
  this.journal?.syncRequests(this.serverId, agentId, this.generation, agent?.pendingPermissions || []);
202
+ this.rememberRequests(agentId, agent);
196
203
  // Observation, journal synchronization and notification share one fence.
197
204
  observe?.(agent);
198
205
  return agent;
@@ -202,7 +209,15 @@ export class OfficialClient {
202
209
  }
203
210
  }
204
211
  async current(agentId) { return this.readCurrent(agentId); }
205
- async activityTask(agentId, signal) { signal?.throwIfAborted(); const observationOrder = ++this.observationOrder; const value = await this.sdk.fetchAgent({ agentId, timeout: 250 }); signal?.throwIfAborted(); this.fenceTerminalRead(agentId, value?.agent || null, observationOrder); return value?.agent ? projectTask(value.agent) : null; }
212
+ rememberRequests(agentId, agent) {
213
+ if (agent?.pendingPermissions.length)
214
+ this.pendingTasks.set(agentId, projectTask(agent));
215
+ else
216
+ this.pendingTasks.delete(agentId);
217
+ }
218
+ // Only accepted source reads enter this cache. A limited discovery page cannot
219
+ // erase a still-current request previously observed through its exact event.
220
+ notificationSnapshot() { return { version: 1, daemonServerId: this.serverId, tasks: structuredClone([...this.pendingTasks.values()]) }; }
206
221
  async send(command) { if (!this.sdk.isConnected)
207
222
  throw Error('OFFICIAL_DISCONNECTED'); await this.sdk.sendAgentMessage(command.agentId, command.text, { messageId: command.messageId }); }
208
223
  async permission(command) { if (!this.sdk.isConnected)
@@ -238,6 +253,7 @@ export class OfficialClient {
238
253
  for (const a of agents) {
239
254
  this.fenceTerminalRead(a.id, a, read.observedOrder);
240
255
  this.journal?.syncRequests(this.serverId, a.id, this.generation, a.pendingPermissions);
256
+ this.rememberRequests(a.id, a);
241
257
  this.journal?.syncAttention(a.id, a.requiresAttention === true, a.attentionTimestamp ? Date.parse(a.attentionTimestamp) : null);
242
258
  }
243
259
  for (const a of agents) {
@@ -246,20 +262,11 @@ export class OfficialClient {
246
262
  if (a.requiresAttention && a.attentionReason && a.attentionReason !== 'permission' && a.attentionTimestamp)
247
263
  this.emit({ agentId: a.id, kind: a.attentionReason, timestamp: Date.parse(a.attentionTimestamp) });
248
264
  }
249
- let usage = null;
250
- if (info.features?.providerUsageList) {
251
- try {
252
- usage = projectUsage(await this.sdk.listProviderUsage());
253
- }
254
- catch {
255
- usage = null;
256
- }
257
- }
258
- return { version: 1, daemonServerId: info.serverId, hostName: (info.hostname || hostname()).slice(0, 256), measuredAt: Date.now(), tasks: agents.map(projectTask), usage };
265
+ return { ...this.notificationSnapshot(), hostName: (info.hostname || hostname()).slice(0, 256), measuredAt: Date.now() };
259
266
  }
260
267
  finally {
261
268
  this.requestReads.delete(read);
262
269
  }
263
270
  }
264
- async close() { this.terminalReads.clear(); this.requestReads.clear(); this.unlisten?.(); await this.subscription?.release().catch(() => { }); await this.sdk.close(); }
271
+ async close() { this.pendingTasks.clear(); this.terminalReads.clear(); this.requestReads.clear(); this.unlisten?.(); await this.subscription?.release().catch(() => { }); await this.sdk.close(); }
265
272
  }
@@ -2,28 +2,14 @@ import type { OfficialClient } from './official-client.js';
2
2
  import type { Pair } from './config.js';
3
3
  import { type OperationJournal } from './journal.js';
4
4
  export declare function projectSnapshot(source: Awaited<ReturnType<OfficialClient['snapshot']>>, pair: Pair, journal: OperationJournal, generation: string): Promise<{
5
+ version: number;
6
+ daemonServerId: string;
5
7
  tasks: {
8
+ agentId: string;
6
9
  pendingRequests: {
7
10
  requestId: string;
8
11
  requestBinding: string;
9
12
  request: import("@getpaseo/protocol/agent-types").AgentPermissionRequest;
10
13
  }[];
11
- agentId: string;
12
- provider: string;
13
- title: string | null;
14
- status: "error" | "running" | "idle" | "closed" | "initializing";
15
- createdAt: string;
16
- updatedAt: string;
17
- lastUserMessageAt: string | null;
18
- activeTurnStartedAt: string | null;
19
- cwd: string | null;
20
- requiresAttention: boolean;
21
- attentionReason: "permission" | "error" | "finished" | null;
22
14
  }[];
23
- tasksTruncated: boolean;
24
- version: number;
25
- daemonServerId: string;
26
- hostName: string;
27
- measuredAt: number;
28
- usage: unknown;
29
15
  }>;
@@ -1,35 +1,25 @@
1
1
  import { canonical, digest } from './journal.js';
2
2
  import { occurrenceBinding } from './bindings.js';
3
+ // Cloud state exists only to hydrate notification replies and approvals.
3
4
  export async function projectSnapshot(source, pair, journal, generation) {
4
5
  const tasks = [];
5
- let tasksTruncated = false;
6
- for (const task of source.tasks) {
7
- if (Buffer.byteLength(task.agentId) > 256) {
8
- tasksTruncated = true;
9
- continue;
10
- }
6
+ for (const task of [...source.tasks].sort((a, b) => a.agentId.localeCompare(b.agentId))) {
11
7
  const pendingRequests = [];
12
- for (const pending of task.pendingRequests) {
13
- if (Buffer.byteLength(pending.requestId) > 256 || Buffer.byteLength(JSON.stringify(pending.request)) > 8192) {
14
- tasksTruncated = true;
15
- continue;
16
- }
8
+ for (const pending of [...task.pendingRequests].sort((a, b) => a.requestId.localeCompare(b.requestId))) {
17
9
  const occurrence = journal.currentOccurrence(source.daemonServerId, task.agentId, pending.requestId);
18
10
  if (!occurrence || occurrence.generation !== generation || occurrence.fingerprint !== digest(canonical(pending.request)))
19
11
  continue;
12
+ if (Buffer.byteLength(task.agentId) > 256 || Buffer.byteLength(pending.requestId) > 256 || Buffer.byteLength(JSON.stringify(pending.request)) > 8192)
13
+ throw Error('NOTIFICATION_REQUEST_LIMIT');
20
14
  const requestBinding = await occurrenceBinding(pair, occurrence);
21
- if (!journal.isCurrent(occurrence))
22
- continue;
23
- pendingRequests.push({ requestId: pending.requestId, requestBinding, request: pending.request });
15
+ if (journal.isCurrent(occurrence))
16
+ pendingRequests.push({ requestId: pending.requestId, requestBinding, request: pending.request });
24
17
  }
25
- tasks.push({ ...task, pendingRequests });
26
- }
27
- const result = { ...source, tasks, tasksTruncated };
28
- while (Buffer.byteLength(JSON.stringify(result)) > 60000 && result.tasks.length) {
29
- result.tasks.pop();
30
- result.tasksTruncated = true;
18
+ if (pendingRequests.length)
19
+ tasks.push({ agentId: task.agentId, pendingRequests });
31
20
  }
21
+ const result = { version: 1, daemonServerId: source.daemonServerId, tasks };
32
22
  if (Buffer.byteLength(JSON.stringify(result)) > 60000)
33
- throw Error('SNAPSHOT_LIMIT');
23
+ throw Error('NOTIFICATION_STATE_LIMIT');
34
24
  return result;
35
25
  }
package/dist/runtime.js CHANGED
@@ -1,4 +1,4 @@
1
- import { randomUUID, createHash } from 'node:crypto';
1
+ import { createHash } from 'node:crypto';
2
2
  import { join } from 'node:path';
3
3
  import { setTimeout as sleep } from 'node:timers/promises';
4
4
  import { loadConfig, saveConfig, privateDirectory, pruneRetiredPairs } from './config.js';
@@ -13,7 +13,7 @@ import { occurrenceBinding } from './bindings.js';
13
13
  import { projectSnapshot } from './projection.js';
14
14
  import { ownRuntime } from './control.js';
15
15
  import { LIMITS, object } from './limits.js';
16
- import { ActivityPublisher, ActivityWorkLane, widgetFingerprint } from './activity.js';
16
+ import { NotificationStatePublisher } from './notification-state.js';
17
17
  import { LocalEnrollment } from './local-enrollment.js';
18
18
  import { inspectResource } from './resources.js';
19
19
  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); }
@@ -96,8 +96,6 @@ export async function runRuntime(dir, version) {
96
96
  const parentGone = () => { draining = true; drainWake.abort(); };
97
97
  let detach, closeJournal;
98
98
  const release = await ownRuntime(dir, () => ({ stage, lastError, activePairs, version: version ?? null }), stop);
99
- const activityLane = new ActivityWorkLane();
100
- let activityFailure = null, activityPairCursor = 0;
101
99
  const enrollment = new LocalEnrollment(dir);
102
100
  try {
103
101
  if (!inspectResource(join(dir, 'config.json'), 'file', true))
@@ -116,8 +114,7 @@ export async function runRuntime(dir, version) {
116
114
  let backoff = LIMITS.pollMs;
117
115
  let measuredAt = 0;
118
116
  let snapshot;
119
- const statePublications = new Map();
120
- const activityPublisher = new ActivityPublisher();
117
+ const statePublisher = new NotificationStatePublisher();
121
118
  const retryStates = new Map();
122
119
  const pollOrigins = new Set();
123
120
  process.once('SIGINT', stop);
@@ -128,8 +125,7 @@ export async function runRuntime(dir, version) {
128
125
  journal.cleanup(now);
129
126
  const config = await loadConfig(dir);
130
127
  pollOrigins.clear();
131
- let failure = activityFailure;
132
- activityFailure = null;
128
+ let failure;
133
129
  let acquisitionFailed = false;
134
130
  const clouds = new Map();
135
131
  const cycleFences = new Map();
@@ -153,10 +149,7 @@ export async function runRuntime(dir, version) {
153
149
  if (pruneRetiredPairs(config, now, journal))
154
150
  await saveConfig(dir, config);
155
151
  journal.cleanupRevocations(config.pairs.map(p => p.pairId), now);
156
- for (const pairId of statePublications.keys())
157
- if (!config.pairs.some(pair => pair.pairId === pairId))
158
- statePublications.delete(pairId);
159
- activityPublisher.retain(config.cloudEnabled ? config.pairs.filter(pair => pair.active && pair.relayRetiredAt === undefined && !journal.pairRevoked(pair.pairId)).map(pair => pair.pairId) : []);
152
+ statePublisher.retain(config.cloudEnabled ? config.pairs.filter(pair => pair.active && pair.relayRetiredAt === undefined && !journal.pairRevoked(pair.pairId)).map(pair => pair.pairId) : []);
160
153
  for (const origin of retryStates.keys())
161
154
  if (!config.pairs.some(pair => (pair.apiOrigin || config.apiOrigin) === origin))
162
155
  retryStates.delete(origin);
@@ -294,33 +287,6 @@ export async function runRuntime(dir, version) {
294
287
  if (bound)
295
288
  await queueAttention(journal, pair, bound);
296
289
  }
297
- if (!stopped && !draining) {
298
- const candidates = config.pairs.filter(pair => pair.active && pair.relayRetiredAt === undefined && !journal.pairRevoked(pair.pairId) && clouds.has(pair.pairId));
299
- const ordered = [...candidates.slice(activityPairCursor), ...candidates.slice(0, activityPairCursor)], activitySnapshot = snapshot, activityOfficial = official;
300
- // Schedule cached terminal recovery before any optional normal discovery.
301
- // The owned lane never delays command acquisition and is aborted/joined on drain.
302
- if (activityLane.start(async (signal) => {
303
- let optionalFailure;
304
- for (const terminalOnly of [true, false])
305
- for (const pair of ordered) {
306
- signal.throwIfAborted();
307
- if (!pair.active || journal.pairRevoked(pair.pairId))
308
- continue;
309
- const cloud = clouds.get(pair.pairId);
310
- try {
311
- await activityPublisher.publish(pair, cloud, activitySnapshot, Date.now(), (agentId, readSignal) => activityOfficial.activityTask(agentId, readSignal), { signal, terminalOnly });
312
- }
313
- catch (error) {
314
- if (signal.aborted)
315
- throw error;
316
- optionalFailure ??= error;
317
- }
318
- }
319
- if (optionalFailure)
320
- throw optionalFailure;
321
- }, error => { activityFailure = error; }, AbortSignal.any([controller.signal, drainWake.signal])))
322
- activityPairCursor = (activityPairCursor + 1) % Math.max(1, candidates.length);
323
- }
324
290
  for (const pair of config.pairs) {
325
291
  if (stopped)
326
292
  break;
@@ -347,20 +313,10 @@ export async function runRuntime(dir, version) {
347
313
  const active = await activatePending(config, dir, pair, cloud, official.info().serverId, snapshot.hostName);
348
314
  if (!active)
349
315
  continue;
316
+ let detailsCurrent = false;
350
317
  try {
351
- let publication = statePublications.get(pair.pairId);
352
- // A lost acknowledgement keeps the exact immutable envelope even across a
353
- // newer measurement. Expired display-only state can yield to a fresh sample.
354
- if (!publication || publication.envelope.expiresAt <= Date.now() || (publication.acknowledged && publication.envelope.issuedAt !== snapshot.measuredAt)) {
355
- const payload = await projectSnapshot(snapshot, pair, journal, official.generation);
356
- const envelope = await sealEnvelope(decode(pair.rootKey, 32), { version: 1, pairId: pair.pairId, id: randomUUID(), channel: 'state', issuedAt: snapshot.measuredAt, expiresAt: snapshot.measuredAt + LIMITS.snapshotMs }, payload);
357
- publication = { envelope, widgetFingerprint: await widgetFingerprint(pair, payload), acknowledged: false };
358
- statePublications.set(pair.pairId, publication);
359
- }
360
- if (!publication.acknowledged) {
361
- await cloud.state(publication.envelope, publication.widgetFingerprint);
362
- publication.acknowledged = true;
363
- }
318
+ const payload = await projectSnapshot({ ...official.notificationSnapshot(), hostName: snapshot.hostName, measuredAt: snapshot.measuredAt }, pair, journal, official.generation);
319
+ detailsCurrent = await statePublisher.publish(pair, cloud, payload);
364
320
  }
365
321
  catch (error) {
366
322
  failure = error;
@@ -374,6 +330,8 @@ export async function runRuntime(dir, version) {
374
330
  failure = error;
375
331
  }
376
332
  for (const item of journal.attention(pair.pairId, Date.now())) {
333
+ if (!detailsCurrent && ['question', 'permission'].includes(item.body.kind))
334
+ continue;
377
335
  try {
378
336
  await cloud.attention(item.body);
379
337
  journal.attentionSent(pair.pairId, item.id);
@@ -455,7 +413,6 @@ export async function runRuntime(dir, version) {
455
413
  process.removeListener('message', parentMessage);
456
414
  process.removeListener('disconnect', parentGone);
457
415
  try {
458
- await activityLane.close();
459
416
  detach?.();
460
417
  await official?.close().catch(() => { });
461
418
  }