@moxuli/moremote 0.1.2 → 0.1.4

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.
@@ -0,0 +1,50 @@
1
+ export interface EnrollmentRequest {
2
+ version: 1;
3
+ id: string;
4
+ clientId: string;
5
+ daemonServerId: string;
6
+ issuedAt: number;
7
+ expiresAt: number;
8
+ }
9
+ export interface EnrollmentOffer {
10
+ version: 1;
11
+ apiOrigin: string;
12
+ pairId: string;
13
+ enrollmentToken: string;
14
+ rootKey: string;
15
+ expiresAt: number;
16
+ }
17
+ export interface EnrollmentRecord {
18
+ request: EnrollmentRequest;
19
+ bytes: string;
20
+ fingerprint: string;
21
+ pairId: string;
22
+ offer: EnrollmentOffer;
23
+ createBytes: string;
24
+ created: boolean;
25
+ }
26
+ export interface EnrollmentDescriptor {
27
+ version: 1;
28
+ daemonServerId: string;
29
+ instanceId: string;
30
+ apiOrigin: string;
31
+ enabled: boolean;
32
+ measuredAt: number;
33
+ expiresAt: number;
34
+ }
35
+ export interface EnrollmentResponse {
36
+ version: 1;
37
+ id: string;
38
+ clientId: string;
39
+ daemonServerId: string;
40
+ expiresAt: number;
41
+ status: 'pending' | 'offer' | 'active' | 'disabled' | 'error';
42
+ offer?: EnrollmentOffer;
43
+ code?: string;
44
+ }
45
+ export declare const DISCOVERY_NAME = ".moremote-cli-connect";
46
+ export declare const descriptorLifetime = 90000;
47
+ export declare const descriptorRenewal = 30000;
48
+ export declare function requestFingerprint(bytes: string): string;
49
+ export declare function parseEnrollmentRequest(bytes: string): EnrollmentRequest;
50
+ export declare function validateEnrollmentRecords(value: unknown): asserts value is EnrollmentRecord[];
@@ -0,0 +1,44 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { decode } from './crypto.js';
3
+ import { exact, object, UUID, LIMITS } from './limits.js';
4
+ export const DISCOVERY_NAME = '.moremote-cli-connect';
5
+ export const descriptorLifetime = 90000;
6
+ export const descriptorRenewal = 30000;
7
+ export function requestFingerprint(bytes) { return createHash('sha256').update(bytes, 'utf8').digest('hex'); }
8
+ export function parseEnrollmentRequest(bytes) {
9
+ if (Buffer.byteLength(bytes) > 4096)
10
+ throw Error('ENROLLMENT_REQUEST_LIMIT');
11
+ const request = object(JSON.parse(bytes));
12
+ exact(request, ['version', 'id', 'clientId', 'daemonServerId', 'issuedAt', 'expiresAt']);
13
+ if (request.version !== 1 || typeof request.id !== 'string' || !UUID.test(request.id) || typeof request.clientId !== 'string' || !UUID.test(request.clientId) || typeof request.daemonServerId !== 'string' || !request.daemonServerId || Buffer.byteLength(request.daemonServerId) > 512 || !Number.isSafeInteger(request.issuedAt) || Number(request.issuedAt) < 0 || !Number.isSafeInteger(request.expiresAt) || Number(request.expiresAt) <= Number(request.issuedAt) || Number(request.expiresAt) - Number(request.issuedAt) > LIMITS.enrollmentMs)
14
+ throw Error('INVALID_ENROLLMENT_REQUEST');
15
+ return request;
16
+ }
17
+ export function validateEnrollmentRecords(value) {
18
+ if (!Array.isArray(value) || value.length > 16)
19
+ throw Error('INVALID_ENROLLMENT_RECORDS');
20
+ const ids = new Set(), pairs = new Set();
21
+ for (const item of value) {
22
+ const record = object(item);
23
+ exact(record, ['request', 'bytes', 'fingerprint', 'pairId', 'offer', 'createBytes', 'created']);
24
+ if (typeof record.bytes !== 'string' || record.fingerprint !== requestFingerprint(record.bytes) || typeof record.created !== 'boolean' || typeof record.pairId !== 'string' || !UUID.test(record.pairId))
25
+ throw Error('INVALID_ENROLLMENT_RECORD');
26
+ const request = parseEnrollmentRequest(record.bytes);
27
+ if (JSON.stringify(record.request) !== JSON.stringify(request) || ids.has(request.id) || pairs.has(record.pairId))
28
+ throw Error('INVALID_ENROLLMENT_RECORD');
29
+ ids.add(request.id);
30
+ pairs.add(record.pairId);
31
+ const offer = object(record.offer);
32
+ exact(offer, ['version', 'apiOrigin', 'pairId', 'enrollmentToken', 'rootKey', 'expiresAt']);
33
+ if (offer.version !== 1 || offer.pairId !== record.pairId || typeof offer.apiOrigin !== 'string' || !Number.isSafeInteger(offer.expiresAt) || Number(offer.expiresAt) <= request.issuedAt || Number(offer.expiresAt) > request.expiresAt || typeof offer.rootKey !== 'string' || typeof offer.enrollmentToken !== 'string')
34
+ throw Error('INVALID_ENROLLMENT_OFFER');
35
+ decode(offer.rootKey, 32);
36
+ decode(offer.enrollmentToken, 32);
37
+ if (typeof record.createBytes !== 'string' || Buffer.byteLength(record.createBytes) > 1024)
38
+ throw Error('INVALID_ENROLLMENT_CREATE');
39
+ const body = object(JSON.parse(record.createBytes));
40
+ exact(body, ['pairId', 'hostTokenHash', 'enrollmentTokenHash', 'expiresAt']);
41
+ if (body.pairId !== record.pairId || body.expiresAt !== offer.expiresAt || typeof body.hostTokenHash !== 'string' || !/^[a-f0-9]{64}$/.test(body.hostTokenHash) || body.enrollmentTokenHash !== requestFingerprint(offer.enrollmentToken))
42
+ throw Error('INVALID_ENROLLMENT_CREATE');
43
+ }
44
+ }
@@ -0,0 +1,25 @@
1
+ import { type Config, type Pair } from './config.js';
2
+ import { CloudClient } from './cloud-client.js';
3
+ import { EnrollmentFiles, type DiscoveryOptions } from './enrollment-files.js';
4
+ export declare const DEFAULT_API_ORIGIN = "https://moremote-cloud-ingress.pages.dev";
5
+ export interface LocalEnrollmentOptions {
6
+ clock?: () => number;
7
+ files?: (options: DiscoveryOptions) => EnrollmentFiles;
8
+ persist?: (directory: string, config: Config) => Promise<void>;
9
+ }
10
+ export type EnrollmentCloudFactory = (pair: Pair) => Pick<CloudClient, 'create'>;
11
+ export declare class LocalEnrollment {
12
+ private directory;
13
+ private options;
14
+ private files;
15
+ private config;
16
+ private cursor;
17
+ private readonly clock;
18
+ private readonly persist;
19
+ constructor(directory: string, options?: LocalEnrollmentOptions);
20
+ private storage;
21
+ cleanup(config: Config): Promise<void>;
22
+ cycle(config: Config, daemonServerId: string, cloud: EnrollmentCloudFactory): Promise<void>;
23
+ private response;
24
+ close(): void;
25
+ }
@@ -0,0 +1,160 @@
1
+ import { saveConfig, validateOrigin } from './config.js';
2
+ import { makeOffer, tokenHash } from './pairing.js';
3
+ import { EnrollmentFiles } from './enrollment-files.js';
4
+ import { parseEnrollmentRequest, requestFingerprint } from './enrollment-protocol.js';
5
+ export const DEFAULT_API_ORIGIN = 'https://moremote-cloud-ingress.pages.dev';
6
+ // The runtime's existing serialized cycle owns this consumer and its Config.
7
+ // No watcher, background config writer, listener or official mutation is added.
8
+ export class LocalEnrollment {
9
+ directory;
10
+ options;
11
+ files;
12
+ config;
13
+ cursor = 0;
14
+ clock;
15
+ persist;
16
+ constructor(directory, options = {}) {
17
+ this.directory = directory;
18
+ this.options = options;
19
+ this.clock = options.clock ?? Date.now;
20
+ this.persist = options.persist ?? saveConfig;
21
+ }
22
+ storage(config) {
23
+ if (!config.localEnrollment || !config.daemonServerId)
24
+ return;
25
+ this.files ??= (this.options.files ?? (options => new EnrollmentFiles(options)))({ home: config.localEnrollment.home, stateDirectory: this.directory, daemonServerId: config.daemonServerId });
26
+ this.files.open(config.enrollmentRequests ?? []);
27
+ return this.files;
28
+ }
29
+ async cleanup(config) {
30
+ this.config = config;
31
+ const files = this.storage(config);
32
+ if (!files)
33
+ return;
34
+ const now = this.clock(), records = config.enrollmentRequests ?? [];
35
+ let changed = false;
36
+ for (const record of records) {
37
+ const pair = config.pairs.find(pair => pair.pairId === record.pairId);
38
+ if (!config.cloudEnabled || pair?.active || pair?.revokedAt !== undefined || pair?.relayRetiredAt !== undefined || now >= record.offer.expiresAt)
39
+ files.removeResponse(record);
40
+ if (config.cloudEnabled && now < record.offer.expiresAt && (pair?.revokedAt !== undefined || pair?.relayRetiredAt !== undefined))
41
+ files.writeResponse(record, this.response(record, 'disabled'));
42
+ if (pair?.active || now >= record.offer.expiresAt) {
43
+ const name = record.request.id + '.json';
44
+ try {
45
+ const file = files.readRequest(name);
46
+ if (file.text === record.bytes)
47
+ files.removeRequest(name, file.identity);
48
+ }
49
+ catch (error) {
50
+ if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT'))
51
+ throw error;
52
+ }
53
+ }
54
+ }
55
+ const retained = records.filter(record => now < record.offer.expiresAt);
56
+ if (retained.length !== records.length) {
57
+ config.enrollmentRequests = retained;
58
+ changed = true;
59
+ }
60
+ if (changed)
61
+ await this.persist(this.directory, config);
62
+ }
63
+ async cycle(config, daemonServerId, cloud) {
64
+ if (!config.localEnrollment)
65
+ return;
66
+ if (!config.daemonServerId || config.daemonServerId !== daemonServerId)
67
+ throw Error('ENROLLMENT_DAEMON_MISMATCH');
68
+ await this.cleanup(config);
69
+ const files = this.storage(config);
70
+ const origin = validateOrigin(config.apiOrigin ?? DEFAULT_API_ORIGIN, false), now = this.clock();
71
+ files.publish(config.cloudEnabled, origin, now);
72
+ if (!config.cloudEnabled)
73
+ return;
74
+ const names = files.requestNames();
75
+ if (!names.length)
76
+ return;
77
+ const start = this.cursor % names.length, selected = [...names.slice(start), ...names.slice(0, start)].slice(0, 16);
78
+ this.cursor = (start + selected.length) % names.length;
79
+ let failure, creationAttempted = false;
80
+ for (const name of selected) {
81
+ try {
82
+ const file = files.readRequest(name), record = config.enrollmentRequests?.find(record => record.request.id === name.slice(0, -5));
83
+ if (record && record.bytes !== file.text) {
84
+ files.removeResponse(record);
85
+ throw Error('ENROLLMENT_REQUEST_CONFLICT');
86
+ }
87
+ if (file.text === '')
88
+ continue; // Official create/write is a two-step transaction.
89
+ const request = parseEnrollmentRequest(file.text);
90
+ if (request.id + '.json' !== name || request.daemonServerId !== daemonServerId)
91
+ throw Error('ENROLLMENT_DAEMON_MISMATCH');
92
+ if (request.expiresAt <= this.clock()) {
93
+ files.removeRequest(name, file.identity);
94
+ continue;
95
+ }
96
+ files.assertResponseAvailable(request.id, record);
97
+ if (request.issuedAt > this.clock())
98
+ throw Error('ENROLLMENT_REQUEST_FROM_FUTURE');
99
+ let owned = record;
100
+ if (!owned) {
101
+ if (creationAttempted)
102
+ continue;
103
+ if (config.pairs.some(pair => pair.automaticRequestId === request.id))
104
+ throw Error('ENROLLMENT_REQUEST_CONFLICT');
105
+ if (config.pairs.some(pair => pair.automaticClientId === request.clientId && pair.daemonServerId === daemonServerId && pair.revokedAt === undefined && pair.relayRetiredAt === undefined && (pair.active || pair.expiresAt === undefined || pair.expiresAt > this.clock())))
106
+ throw Error('ENROLLMENT_CLIENT_ALREADY_BOUND');
107
+ if (config.pairs.length >= 16 || (config.enrollmentRequests?.length ?? 0) >= 16)
108
+ throw Error('PAIRING_LIMIT');
109
+ const generated = makeOffer(origin, this.clock());
110
+ generated.pair.expiresAt = Math.min(generated.pair.expiresAt, request.expiresAt);
111
+ const pair = { ...generated.pair, daemonServerId, automaticClientId: request.clientId, automaticRequestId: request.id };
112
+ const offer = { ...generated.offer, version: 1, enrollmentToken: pair.enrollmentToken, expiresAt: pair.expiresAt };
113
+ const createBytes = JSON.stringify({ pairId: pair.pairId, hostTokenHash: tokenHash(pair.hostToken), enrollmentTokenHash: tokenHash(offer.enrollmentToken), expiresAt: offer.expiresAt });
114
+ owned = { request, bytes: file.text, fingerprint: requestFingerprint(file.text), pairId: pair.pairId, offer, createBytes, created: false };
115
+ config.pairs.push(pair);
116
+ (config.enrollmentRequests ??= []).push(owned);
117
+ await this.persist(this.directory, config); // Original keys/request precede all cloud I/O.
118
+ }
119
+ const pair = config.pairs.find(pair => pair.pairId === owned.pairId);
120
+ if (!pair)
121
+ throw Error('ENROLLMENT_PAIR_MISSING');
122
+ if (pair.active) {
123
+ files.removeResponse(owned);
124
+ files.removeRequest(name, file.identity);
125
+ continue;
126
+ }
127
+ if (pair.revokedAt !== undefined || pair.relayRetiredAt !== undefined) {
128
+ files.writeResponse(owned, this.response(owned, 'disabled'));
129
+ continue;
130
+ }
131
+ if (!owned.created) {
132
+ if (creationAttempted)
133
+ continue;
134
+ creationAttempted = true;
135
+ await cloud(pair).create(JSON.parse(owned.createBytes), AbortSignal.timeout(3000));
136
+ owned.created = true;
137
+ await this.persist(this.directory, config);
138
+ }
139
+ // An unknown create acknowledgement retries the same original body. Recheck
140
+ // the immutable local request and deadline after network/persistence awaits.
141
+ if (this.clock() >= owned.offer.expiresAt) {
142
+ files.removeResponse(owned);
143
+ continue;
144
+ }
145
+ if (files.readRequest(name).text !== owned.bytes) {
146
+ files.removeResponse(owned);
147
+ throw Error('ENROLLMENT_REQUEST_CONFLICT');
148
+ }
149
+ files.writeResponse(owned, { ...this.response(owned, 'offer'), offer: owned.offer });
150
+ }
151
+ catch (error) {
152
+ failure ??= error;
153
+ }
154
+ }
155
+ if (failure)
156
+ throw failure;
157
+ }
158
+ response(record, status) { return { version: 1, id: record.request.id, clientId: record.request.clientId, daemonServerId: record.request.daemonServerId, expiresAt: record.offer.expiresAt, status }; }
159
+ close() { this.files?.close(this.config?.enrollmentRequests ?? []); this.files = undefined; }
160
+ }
@@ -2,12 +2,13 @@ import type { DaemonClient } from '@getpaseo/client/internal/daemon-client';
2
2
  import type { ServerInfoStatusPayload, AgentSnapshotPayload, ProviderUsage } 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,8 +16,10 @@ 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;
