@moxuli/moremote 0.1.2 → 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.
Files changed (41) hide show
  1. package/README.md +69 -50
  2. package/bin/moremote-cli.js +11 -4
  3. package/dist/cli.js +33 -7
  4. package/dist/cloud-client.d.ts +2 -9
  5. package/dist/cloud-client.js +3 -8
  6. package/dist/config.d.ts +7 -0
  7. package/dist/config.js +23 -4
  8. package/dist/enrollment-files.d.ts +37 -0
  9. package/dist/enrollment-files.js +225 -0
  10. package/dist/enrollment-protocol.d.ts +50 -0
  11. package/dist/enrollment-protocol.js +44 -0
  12. package/dist/local-enrollment.d.ts +25 -0
  13. package/dist/local-enrollment.js +160 -0
  14. package/dist/notification-state.d.ts +10 -0
  15. package/dist/notification-state.js +36 -0
  16. package/dist/official-client.d.ts +25 -65
  17. package/dist/official-client.js +83 -35
  18. package/dist/operations.d.ts +1 -0
  19. package/dist/operations.js +24 -4
  20. package/dist/projection.d.ts +3 -15
  21. package/dist/projection.js +11 -21
  22. package/dist/resources.d.ts +2 -1
  23. package/dist/resources.js +67 -31
  24. package/dist/runtime.d.ts +10 -1
  25. package/dist/runtime.js +81 -59
  26. package/dist/setup-upgrade.d.ts +2 -0
  27. package/dist/setup-upgrade.js +65 -0
  28. package/dist/setup.d.ts +12 -0
  29. package/dist/setup.js +38 -0
  30. package/docs/STATE.md +197 -13
  31. package/docs/configuration.md +70 -49
  32. package/docs/native-enrollment-acceptance.md +21 -0
  33. package/docs/specs/01-architecture.md +14 -1
  34. package/docs/specs/02-encrypted-delivery.md +4 -4
  35. package/docs/specs/03-api-contract.md +18 -123
  36. package/docs/specs/04-control-and-receipt-lifecycle.md +12 -0
  37. package/docs/specs/05-endpoint-and-lifecycle.md +126 -2
  38. package/docs/specs/06-managed-updates.md +25 -0
  39. package/package.json +29 -6
  40. package/dist/activity.d.ts +0 -77
  41. package/dist/activity.js +0 -193
@@ -1,13 +1,14 @@
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
- import { type ReceiptState, type OperationJournal } from './journal.js';
5
+ import { type ReceiptState, type OperationJournal, type Occurrence } from './journal.js';
6
6
  import { type Evidence } from './evidence.js';
7
7
  export interface Attention {
8
8
  agentId: string;
9
9
  requestId?: string;
10
10
  requestBinding?: string;
11
+ occurrence?: Occurrence;
11
12
  kind: 'finished' | 'question' | 'permission' | 'error';
12
13
  timestamp: number;
13
14
  }
@@ -15,48 +16,11 @@ export declare function localListen(home: string): string;
15
16
  export declare function readLocalCredentialForTarget(home: string, target: string): string | undefined;
16
17
  export declare function projectTask(a: AgentSnapshotPayload): {
17
18
  agentId: string;
18
- title: string | null;
19
- status: "error" | "running" | "idle" | "closed" | "initializing";
20
- updatedAt: string;
21
- lastUserMessageAt: string | null;
22
- activeTurnStartedAt: string | null;
23
- cwd: string | null;
24
- requiresAttention: boolean;
25
- attentionReason: "permission" | "error" | "finished" | null;
26
19
  pendingRequests: {
27
20
  requestId: string;
28
21
  request: import("@getpaseo/protocol/agent-types").AgentPermissionRequest;
29
22
  }[];
30
23
  };
