@moxuli/moremote 0.1.4 → 0.1.6

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
@@ -50,7 +50,7 @@ This explicit command authenticates the existing official daemon, enables cloud
50
50
  and automatic local enrollment, and installs/starts only the CLI's owned per-user
51
51
  background service. It preserves configured targets/custom HTTPS origins, active
52
52
  and revoked phones, and existing update preferences. With no origin configured,
53
- it selects `https://moremote-cloud-ingress.pages.dev`. It never starts, modifies
53
+ it selects `https://api.moremote.moxuli.com`. It never starts, modifies
54
54
  or upgrades Paseo or global tools. Source-checkout setup without managed state
55
55
  binds the current source frontend and retains manual updates. Installed packages
56
56
  or retained managed state require an enrollment-capable runtime: explicit setup
@@ -59,6 +59,11 @@ the automatic-update opt-out. A missing current package/capability fails clearly
59
59
  before enabling enrollment, never by substituting old public code. The immutable
60
60
  old package stays retained; its selected runtime/bootstrap move to capable code.
61
61
 
62
+ Existing installations keep their configured API origin, including
63
+ `https://moremote-cloud-ingress.pages.dev`. Retained pair origins and pending
64
+ offers remain unchanged; both domains must serve the same notification backend
65
+ directly, without an HTTP redirect or another pairing.
66
+
62
67
  Pair the computer **only in official Paseo**. A compatible MoRemote app uses
63
68
  that already authenticated connection's ordinary file channel to discover the
64
69
  optional CLI and enroll its own phone automatically, even before a workspace
@@ -94,36 +99,18 @@ output. It installs no service. Existing custom origins and per-phone authority
94
99
  remain unchanged. Published 0.1.2 requires explicit origin/cloud configuration
95
100
  before using that legacy manual path.
96
101
 
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).
102
+ ## Notification-only cloud boundary — unreleased source
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).
123
110
 
124
111
  ## What leaves the computer
125
112
 
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.
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.
127
114
 
128
115
  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
116
  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 +137,9 @@ Default CLI state uses `LOCALAPPDATA/MoRemoteCLI` on Windows, `~/Library/Applica
150
137
 
151
138
  Public release prerequisites, existing-secret setup and exact verification commands:
152
139
  [releasing](docs/releasing.md). Checked-in workflows are not proof of a published package.
140
+
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.
package/dist/cli.js CHANGED
@@ -17,6 +17,7 @@ import { OperationJournal } from './journal.js';
17
17
  const VERSION = await packageVersion();
18
18
  import { setupEnrollment } from './setup.js';
19
19
  import { setupServiceEntry } from './setup-upgrade.js';
20
+ import { DEFAULT_API_ORIGIN } from './local-enrollment.js';
20
21
  const HELP = `MoRemote CLI ${VERSION} — optional Paseo 0.15.3 enhancement
21
22
  Usage: moremote-cli <command> [options]
22
23
  setup --yes Enable automatic enrollment and own background service
@@ -179,7 +180,7 @@ async function main() {
179
180
  await stopped(dir);
180
181
  if (config.pairs.length >= 16)
181
182
  throw Error('PAIRING_LIMIT');
182
- const origin = validateOrigin(config.apiOrigin ?? 'https://moremote-cloud-ingress.pages.dev', config.allowLoopbackHttp);
183
+ const origin = validateOrigin(config.apiOrigin ?? DEFAULT_API_ORIGIN, config.allowLoopbackHttp);
183
184
  const official = new OfficialClient(config);
184
185
  try {
185
186
  await official.connect();
@@ -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
  }
@@ -1,7 +1,7 @@
1
1
  import { type Config, type Pair } from './config.js';
2
2
  import { CloudClient } from './cloud-client.js';
3
3
  import { EnrollmentFiles, type DiscoveryOptions } from './enrollment-files.js';
4
- export declare const DEFAULT_API_ORIGIN = "https://moremote-cloud-ingress.pages.dev";
4
+ export declare const DEFAULT_API_ORIGIN = "https://api.moremote.moxuli.com";
5
5
  export interface LocalEnrollmentOptions {
6
6
  clock?: () => number;
7
7
  files?: (options: DiscoveryOptions) => EnrollmentFiles;
@@ -2,7 +2,7 @@ import { saveConfig, validateOrigin } from './config.js';
2
2
  import { makeOffer, tokenHash } from './pairing.js';
3
3
  import { EnrollmentFiles } from './enrollment-files.js';
4
4
  import { parseEnrollmentRequest, requestFingerprint } from './enrollment-protocol.js';
5
- export const DEFAULT_API_ORIGIN = 'https://moremote-cloud-ingress.pages.dev';
5
+ export const DEFAULT_API_ORIGIN = 'https://api.moremote.moxuli.com';
6
6
  // The runtime's existing serialized cycle owns this consumer and its Config.
7
7
  // No watcher, background config writer, listener or official mutation is added.
8
8
  export class LocalEnrollment {
@@ -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
  }