19
+ provider: string;
18
20
  title: string | null;
19
21
  status: "error" | "running" | "idle" | "closed" | "initializing";
22
+ createdAt: string;
20
23
  updatedAt: string;
21
24
  lastUserMessageAt: string | null;
22
25
  activeTurnStartedAt: string | null;
@@ -67,11 +70,13 @@ export declare class OfficialClient implements OfficialOperations {
67
70
  private callbacks;
68
71
  private unlisten;
69
72
  private terminalReads;
73
+ private requestReads;
70
74
  private observationOrder;
71
75
  constructor(config: Config, journal?: OperationJournal | undefined);
72
76
  connect(): Promise<void>;
73
77
  info(): ServerInfoStatusPayload | null;
74
78
  private emit;
79
+ private emitRequest;
75
80
  private readTerminal;
76
81
  private terminalTimestamp;
77
82
  private fenceTerminalRead;
@@ -79,7 +84,12 @@ export declare class OfficialClient implements OfficialOperations {
79
84
  requestContext(): {
80
85
  serverId: string;
81
86
  generation: `${string}-${string}-${string}-${string}-${string}`;
87
+ journal: OperationJournal | undefined;
82
88
  };
89
+ private beginRequestRead;
90
+ private fenceRequestReads;
91
+ private acceptRequestRead;
92
+ private readCurrent;
83
93
  current(agentId: string): Promise<{
84
94
  id: string;
85
95
  provider: string;
@@ -140,8 +150,10 @@ export declare class OfficialClient implements OfficialOperations {
140
150
  } | null>;
141
151
  activityTask(agentId: string, signal?: AbortSignal): Promise<{
142
152
  agentId: string;
153
+ provider: string;
143
154
  title: string | null;
144
155
  status: "error" | "running" | "idle" | "closed" | "initializing";
156
+ createdAt: string;
145
157
  updatedAt: string;
146
158
  lastUserMessageAt: string | null;
147
159
  activeTurnStartedAt: string | null;
@@ -168,8 +180,10 @@ export declare class OfficialClient implements OfficialOperations {
168
180
  measuredAt: number;
169
181
  tasks: {
170
182
  agentId: string;
183
+ provider: string;
171
184
  title: string | null;
172
185
  status: "error" | "running" | "idle" | "closed" | "initializing";
186
+ createdAt: string;
173
187
  updatedAt: string;
174
188
  lastUserMessageAt: string | null;
175
189
  activeTurnStartedAt: string | null;
@@ -45,7 +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 })) }; }
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
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 })) })) }; }
50
50
  export class OfficialClient {
51
51
  config;
@@ -57,6 +57,7 @@ export class OfficialClient {
57
57
  callbacks = new Set();
58
58
  unlisten;
59
59
  terminalReads = new Map();
60
+ requestReads = new Set();
60
61
  observationOrder = 0;
61
62
  constructor(config, journal) {
62
63
  this.config = config;
@@ -98,12 +99,13 @@ 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);
108
110
  }
109
111
  });