31
- export interface OfficialUsage {
32
- fetchedAt: string;
33
- providers: ProviderUsage[];
34
- }
35
- export declare function projectUsage(u: OfficialUsage): {
36
- fetchedAt: string;
37
- providers: {
38
- providerId: string;
39
- displayName: string;
40
- status: "error" | "unavailable" | "available";
41
- fetchedAt: string;
42
- windows: {
43
- id: string;
44
- label: string;
45
- usedPct: number | null;
46
- remainingPct: number | null;
47
- resetsAt: string | null;
48
- }[];
49
- balances: {
50
- id: string;
51
- label: string;
52
- used: number | null;
53
- remaining: number | null;
54
- limit: number | null;
55
- unit: "tokens" | "usd" | "credits" | "requests";
56
- resetsAt: string | null;
57
- }[] | undefined;
58
- }[];
59
- };
60
24
  export declare class OfficialClient implements OfficialOperations {
61
25
  readonly config: Config;
62
26
  private journal?;
@@ -67,11 +31,14 @@ export declare class OfficialClient implements OfficialOperations {
67
31
  private callbacks;
68
32
  private unlisten;
69
33
  private terminalReads;
34
+ private requestReads;
70
35
  private observationOrder;
36
+ private pendingTasks;
71
37
  constructor(config: Config, journal?: OperationJournal | undefined);
72
38
  connect(): Promise<void>;
73
39
  info(): ServerInfoStatusPayload | null;
74
40
  private emit;
41
+ private emitRequest;
75
42
  private readTerminal;
76
43
  private terminalTimestamp;
77
44
  private fenceTerminalRead;
@@ -79,7 +46,12 @@ export declare class OfficialClient implements OfficialOperations {
79
46
  requestContext(): {
80
47
  serverId: string;
81
48
  generation: `${string}-${string}-${string}-${string}-${string}`;
49
+ journal: OperationJournal | undefined;
82
50
  };
51
+ private beginRequestRead;
52
+ private fenceRequestReads;
53
+ private acceptRequestRead;
54
+ private readCurrent;
83
55
  current(agentId: string): Promise<{
84
56
  id: string;
85
57
  provider: string;
@@ -88,7 +60,7 @@ export declare class OfficialClient implements OfficialOperations {
88
60
  createdAt: string;
89
61
  updatedAt: string;
90
62
  lastUserMessageAt: string | null;
91
- status: "error" | "running" | "idle" | "closed" | "initializing";
63
+ status: "error" | "initializing" | "idle" | "running" | "closed";
92
64
  capabilities: import("@getpaseo/protocol/agent-types").AgentCapabilityFlags;
93
65
  currentModeId: string | null;
94
66
  availableModes: import("@getpaseo/protocol/agent-types").AgentMode[];
@@ -138,21 +110,18 @@ export declare class OfficialClient implements OfficialOperations {
138
110
  providerUnavailable?: boolean | undefined;
139
111
  internal?: boolean | undefined;
140
112
  } | null>;
141
- activityTask(agentId: string, signal?: AbortSignal): Promise<{
142
- agentId: string;
143
- title: string | null;
144
- status: "error" | "running" | "idle" | "closed" | "initializing";
145
- updatedAt: string;
146
- lastUserMessageAt: string | null;
147
- activeTurnStartedAt: string | null;
148
- cwd: string | null;
149
- requiresAttention: boolean;
150
- attentionReason: "permission" | "error" | "finished" | null;
151
- pendingRequests: {
152
- requestId: string;
153
- 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
+ }[];
154
123
  }[];
155
- } | null>;
124
+ };
156
125
  send(command: Extract<Command, {
157
126
  type: 'send';
158
127
  }>): Promise<void>;
@@ -162,26 +131,17 @@ export declare class OfficialClient implements OfficialOperations {
162
131
  reconcile(command: Command, pair?: Pick<Pair, 'pairId' | 'rootKey'>): Promise<ReceiptState | null>;
163
132
  reconcileEvidence(evidence: Evidence, pair?: Pick<Pair, 'pairId' | 'rootKey'>): Promise<ReceiptState | null>;
164
133
  snapshot(): Promise<{
165
- version: number;
166
- daemonServerId: string;
167
134
  hostName: string;
168
135
  measuredAt: number;
136
+ version: number;
137
+ daemonServerId: string;
169
138
  tasks: {
170
139
  agentId: string;
171
- title: string | null;
172
- status: "error" | "running" | "idle" | "closed" | "initializing";
173
- updatedAt: string;
174
- lastUserMessageAt: string | null;
175
- activeTurnStartedAt: string | null;
176
- cwd: string | null;
177
- requiresAttention: boolean;
178
- attentionReason: "permission" | "error" | "finished" | null;
179
140
  pendingRequests: {
180
141
  requestId: string;
181
142
  request: import("@getpaseo/protocol/agent-types").AgentPermissionRequest;
182
143
  }[];
183
144
  }[];
184
- usage: unknown;
185
145
  }>;
186
146
  close(): Promise<void>;
187
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, title: a.title?.slice(0, 160) || null, status: a.status, 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;
@@ -57,7 +56,9 @@ export class OfficialClient {
57
56
  callbacks = new Set();
58
57
  unlisten;
59
58
  terminalReads = new Map();
59
+ requestReads = new Set();
60
60
  observationOrder = 0;
61
+ pendingTasks = new Map();
61
62
  constructor(config, journal) {
62
63
  this.config = config;
63
64
  this.journal = journal;
@@ -98,13 +99,20 @@ export class OfficialClient {
98
99
  }
99
100
  if (message.type === 'agent_permission_request') {
100
101
  const p = message.payload;
101
- void this.current(p.agentId).then(agent => { const r = agent?.pendingPermissions?.find(r => r.id === p.request.id); if (!r)
102
- return; const ts = Date.parse(agent?.attentionTimestamp || agent?.updatedAt || ''); if (Number.isFinite(ts))
103
- this.emit({ agentId: p.agentId, requestId: r.id, kind: r.kind === 'question' ? 'question' : 'permission', timestamp: ts }); }).catch(() => { });
102
+ this.fenceRequestReads(p.agentId, ++this.observationOrder);
103
+ void this.readCurrent(p.agentId, agent => { const r = agent?.pendingPermissions?.find(r => r.id === p.request.id); if (r)
104
+ this.emitRequest(p.agentId, r); }).catch(() => { });
104
105
  }
105
106
  if (message.type === 'agent_permission_resolved') {
106
107
  const p = message.payload;
108
+ this.fenceRequestReads(p.agentId, ++this.observationOrder);
107
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
+ }
108
116
  }
109
117
  });
110
118
  this.subscription = this.sdk.observeEvents(['agent_attention_required', 'agent_permission_request', 'agent_permission_resolved', 'status.server_info'], { notifications: false });
@@ -114,6 +122,15 @@ export class OfficialClient {
114
122
  emit(event) { if (Number.isSafeInteger(event.timestamp) && event.timestamp >= 0)
115
123
  for (const cb of this.callbacks)
116
124
  cb(event); }
125
+ emitRequest(agentId, request) {
126
+ const occurrence = this.journal?.currentOccurrence(this.serverId, agentId, request.id);
127
+ if (this.journal && !occurrence)
128
+ return;
129
+ // Pending requests have independent lifetimes. The global attention clock can
130
+ // still describe an older finished turn; never use it to expire a new request.
131
+ // Runtime journals retain one observation clock per exact current occurrence.
132
+ this.emit({ agentId, requestId: request.id, occurrence, kind: request.kind === 'question' ? 'question' : 'permission', timestamp: occurrence?.createdAt ?? Date.now() });
133
+ }
117
134
  readTerminal(event) {
118
135
  const read = { event, valid: true, next: null };
119
136
  this.terminalReads.set(event.agentId, read);
@@ -159,9 +176,48 @@ export class OfficialClient {
159
176
  pending.next = null;
160
177
  }
161
178
  onAttention(callback) { this.callbacks.add(callback); return () => { this.callbacks.delete(callback); }; }
162
- requestContext() { return { serverId: this.serverId, generation: this.generation }; }
163
- async current(agentId) { const observationOrder = ++this.observationOrder; const value = await this.sdk.fetchAgent({ agentId, timeout: 15000 }); const agent = value?.agent || null; this.fenceTerminalRead(agentId, agent, observationOrder); this.journal?.syncRequests(this.serverId, agentId, this.generation, agent?.pendingPermissions || []); return agent; }
164
- 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; }
179
+ requestContext() { return { serverId: this.serverId, generation: this.generation, journal: this.journal }; }
180
+ beginRequestRead(agentId) { const read = { agentId, observedOrder: ++this.observationOrder, stale: new Set() }; this.requestReads.add(read); return read; }
181
+ fenceRequestReads(agentId, observedOrder) {
182
+ // Track only in-flight reads, not an unbounded history of observed agents.
183
+ for (const read of this.requestReads)
184
+ if (read.observedOrder < observedOrder && (read.agentId === undefined || read.agentId === agentId))
185
+ read.stale.add(agentId);
186
+ }
187
+ acceptRequestRead(read, agentId) {
188
+ if (!this.requestReads.has(read) || read.stale.has(agentId))
189
+ return false;
190
+ this.fenceRequestReads(agentId, read.observedOrder);
191
+ return true;
192
+ }
193
+ async readCurrent(agentId, observe) {
194
+ const read = this.beginRequestRead(agentId);
195
+ try {
196
+ const value = await this.sdk.fetchAgent({ agentId, timeout: 15000 });
197
+ if (!this.acceptRequestRead(read, agentId))
198
+ return null;
199
+ const agent = value?.agent || null;
200
+ this.fenceTerminalRead(agentId, agent, read.observedOrder);
201
+ this.journal?.syncRequests(this.serverId, agentId, this.generation, agent?.pendingPermissions || []);
202
+ this.rememberRequests(agentId, agent);
203
+ // Observation, journal synchronization and notification share one fence.
204
+ observe?.(agent);
205
+ return agent;
206
+ }
207
+ finally {
208
+ this.requestReads.delete(read);
209
+ }
210
+ }
211
+ async current(agentId) { return this.readCurrent(agentId); }
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()]) }; }
165
221
  async send(command) { if (!this.sdk.isConnected)
166
222
  throw Error('OFFICIAL_DISCONNECTED'); await this.sdk.sendAgentMessage(command.agentId, command.text, { messageId: command.messageId }); }