@@ -114,6 +116,15 @@ export class OfficialClient {
114
116
  emit(event) { if (Number.isSafeInteger(event.timestamp) && event.timestamp >= 0)
115
117
  for (const cb of this.callbacks)
116
118
  cb(event); }
119
+ emitRequest(agentId, request) {
120
+ const occurrence = this.journal?.currentOccurrence(this.serverId, agentId, request.id);
121
+ if (this.journal && !occurrence)
122
+ return;
123
+ // Pending requests have independent lifetimes. The global attention clock can
124
+ // still describe an older finished turn; never use it to expire a new request.
125
+ // Runtime journals retain one observation clock per exact current occurrence.
126
+ this.emit({ agentId, requestId: request.id, occurrence, kind: request.kind === 'question' ? 'question' : 'permission', timestamp: occurrence?.createdAt ?? Date.now() });
127
+ }
117
128
  readTerminal(event) {
118
129
  const read = { event, valid: true, next: null };
119
130
  this.terminalReads.set(event.agentId, read);
@@ -159,8 +170,38 @@ export class OfficialClient {
159
170
  pending.next = null;
160
171
  }
161
172
  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; }
173
+ requestContext() { return { serverId: this.serverId, generation: this.generation, journal: this.journal }; }
174
+ beginRequestRead(agentId) { const read = { agentId, observedOrder: ++this.observationOrder, stale: new Set() }; this.requestReads.add(read); return read; }
175
+ fenceRequestReads(agentId, observedOrder) {
176
+ // Track only in-flight reads, not an unbounded history of observed agents.
177
+ for (const read of this.requestReads)
178
+ if (read.observedOrder < observedOrder && (read.agentId === undefined || read.agentId === agentId))
179
+ read.stale.add(agentId);
180
+ }
181
+ acceptRequestRead(read, agentId) {
182
+ if (!this.requestReads.has(read) || read.stale.has(agentId))
183
+ return false;
184
+ this.fenceRequestReads(agentId, read.observedOrder);
185
+ return true;
186
+ }
187
+ async readCurrent(agentId, observe) {
188
+ const read = this.beginRequestRead(agentId);
189
+ try {
190
+ const value = await this.sdk.fetchAgent({ agentId, timeout: 15000 });
191
+ if (!this.acceptRequestRead(read, agentId))
192
+ return null;
193
+ const agent = value?.agent || null;
194
+ this.fenceTerminalRead(agentId, agent, read.observedOrder);
195
+ this.journal?.syncRequests(this.serverId, agentId, this.generation, agent?.pendingPermissions || []);
196
+ // Observation, journal synchronization and notification share one fence.
197
+ observe?.(agent);
198
+ return agent;
199
+ }
200
+ finally {
201
+ this.requestReads.delete(read);
202
+ }
203
+ }
204
+ async current(agentId) { return this.readCurrent(agentId); }
164
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; }
165
206
  async send(command) { if (!this.sdk.isConnected)
166
207
  throw Error('OFFICIAL_DISCONNECTED'); await this.sdk.sendAgentMessage(command.agentId, command.text, { messageId: command.messageId }); }