167
223
  async permission(command) { if (!this.sdk.isConnected)
@@ -190,35 +246,27 @@ export class OfficialClient {
190
246
  const info = this.info();
191
247
  if (!info)
192
248
  throw Error('OFFICIAL_IDENTITY_UNAVAILABLE');
193
- const observationOrder = ++this.observationOrder;
194
- const result = await this.sdk.fetchAgents({ page: { limit: LIMITS.tasks }, filter: { includeArchived: false, includeInternal: false }, sort: [{ key: 'updated_at', direction: 'desc' }], timeout: 15000 });
195
- const agents = result.entries.slice(0, LIMITS.tasks).map(entry => entry.agent);
196
- for (const a of agents) {
197
- this.fenceTerminalRead(a.id, a, observationOrder);
198
- this.journal?.syncRequests(this.serverId, a.id, this.generation, a.pendingPermissions);
199
- this.journal?.syncAttention(a.id, a.requiresAttention === true, a.attentionTimestamp ? Date.parse(a.attentionTimestamp) : null);
200
- }
201
- for (const a of agents) {
202
- if (a.requiresAttention && a.attentionReason && a.attentionTimestamp) {
203
- const timestamp = Date.parse(a.attentionTimestamp);
204
- if (a.attentionReason === 'permission') {
205
- for (const r of a.pendingPermissions)
206
- this.emit({ agentId: a.id, requestId: r.id, kind: r.kind === 'question' ? 'question' : 'permission', timestamp });
207
- }
208
- else
209
- this.emit({ agentId: a.id, kind: a.attentionReason, timestamp });
249
+ const read = this.beginRequestRead();
250
+ try {
251
+ const result = await this.sdk.fetchAgents({ page: { limit: LIMITS.tasks }, filter: { includeArchived: false, includeInternal: false }, sort: [{ key: 'updated_at', direction: 'desc' }], timeout: 15000 });
252
+ const agents = result.entries.slice(0, LIMITS.tasks).map(entry => entry.agent).filter(agent => this.acceptRequestRead(read, agent.id));
253
+ for (const a of agents) {
254
+ this.fenceTerminalRead(a.id, a, read.observedOrder);
255
+ this.journal?.syncRequests(this.serverId, a.id, this.generation, a.pendingPermissions);
256
+ this.rememberRequests(a.id, a);
257
+ this.journal?.syncAttention(a.id, a.requiresAttention === true, a.attentionTimestamp ? Date.parse(a.attentionTimestamp) : null);
210
258
  }
211
- }
212
- let usage = null;
213
- if (info.features?.providerUsageList) {
214
- try {
215
- usage = projectUsage(await this.sdk.listProviderUsage());
216
- }
217
- catch {
218
- usage = null;
259
+ for (const a of agents) {
260
+ for (const request of a.pendingPermissions)
261
+ this.emitRequest(a.id, request);
262
+ if (a.requiresAttention && a.attentionReason && a.attentionReason !== 'permission' && a.attentionTimestamp)
263
+ this.emit({ agentId: a.id, kind: a.attentionReason, timestamp: Date.parse(a.attentionTimestamp) });
219
264
  }
265
+ return { ...this.notificationSnapshot(), hostName: (info.hostname || hostname()).slice(0, 256), measuredAt: Date.now() };
266
+ }
267
+ finally {
268
+ this.requestReads.delete(read);
220
269
  }
221
- return { version: 1, daemonServerId: info.serverId, hostName: (info.hostname || hostname()).slice(0, 256), measuredAt: Date.now(), tasks: agents.map(projectTask), usage };
222
270
  }
223
- async close() { this.terminalReads.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(); }
224
272
  }
@@ -44,6 +44,7 @@ export interface OfficialOperations {
44
44
  requestContext?(): {
45
45
  serverId: string;
46
46
  generation: string;
47
+ journal?: OperationJournal;
47
48
  };
48
49
  }
49
50
  export interface OperationCloud {
@@ -1,5 +1,6 @@
1
1
  import { exact, object, text, LIMITS } from './limits.js';
2
2
  import { decode, openEnvelope, sealEnvelope, validateEnvelope } from './crypto.js';
3
+ import { canonical, digest } from './journal.js';
3
4
  import { occurrenceBinding } from './bindings.js';
4
5
  import { validatePermissionInput } from './permission.js';
5
6
  import { evidenceForCommand } from './evidence.js';
@@ -57,10 +58,29 @@ export function validateCommand(value, id, current) {
57
58
  }
58
59
  return c;
59
60
  }
60
- export async function boundCurrent(ctx, agentId) { const current = await ctx.official.current(agentId); if (!current)
61
- return null; const source = ctx.official.requestContext?.(); if (!source)
62
- return current; const requests = current.pendingPermissions || []; ctx.journal.syncRequests(source.serverId, agentId, source.generation, requests); return { ...current, pendingPermissions: await Promise.all(requests.map(async (r) => { const occurrence = ctx.journal.currentOccurrence(source.serverId, agentId, r.id); if (!occurrence)
63
- return { ...r, requestBinding: undefined }; return { ...r, occurrence, requestBinding: await occurrenceBinding(ctx.pair, occurrence) }; })) }; }
61
+ export async function boundCurrent(ctx, agentId) {
62
+ const current = await ctx.official.current(agentId);
63
+ if (!current)
64
+ return null;
65
+ const source = ctx.official.requestContext?.();
66
+ if (!source)
67
+ return current;
68
+ if (source.journal && source.journal !== ctx.journal)
69
+ throw Error('REQUEST_JOURNAL_MISMATCH');
70
+ const requests = current.pendingPermissions || [];
71
+ // A journal-owning adapter synchronizes before resolving current(). Repeating
72
+ // that write here could restore an older response after a newer observation.
73
+ if (!source.journal)
74
+ ctx.journal.syncRequests(source.serverId, agentId, source.generation, requests);
75
+ return { ...current, pendingPermissions: await Promise.all(requests.map(async (request) => {
76
+ const unbound = { ...request, occurrence: undefined, requestBinding: undefined };
77
+ const occurrence = ctx.journal.currentOccurrence(source.serverId, agentId, request.id);
78
+ if (!occurrence || occurrence.generation !== source.generation || occurrence.fingerprint !== digest(canonical(request)))
79
+ return unbound;
80
+ const requestBinding = await occurrenceBinding(ctx.pair, occurrence);
81
+ return ctx.journal.isCurrent(occurrence) ? { ...request, occurrence, requestBinding } : unbound;
82
+ })) };
83
+ }
64
84
  async function outcome(ctx, e, state, now, code) {
65
85
  const old = ctx.journal.get(e.pairId, e.id);
66
86
  if (old.state === 'accepted' && state === 'unknown')
@@ -2,26 +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
- title: string | null;
13
- status: "error" | "running" | "idle" | "closed" | "initializing";
14
- updatedAt: string;
15
- lastUserMessageAt: string | null;
16
- activeTurnStartedAt: string | null;
17
- cwd: string | null;
18
- requiresAttention: boolean;
19
- attentionReason: "permission" | "error" | "finished" | null;
20
14
  }[];
21
- tasksTruncated: boolean;
22
- version: number;
23
- daemonServerId: string;
24
- hostName: string;
25
- measuredAt: number;
26
- usage: unknown;
27
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
  }
@@ -1,6 +1,7 @@
1
1
  import { type Stats } from 'node:fs';
2
2
  import { DatabaseSync } from 'node:sqlite';
3
3
  export declare const JOURNAL_APPLICATION_ID = 1297236785;
4
+ export declare const CONFIG_BYTES = 524288;
4
5
  export declare const RUNTIME_OWNER = "MoRemote CLI runtime";
5
6
  export interface ResourceIdentity {
6
7
  dev: number;
@@ -38,7 +39,7 @@ export interface RuntimeResources {
38
39
  export declare function hasCode(error: unknown, code: string): boolean;
39
40
  export declare function sameResource(left: ResourceIdentity, right: ResourceIdentity): boolean;
40
41
  export declare function inspectResource(path: string, kind: 'file' | 'directory' | 'socket', optional?: boolean, privateMode?: boolean): Stats | null;
41
- export declare function readPrivateText(path: string, limit: number, encoding?: 'utf8' | 'utf16le'): {
42
+ export declare function readPrivateText(path: string, limit: number, encoding?: 'utf8' | 'utf16le', privateMode?: boolean): {
42
43
  text: string;
43
44
  identity: {
44
45
  dev: number;
package/dist/resources.js CHANGED
@@ -3,10 +3,22 @@ import { dirname, basename, join } from 'node:path';
3
3
  import { pathToFileURL } from 'node:url';
4
4
  import { DatabaseSync } from 'node:sqlite';
5
5
  import { createHash, randomUUID } from 'node:crypto';
6
+ import { isUtf8 } from 'node:buffer';
6
7
  export const JOURNAL_APPLICATION_ID = 0x4d524331;
8
+ export const CONFIG_BYTES = 524288;
7
9
  export const RUNTIME_OWNER = 'MoRemote CLI runtime';
8
10
  export function hasCode(error, code) { return error instanceof Error && 'code' in error && error.code === code; }
9
11
  export function sameResource(left, right) { return left.dev === right.dev && left.ino === right.ino; }
12
+ function assertResource(stat, kind, privateMode, retiredFile = false) {
13
+ if (stat.isSymbolicLink() || !(kind === 'file' ? stat.isFile() : kind === 'directory' ? stat.isDirectory() : stat.isSocket()))
14
+ throw Error('FOREIGN_RESOURCE_KIND');
15
+ if (kind !== 'directory' && stat.nlink !== 1 && !(retiredFile && kind === 'file' && stat.nlink === 0))
16
+ throw Error('FOREIGN_RESOURCE_LINKS');
17
+ if (typeof process.getuid === 'function' && stat.uid !== process.getuid())
18
+ throw Error('FOREIGN_RESOURCE_USER');
19
+ if (privateMode && process.platform !== 'win32' && ((stat.mode & 0o7077) !== 0 || (stat.mode & (kind === 'directory' ? 0o700 : 0o600)) !== (kind === 'directory' ? 0o700 : 0o600)))
20
+ throw Error('FOREIGN_RESOURCE_MODE');
21
+ }
10
22
  export function inspectResource(path, kind, optional = false, privateMode = true) {
11
23
  let stat;
12
24
  try {
@@ -17,39 +29,60 @@ export function inspectResource(path, kind, optional = false, privateMode = true
17
29
  return null;
18
30
  throw error;
19
31
  }
20
- if (stat.isSymbolicLink() || !(kind === 'file' ? stat.isFile() : kind === 'directory' ? stat.isDirectory() : stat.isSocket()))
21
- throw Error('FOREIGN_RESOURCE_KIND');
22
- if (kind !== 'directory' && stat.nlink !== 1)
23
- throw Error('FOREIGN_RESOURCE_LINKS');
24
- if (typeof process.getuid === 'function' && stat.uid !== process.getuid())
25
- throw Error('FOREIGN_RESOURCE_USER');
26
- if (privateMode && process.platform !== 'win32' && ((stat.mode & 0o7077) !== 0 || (stat.mode & (kind === 'directory' ? 0o700 : 0o600)) !== (kind === 'directory' ? 0o700 : 0o600)))
27
- throw Error('FOREIGN_RESOURCE_MODE');
32
+ assertResource(stat, kind, privateMode);
28
33
  return stat;
29
34
  }
30
- export function readPrivateText(path, limit, encoding = 'utf8') {
31
- const before = inspectResource(path, 'file');
32
- const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
33
- try {
34
- const opened = fstatSync(fd);
35
- if (!before || !sameResource(before, opened) || !opened.isFile() || opened.nlink !== 1 || opened.size > limit)
36
- throw Error('FOREIGN_RESOURCE_LIMIT');
37
- const bytes = Buffer.alloc(limit + 1);
38
- let size = 0;
39
- while (size < bytes.length) {
40
- const count = readSync(fd, bytes, size, bytes.length - size, null);
41
- if (count === 0)
42
- break;
43
- size += count;
35
+ export function readPrivateText(path, limit, encoding = 'utf8', privateMode = true) {
36
+ for (let attempt = 0; attempt < 3; attempt++) {
37
+ const before = inspectResource(path, 'file', false, privateMode);
38
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
39
+ try {
40
+ const opened = fstatSync(fd);
41
+ assertResource(opened, 'file', privateMode, true);
42
+ if (opened.size > limit)
43
+ throw Error('FOREIGN_RESOURCE_LIMIT');
44
+ // A rename can retire an already opened inode before fstat. Never read or
45
+ // return that unlinked handle; require a valid replacement and reopen it.
46
+ if (opened.nlink === 0) {
47
+ const replacement = inspectResource(path, 'file', false, privateMode);
48
+ if (!replacement || sameResource(opened, replacement))
49
+ throw Error('FOREIGN_RESOURCE_CHANGED');
50
+ continue;
51
+ }
52
+ if (!before || !sameResource(before, opened))
53
+ continue;
54
+ const bytes = Buffer.alloc(limit + 1);
55
+ let size = 0;
56
+ while (size < bytes.length) {
57
+ const count = readSync(fd, bytes, size, bytes.length - size, null);
58
+ if (count === 0)
59
+ break;
60
+ size += count;
61
+ }
62
+ if (size > limit)
63
+ throw Error('FOREIGN_RESOURCE_LIMIT');
64
+ const finished = fstatSync(fd);
65
+ assertResource(finished, 'file', privateMode, true);
66
+ // Content changes already observed on this handle remain failures even if a
67
+ // later atomic replacement would otherwise permit reopening the pathname.
68
+ if (opened.size !== size || opened.size !== finished.size || opened.mtimeMs !== finished.mtimeMs)
69
+ throw Error('FOREIGN_RESOURCE_CHANGED');
70
+ const after = inspectResource(path, 'file', false, privateMode);
71
+ // Only an ordinary owned replacement permits another read. Linked, foreign
72
+ // or insecure paths fail inspection, and in-place mutation is never retried.
73
+ if (after && !sameResource(opened, after))
74
+ continue;
75
+ if (!after || finished.nlink !== 1 || opened.size !== after.size || opened.mtimeMs !== after.mtimeMs || opened.ctimeMs !== after.ctimeMs || opened.ctimeMs !== finished.ctimeMs)
76
+ throw Error('FOREIGN_RESOURCE_CHANGED');
77
+ if (encoding === 'utf8' && !isUtf8(bytes.subarray(0, size)))
78
+ throw Error('FOREIGN_RESOURCE_ENCODING');
79
+ return { text: bytes.toString(encoding, 0, size), identity: { dev: opened.dev, ino: opened.ino } };
80
+ }
81
+ finally {
82
+ closeSync(fd);
44
83
  }
45
- const after = inspectResource(path, 'file');
46
- if (size > limit || !after || !sameResource(opened, after) || opened.size !== after.size || opened.mtimeMs !== after.mtimeMs)
47
- throw Error('FOREIGN_RESOURCE_CHANGED');
48
- return { text: bytes.toString(encoding, 0, size), identity: { dev: opened.dev, ino: opened.ino } };
49
- }
50
- finally {
51
- closeSync(fd);
52
84
  }
85
+ throw Error('FOREIGN_RESOURCE_CHANGED');
53
86
  }
54
87
  export function assertStateRoot(dir) {
55
88
  inspectResource(dir, 'directory');
@@ -210,6 +243,9 @@ export function writePrivateAtomic(path, value) {
210
243
  assertStateRoot(dir);
211
244
  if (name !== 'config.json' && name !== 'runtime.json' && name !== 'runtime.lock')
212
245
  throw Error('FOREIGN_RESOURCE_NAME');
246
+ const bytes = JSON.stringify(value) + '\n';
247
+ if (name === 'config.json' && Buffer.byteLength(bytes) > CONFIG_BYTES)
248
+ throw Error('CONFIG_LIMIT');
213
249
  const before = inspectResource(path, 'file', true);
214
250
  if (before) {
215
251
  if (name === 'runtime.lock')
@@ -218,7 +254,7 @@ export function writePrivateAtomic(path, value) {
218
254
  assertStateResource(dir, name);
219
255
  }
220
256
  const temp = path + '.' + randomUUID() + '.tmp';
221
- const identity = createPrivateFile(temp, JSON.stringify(value) + '\n');
257
+ const identity = createPrivateFile(temp, bytes);
222
258
  try {
223
259
  const current = inspectResource(path, 'file', true);
224
260
  if (before ? (!current || !sameResource(before, current)) : current !== null)
@@ -279,7 +315,7 @@ export function assertStateResource(dir, name) {
279
315
  return;
280
316
  }
281
317
  if (name === 'config.json' || /^config\.json\.[0-9a-f-]{36}\.tmp$/.test(name)) {
282
- const value = JSON.parse(readPrivateText(path, 131072).text);
318
+ const value = JSON.parse(readPrivateText(path, CONFIG_BYTES).text);
283
319
  if (!object(value) || value.version !== 1 || typeof value.clientId !== 'string' || !value.clientId.startsWith('moremote-cli-') || value.clientId.length > 256)
284
320
  throw Error('FOREIGN_CONFIG');
285
321
  return;
package/dist/runtime.d.ts CHANGED
@@ -1,8 +1,17 @@
1
1
  import { type Pair } from './config.js';
2
- import { type Attention } from './official-client.js';
2
+ import { OfficialClient, type Attention } from './official-client.js';
3
3
  import { OperationJournal, type Occurrence } from './journal.js';
4
4
  export declare function queueAttention(journal: OperationJournal, pair: Pair, event: Attention & {
5
5
  sourceFingerprint?: string;
6
6
  occurrence?: Occurrence;
7
7
  }, now?: number): Promise<void>;
8
+ export declare function boundAttention(journal: OperationJournal, pair: Pair, event: Attention, official: Pick<OfficialClient, 'requestContext' | 'generation'>): Promise<Attention | {
9
+ occurrence: Occurrence;
10
+ sourceFingerprint: string;
11
+ requestBinding: string;
12
+ agentId: string;
13
+ requestId?: string;
14
+ kind: "finished" | "question" | "permission" | "error";
15
+ timestamp: number;
16
+ } | null>;
8
17
  export declare function runRuntime(dir: string, version?: string): Promise<void>;