@@ -190,35 +231,35 @@ export class OfficialClient {
190
231
  const info = this.info();
191
232
  if (!info)
192
233
  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 });
234
+ const read = this.beginRequestRead();
235
+ try {
236
+ const result = await this.sdk.fetchAgents({ page: { limit: LIMITS.tasks }, filter: { includeArchived: false, includeInternal: false }, sort: [{ key: 'updated_at', direction: 'desc' }], timeout: 15000 });
237
+ const agents = result.entries.slice(0, LIMITS.tasks).map(entry => entry.agent).filter(agent => this.acceptRequestRead(read, agent.id));
238
+ for (const a of agents) {
239
+ this.fenceTerminalRead(a.id, a, read.observedOrder);
240
+ this.journal?.syncRequests(this.serverId, a.id, this.generation, a.pendingPermissions);
241
+ this.journal?.syncAttention(a.id, a.requiresAttention === true, a.attentionTimestamp ? Date.parse(a.attentionTimestamp) : null);
210
242
  }
211
- }
212
- let usage = null;
213
- if (info.features?.providerUsageList) {
214
- try {
215
- usage = projectUsage(await this.sdk.listProviderUsage());
243
+ for (const a of agents) {
244
+ for (const request of a.pendingPermissions)
245
+ this.emitRequest(a.id, request);
246
+ if (a.requiresAttention && a.attentionReason && a.attentionReason !== 'permission' && a.attentionTimestamp)
247
+ this.emit({ agentId: a.id, kind: a.attentionReason, timestamp: Date.parse(a.attentionTimestamp) });
216
248
  }
217
- catch {
218
- usage = null;
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
+ }
219
257
  }
258
+ return { version: 1, daemonServerId: info.serverId, hostName: (info.hostname || hostname()).slice(0, 256), measuredAt: Date.now(), tasks: agents.map(projectTask), usage };
259
+ }
260
+ finally {
261
+ this.requestReads.delete(read);
220
262
  }
221
- return { version: 1, daemonServerId: info.serverId, hostName: (info.hostname || hostname()).slice(0, 256), measuredAt: Date.now(), tasks: agents.map(projectTask), usage };
222
263
  }
223
- async close() { this.terminalReads.clear(); this.unlisten?.(); await this.subscription?.release().catch(() => { }); await this.sdk.close(); }
264
+ async close() { this.terminalReads.clear(); this.requestReads.clear(); this.unlisten?.(); await this.subscription?.release().catch(() => { }); await this.sdk.close(); }
224
265
  }
@@ -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')
@@ -9,8 +9,10 @@ export declare function projectSnapshot(source: Awaited<ReturnType<OfficialClien
9
9
  request: import("@getpaseo/protocol/agent-types").AgentPermissionRequest;
10
10
  }[];
11
11
  agentId: string;
12
+ provider: string;
12
13
  title: string | null;
13
14
  status: "error" | "running" | "idle" | "closed" | "initializing";
15
+ createdAt: string;
14
16
  updatedAt: string;
15
17
  lastUserMessageAt: string | null;
16
18
  activeTurnStartedAt: string | null;
@@ -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;