@moxuli/moremote 0.1.0 → 0.1.2

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/dist/control.js CHANGED
@@ -3,6 +3,7 @@ import { randomBytes, randomUUID, timingSafeEqual, createHash } from 'node:crypt
3
3
  import { join } from 'node:path';
4
4
  import { chmodSync, renameSync, readdirSync } from 'node:fs';
5
5
  import { assertStateRoot, createPrivateFile, hasCode, inspectResource, inspectRuntime, readRuntimeOwner, readRuntimeRecord, removeOwnedResource, runtimeMatches, RUNTIME_OWNER, sameResource, writePrivateAtomic } from './resources.js';
6
+ import { controlFraming, publishControlTransport, removeControlTransport } from './control-transport.js';
6
7
  export function controlEndpoint(dir) { return process.platform === 'win32' ? '\\\\.\\pipe\\moremote-cli-' + createHash('sha256').update(dir).digest('hex').slice(0, 24) : join(dir, 'runtime.sock'); }
7
8
  function object(value) { return typeof value === 'object' && value !== null && !Array.isArray(value); }
8
9
  function removeRuntimeFile(path, identity, owner, record = false) {
@@ -27,6 +28,15 @@ function running(pid) {
27
28
  throw error;
28
29
  }
29
30
  }
31
+ export function runtimeHasLiveOwner(dir) {
32
+ if (!inspectResource(dir, 'directory', true))
33
+ return false;
34
+ if (readdirSync(dir).length === 0)
35
+ return false;
36
+ assertStateRoot(dir);
37
+ const { lock } = inspectRuntime(dir);
38
+ return lock !== null && running(lock.value.pid);
39
+ }
30
40
  export async function requestControl(dir, action) {
31
41
  if (!inspectResource(dir, 'directory', true))
32
42
  return null;
@@ -40,53 +50,95 @@ export async function requestControl(dir, action) {
40
50
  return null;
41
51
  const expectedRecord = resources.record.identity;
42
52
  const record = resources.record.value;
53
+ const framing = controlFraming(dir, record);
54
+ if (framing === 'legacy-eof' && process.platform === 'win32') {
55
+ if (!running(record.pid))
56
+ return null;
57
+ throw Error('LEGACY_WINDOWS_CONTROL_UNAVAILABLE');
58
+ }
43
59
  const ownerEnded = () => { const path = join(dir, 'runtime.json'); if (!inspectResource(path, 'file', true))
44
60
  return true; const current = readRuntimeRecord(path); return !sameResource(current.identity, expectedRecord) || !runtimeMatches(current.value, record); };
45
- const disconnected = () => { try {
61
+ const { promise, resolve, reject } = Promise.withResolvers();
62
+ const socket = createConnection(controlEndpoint(dir));
63
+ let raw = '', settled = false;
64
+ socket.setEncoding('utf8');
65
+ const succeed = (value) => { if (settled)
66
+ return; settled = true; clearTimeout(timer); socket.destroy(); resolve(value); };
67
+ const fail = (error) => { if (settled)
68
+ return; settled = true; clearTimeout(timer); socket.destroy(); reject(error); };
69
+ const disconnected = () => { if (settled)
70
+ return; if (raw) {
71
+ fail(Error('CONTROL_INVALID_RESPONSE'));
72
+ return;
73
+ } try {
46
74
  if (ownerEnded())
47
- resolve(null);
75
+ succeed(null);
48
76
  else
49
- reject(Error('CONTROL_CONNECTION_CLOSED'));
77
+ fail(Error('CONTROL_CONNECTION_CLOSED'));
50
78
  }
51
79
  catch (error) {
52
- reject(error);
80
+ fail(error);
53
81
  } };
54
- const { promise, resolve, reject } = Promise.withResolvers();
55
- const socket = createConnection(controlEndpoint(dir));
56
- let raw = '';
57
- socket.setTimeout(2000);
82
+ const parseResponse = (frame) => { try {
83
+ const value = JSON.parse(frame);
84
+ if (!object(value))
85
+ throw Error('CONTROL_INVALID_RESPONSE');
86
+ succeed(value);
87
+ }
88
+ catch {
89
+ fail(Error('CONTROL_INVALID_RESPONSE'));
90
+ } };
91
+ const timer = setTimeout(() => fail(Error('CONTROL_TIMEOUT')), 2000);
58
92
  socket.on('connect', () => {
59
93
  try {
60
94
  const current = inspectRuntime(dir);
61
95
  if (!current.record || !sameResource(current.record.identity, expectedRecord) || !runtimeMatches(current.record.value, record))
62
96
  throw Error('RUNTIME_RESOURCE_COLLISION');
63
- socket.end(JSON.stringify({ token: record.token, action }) + '\n');
97
+ if (controlFraming(dir, current.record.value) !== framing)
98
+ throw Error('CONTROL_TRANSPORT_CHANGED');
99
+ const payload = JSON.stringify({ token: record.token, action }) + '\n';
100
+ // The owned generation fact selects exactly one exchange, never a timeout
101
+ // probe/replay. Published 0.1.0 uses EOF; new named pipes remain duplex.
102
+ if (framing === 'legacy-eof')
103
+ socket.end(payload);
104
+ else
105
+ socket.write(payload);
64
106
  }
65
107
  catch (error) {
66
- socket.destroy(error instanceof Error ? error : Error('CONTROL_INVALID'));
108
+ fail(error);
67
109
  }
68
110
  });
69
- socket.on('data', chunk => { raw += chunk; if (Buffer.byteLength(raw) > 4096)
70
- socket.destroy(Error('CONTROL_LIMIT')); });
71
- socket.on('end', () => { if (!raw) {
72
- disconnected();
73
- return;
74
- } try {
75
- const value = JSON.parse(raw);
76
- if (!object(value))
77
- throw Error('CONTROL_INVALID_RESPONSE');
78
- resolve(value);
79
- }
80
- catch {
81
- reject(Error('CONTROL_INVALID_RESPONSE'));
82
- } });
83
- socket.on('timeout', () => socket.destroy(Error('CONTROL_TIMEOUT')));
84
- socket.on('error', error => { if (hasCode(error, 'ECONNREFUSED') || hasCode(error, 'ENOENT'))
85
- resolve(null);
111
+ socket.on('data', chunk => {
112
+ if (settled)
113
+ return;
114
+ raw += chunk;
115
+ if (Buffer.byteLength(raw) > 4096) {
116
+ fail(Error('CONTROL_LIMIT'));
117
+ return;
118
+ }
119
+ if (framing === 'legacy-eof')
120
+ return;
121
+ const end = raw.indexOf('\n');
122
+ if (end < 0)
123
+ return;
124
+ if (end !== raw.length - 1) {
125
+ fail(Error('CONTROL_INVALID_RESPONSE'));
126
+ return;
127
+ }
128
+ parseResponse(raw.slice(0, end));
129
+ });
130
+ socket.on('end', () => { if (framing === 'legacy-eof' && raw)
131
+ parseResponse(raw);
132
+ else
133
+ disconnected(); });
134
+ socket.on('close', disconnected);
135
+ socket.on('error', error => { if (settled)
136
+ return; if (hasCode(error, 'ECONNREFUSED') || hasCode(error, 'ENOENT'))
137
+ succeed(null);
86
138
  else if (hasCode(error, 'ECONNRESET') || hasCode(error, 'EPIPE'))
87
139
  disconnected();
88
140
  else
89
- reject(error); });
141
+ fail(error); });
90
142
  return promise;
91
143
  }
92
144
  function closeServer(server) {
@@ -138,36 +190,57 @@ export async function ownRuntime(dir, status, stop) {
138
190
  const lockPath = join(dir, 'runtime.lock'), recordPath = join(dir, 'runtime.json');
139
191
  let lock = createPrivateFile(lockPath, JSON.stringify(owner) + '\n');
140
192
  const staging = process.platform === 'win32' ? endpoint : join(dir, 's.' + owner.instanceId.slice(0, 8));
141
- let socketIdentity = null, recordIdentity = null;
193
+ let socketIdentity = null, recordIdentity = null, transportIdentity;
142
194
  const server = createServer({ allowHalfOpen: true }, socket => {
143
- let raw = '';
144
- socket.setTimeout(2000, () => socket.destroy());
195
+ let raw = '', handled = false;
196
+ socket.setEncoding('utf8');
197
+ const timer = setTimeout(() => socket.destroy(), 2000);
198
+ socket.once('close', () => clearTimeout(timer));
145
199
  socket.on('error', () => { });
146
- socket.on('data', chunk => { raw += chunk; if (Buffer.byteLength(raw) > 4096)
147
- socket.destroy(); });
148
- socket.on('end', () => {
200
+ socket.on('end', () => socket.destroy());
201
+ const reply = (value) => { const frame = JSON.stringify(value) + '\n'; if (Buffer.byteLength(frame) > 4096)
202
+ socket.destroy();
203
+ else
204
+ socket.write(frame); };
205
+ socket.on('data', chunk => {
206
+ if (handled) {
207
+ socket.destroy();
208
+ return;
209
+ }
210
+ raw += chunk;
211
+ if (Buffer.byteLength(raw) > 4096) {
212
+ handled = true;
213
+ socket.destroy();
214
+ return;
215
+ }
216
+ const end = raw.indexOf('\n');
217
+ if (end < 0)
218
+ return;
219
+ handled = true;
149
220
  try {
150
- const request = JSON.parse(raw);
221
+ if (end !== raw.length - 1)
222
+ throw Error('CONTROL_FRAME');
223
+ const request = JSON.parse(raw.slice(0, end));
151
224
  if (!object(request) || typeof request.token !== 'string' || request.token.length !== 43)
152
225
  throw Error('CONTROL_AUTH');
153
226
  const left = Buffer.from(request.token), right = Buffer.from(owner.token);
154
227
  if (left.length !== right.length || !timingSafeEqual(left, right))
155
228
  throw Error('CONTROL_AUTH');
156
229
  if (request.action === 'stop') {
157
- socket.end(JSON.stringify({ ok: true, stopping: true }));
158
230
  stop();
231
+ reply({ ok: true, stopping: true });
159
232
  }
160
233
  else if (request.action === 'status') {
161
234
  const value = status();
162
235
  if (!object(value))
163
236
  throw Error('CONTROL_STATUS');
164
- socket.end(JSON.stringify({ ok: true, ...value }));
237
+ reply({ ok: true, ...value });
165
238
  }
166
239
  else
167
240
  throw Error('CONTROL_ACTION');
168
241
  }
169
242
  catch {
170
- socket.end(JSON.stringify({ ok: false }));
243
+ reply({ ok: false });
171
244
  }
172
245
  });
173
246
  });
@@ -196,6 +269,9 @@ export async function ownRuntime(dir, status, stop) {
196
269
  renameSync(staging, endpoint);
197
270
  socketIdentity = { dev: secured.dev, ino: secured.ino };
198
271
  }
272
+ // Publish the generation fact durably before making its unchanged legacy-
273
+ // compatible record visible; readers can never select EOF for this record.
274
+ transportIdentity = await publishControlTransport(dir, owner);
199
275
  recordIdentity = writePrivateAtomic(recordPath, { ...owner, socket: socketIdentity });
200
276
  }
201
277
  catch (error) {
@@ -204,6 +280,8 @@ export async function ownRuntime(dir, status, stop) {
204
280
  removeOwnedResource(endpoint, socketIdentity, 'socket');
205
281
  if (recordIdentity)
206
282
  removeRuntimeFile(recordPath, recordIdentity, owner, true);
283
+ if (transportIdentity)
284
+ removeControlTransport(dir, transportIdentity, owner);
207
285
  removeRuntimeFile(lockPath, lock, owner);
208
286
  throw error;
209
287
  }
@@ -220,6 +298,8 @@ export async function ownRuntime(dir, status, stop) {
220
298
  if (recordIdentity)
221
299
  removeRuntimeFile(recordPath, recordIdentity, owner, true);
222
300
  removeRuntimeFile(lockPath, lock, owner);
301
+ if (transportIdentity)
302
+ removeControlTransport(dir, transportIdentity, owner);
223
303
  })();
224
304
  return closing;
225
305
  };
package/dist/crypto.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export type Channel = 'enrollment' | 'activation' | 'command' | 'receipt' | 'state' | 'attention' | 'control' | 'controlReceipt';
1
+ export type Channel = 'enrollment' | 'activation' | 'command' | 'receipt' | 'state' | 'attention' | 'control' | 'controlReceipt' | 'activityInterest' | 'activityState';
2
2
  export interface Metadata {
3
3
  version: 1;
4
4
  pairId: string;
package/dist/crypto.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { webcrypto, randomBytes } from 'node:crypto';
2
2
  import { LIMITS, UUID, object, exact } from './limits.js';
3
3
  const subtle = webcrypto.subtle;
4
- const channels = ['enrollment', 'activation', 'command', 'receipt', 'state', 'attention', 'control', 'controlReceipt'];
4
+ const channels = ['enrollment', 'activation', 'command', 'receipt', 'state', 'attention', 'control', 'controlReceipt', 'activityInterest', 'activityState'];
5
5
  function bytes(v) { return Uint8Array.from(v); }
6
6
  export function decode(value, length) { if (typeof value !== 'string' || !/^[A-Za-z0-9_-]+$/.test(value))
7
7
  throw Error('INVALID_BASE64URL'); const b = Buffer.from(value, 'base64url'); if (b.toString('base64url') !== value || (length !== undefined && b.length !== length))
@@ -15,7 +15,7 @@ export function validateEnvelope(input, now, allowExpired = false) {
15
15
  throw Error('RECEIPT_LIMIT');
16
16
  if (!Number.isSafeInteger(e.issuedAt) || !Number.isSafeInteger(e.expiresAt) || Number(e.issuedAt) < 0 || Number(e.expiresAt) <= Number(e.issuedAt))
17
17
  throw Error('INVALID_TIME');
18
- const ttl = e.channel === 'command' || e.channel === 'control' ? LIMITS.commandMs : LIMITS.enrollmentMs;
18
+ const ttl = e.channel === 'activityInterest' ? 8 * 60 * 60 * 1000 : e.channel === 'command' || e.channel === 'control' ? LIMITS.commandMs : LIMITS.enrollmentMs;
19
19
  if (Number(e.expiresAt) - Number(e.issuedAt) > ttl || Number(e.issuedAt) > now + LIMITS.futureMs || (!allowExpired && Number(e.expiresAt) <= now))
20
20
  throw Error('EXPIRED_OR_FUTURE');
21
21
  decode(e.nonce, 12);
package/dist/journal.js CHANGED
@@ -102,8 +102,9 @@ export class OperationJournal {
102
102
  retire(serverId, agentId, requestId) { this.db.prepare('UPDATE occurrences SET active=0 WHERE serverId=? AND agentId=? AND requestId=?').run(serverId, agentId, requestId); this.db.prepare('UPDATE attention SET resolvedAt=? WHERE agentId=? AND requestId=? AND resolvedAt IS NULL').run(Date.now(), agentId, requestId); }
103
103
  retireGeneration(serverId, generation) { for (const r of this.db.prepare('SELECT agentId,requestId FROM occurrences WHERE serverId=? AND generation!=? AND active=1').all(serverId, generation))
104
104
  this.retire(serverId, r.agentId, r.requestId); }
105
+ // Pending requests are authoritative even when the agent attention flag is false.
105
106
  syncAttention(agentId, requiresAttention, timestamp) { if (!requiresAttention)
106
- this.db.prepare('UPDATE attention SET resolvedAt=? WHERE agentId=? AND resolvedAt IS NULL').run(Date.now(), agentId);
107
+ this.db.prepare('UPDATE attention SET resolvedAt=? WHERE agentId=? AND requestId IS NULL AND resolvedAt IS NULL').run(Date.now(), agentId);
107
108
  else if (timestamp !== null)
108
109
  this.db.prepare("UPDATE attention SET resolvedAt=? WHERE agentId=? AND requestId IS NULL AND resolvedAt IS NULL AND body!='' AND json_extract(body,'$.envelope.issuedAt')!=?").run(Date.now(), agentId, timestamp); }
109
110
  resolution(serverId, agentId, requestId, generation, response, now = Date.now()) { const occurrence = this.currentOccurrence(serverId, agentId, requestId); if (occurrence?.generation === generation)
@@ -1,5 +1,5 @@
1
1
  import type { DaemonClient } from '@getpaseo/client/internal/daemon-client';
2
- import type { ServerInfoStatusPayload } from '@getpaseo/protocol/messages';
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
5
  import { type ReceiptState, type OperationJournal } from './journal.js';
@@ -13,6 +13,50 @@ export interface Attention {
13
13
  }
14
14
  export declare function localListen(home: string): string;
15
15
  export declare function readLocalCredentialForTarget(home: string, target: string): string | undefined;
16
+ export declare function projectTask(a: AgentSnapshotPayload): {
17
+ 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
+ pendingRequests: {
27
+ requestId: string;
28
+ request: import("@getpaseo/protocol/agent-types").AgentPermissionRequest;
29
+ }[];
30
+ };
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
+ };
16
60
  export declare class OfficialClient implements OfficialOperations {
17
61
  readonly config: Config;
18
62
  private journal?;
@@ -22,10 +66,15 @@ export declare class OfficialClient implements OfficialOperations {
22
66
  private serverId;
23
67
  private callbacks;
24
68
  private unlisten;
69
+ private terminalReads;
70
+ private observationOrder;
25
71
  constructor(config: Config, journal?: OperationJournal | undefined);
26
72
  connect(): Promise<void>;
27
73
  info(): ServerInfoStatusPayload | null;
28
74
  private emit;
75
+ private readTerminal;
76
+ private terminalTimestamp;
77
+ private fenceTerminalRead;
29
78
  onAttention(callback: (event: Attention) => void): () => void;
30
79
  requestContext(): {
31
80
  serverId: string;
@@ -39,7 +88,7 @@ export declare class OfficialClient implements OfficialOperations {
39
88
  createdAt: string;
40
89
  updatedAt: string;
41
90
  lastUserMessageAt: string | null;
42
- status: "error" | "initializing" | "idle" | "running" | "closed";
91
+ status: "error" | "running" | "idle" | "closed" | "initializing";
43
92
  capabilities: import("@getpaseo/protocol/agent-types").AgentCapabilityFlags;
44
93
  currentModeId: string | null;
45
94
  availableModes: import("@getpaseo/protocol/agent-types").AgentMode[];
@@ -83,12 +132,27 @@ export declare class OfficialClient implements OfficialOperations {
83
132
  lastUsage?: import("@getpaseo/protocol/agent-types").AgentUsage | undefined;
84
133
  lastError?: string | undefined;
85
134
  requiresAttention?: boolean | undefined;
86
- attentionReason?: "permission" | "finished" | "error" | null | undefined;
135
+ attentionReason?: "permission" | "error" | "finished" | null | undefined;
87
136
  attentionTimestamp?: string | null | undefined;
88
137
  archivedAt?: string | null | undefined;
89
138
  providerUnavailable?: boolean | undefined;
90
139
  internal?: boolean | undefined;
91
140
  } | 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;
154
+ }[];
155
+ } | null>;
92
156
  send(command: Extract<Command, {
93
157
  type: 'send';
94
158
  }>): Promise<void>;
@@ -105,10 +169,13 @@ export declare class OfficialClient implements OfficialOperations {
105
169
  tasks: {
106
170
  agentId: string;
107
171
  title: string | null;
108
- status: "error" | "initializing" | "idle" | "running" | "closed";
172
+ status: "error" | "running" | "idle" | "closed" | "initializing";
109
173
  updatedAt: string;
174
+ lastUserMessageAt: string | null;
175
+ activeTurnStartedAt: string | null;
176
+ cwd: string | null;
110
177
  requiresAttention: boolean;
111
- attentionReason: "permission" | "finished" | "error" | null;
178
+ attentionReason: "permission" | "error" | "finished" | null;
112
179
  pendingRequests: {
113
180
  requestId: string;
114
181
  request: import("@getpaseo/protocol/agent-types").AgentPermissionRequest;
@@ -45,6 +45,8 @@ 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
50
  export class OfficialClient {
49
51
  config;
50
52
  journal;
@@ -54,6 +56,8 @@ export class OfficialClient {
54
56
  serverId = '';
55
57
  callbacks = new Set();
56
58
  unlisten;
59
+ terminalReads = new Map();
60
+ observationOrder = 0;
57
61
  constructor(config, journal) {
58
62
  this.config = config;
59
63
  this.journal = journal;
@@ -77,8 +81,20 @@ export class OfficialClient {
77
81
  this.unlisten = this.sdk.subscribeRawMessages(message => {
78
82
  if (message.type === 'agent_attention_required') {
79
83
  const p = message.payload;
80
- if (p.reason !== 'permission')
81
- this.emit({ agentId: p.agentId, kind: p.reason, timestamp: Date.parse(p.timestamp) });
84
+ if (p.reason !== 'permission') {
85
+ const event = { agentId: p.agentId, kind: p.reason, timestamp: Date.parse(p.timestamp), observedOrder: ++this.observationOrder };
86
+ if (!Number.isSafeInteger(event.timestamp) || event.timestamp < 0)
87
+ return;
88
+ const pending = this.terminalReads.get(p.agentId);
89
+ if (pending) {
90
+ const latest = pending.next || pending.event;
91
+ if (event.timestamp < latest.timestamp || event.timestamp === latest.timestamp && event.kind === latest.kind)
92
+ return;
93
+ pending.next = event;
94
+ }
95
+ else
96
+ this.readTerminal(event);
97
+ }
82
98
  }
83
99
  if (message.type === 'agent_permission_request') {
84
100
  const p = message.payload;
@@ -98,9 +114,54 @@ export class OfficialClient {
98
114
  emit(event) { if (Number.isSafeInteger(event.timestamp) && event.timestamp >= 0)
99
115
  for (const cb of this.callbacks)
100
116
  cb(event); }
117
+ readTerminal(event) {
118
+ const read = { event, valid: true, next: null };
119
+ this.terminalReads.set(event.agentId, read);
120
+ const complete = (agent) => {
121
+ if (this.terminalReads.get(event.agentId) !== read)
122
+ return;
123
+ this.terminalReads.delete(event.agentId);
124
+ if (read.next) {
125
+ this.readTerminal(read.next);
126
+ return;
127
+ }
128
+ if (!read.valid)
129
+ return;
130
+ const timestamp = this.terminalTimestamp(agent, event);
131
+ if (timestamp !== null)
132
+ this.emit({ agentId: event.agentId, kind: event.kind, timestamp });
133
+ };
134
+ // At most one read and one latest event per agent; no retry without a new event.
135
+ // Terminal hydration is read-only; stale replies must not resync requests.
136
+ void this.sdk.fetchAgent({ agentId: event.agentId, timeout: 15000 }).then(value => complete(value?.agent || null)).catch(() => complete(null));
137
+ }
138
+ terminalTimestamp(agent, event) {
139
+ if (!agent || agent.id !== event.agentId || !agent.requiresAttention || agent.attentionReason !== event.kind || agent.activeTurn)
140
+ return null;
141
+ if (event.kind === 'finished' ? agent.status !== 'idle' && agent.status !== 'closed' : agent.status !== 'error')
142
+ return null;
143
+ const timestamp = Date.parse(agent.attentionTimestamp || '');
144
+ // Paseo sets attention before broadcasting; the raw clock is delivery time,
145
+ // not identity. A later attention or user turn cannot belong to this event.
146
+ if (!Number.isSafeInteger(timestamp) || timestamp < 0 || timestamp > event.timestamp || agent.lastUserMessageAt && Date.parse(agent.lastUserMessageAt) > event.timestamp)
147
+ return null;
148
+ return timestamp;
149
+ }
150
+ fenceTerminalRead(agentId, agent, observationOrder) {
151
+ const pending = this.terminalReads.get(agentId);
152
+ if (!pending)
153
+ return;
154
+ // A request begun before an event cannot retire that newer event, even if
155
+ // its older server snapshot arrives later. Keep the slot until it settles.
156
+ if (observationOrder >= pending.event.observedOrder && this.terminalTimestamp(agent, pending.event) === null)
157
+ pending.valid = false;
158
+ if (pending.next && observationOrder >= pending.next.observedOrder && this.terminalTimestamp(agent, pending.next) === null)
159
+ pending.next = null;
160
+ }
101
161
  onAttention(callback) { this.callbacks.add(callback); return () => { this.callbacks.delete(callback); }; }
102
162
  requestContext() { return { serverId: this.serverId, generation: this.generation }; }
103
- async current(agentId) { const value = await this.sdk.fetchAgent({ agentId, timeout: 15000 }); this.journal?.syncRequests(this.serverId, agentId, this.generation, value?.agent.pendingPermissions || []); return value?.agent || null; }
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; }
104
165
  async send(command) { if (!this.sdk.isConnected)
105
166
  throw Error('OFFICIAL_DISCONNECTED'); await this.sdk.sendAgentMessage(command.agentId, command.text, { messageId: command.messageId }); }
106
167
  async permission(command) { if (!this.sdk.isConnected)
@@ -129,9 +190,11 @@ export class OfficialClient {
129
190
  const info = this.info();
130
191
  if (!info)
131
192
  throw Error('OFFICIAL_IDENTITY_UNAVAILABLE');
193
+ const observationOrder = ++this.observationOrder;
132
194
  const result = await this.sdk.fetchAgents({ page: { limit: LIMITS.tasks }, filter: { includeArchived: false, includeInternal: false }, sort: [{ key: 'updated_at', direction: 'desc' }], timeout: 15000 });
133
195
  const agents = result.entries.slice(0, LIMITS.tasks).map(entry => entry.agent);
134
196
  for (const a of agents) {
197
+ this.fenceTerminalRead(a.id, a, observationOrder);
135
198
  this.journal?.syncRequests(this.serverId, a.id, this.generation, a.pendingPermissions);
136
199
  this.journal?.syncAttention(a.id, a.requiresAttention === true, a.attentionTimestamp ? Date.parse(a.attentionTimestamp) : null);
137
200
  }
@@ -149,14 +212,13 @@ export class OfficialClient {
149
212
  let usage = null;
150
213
  if (info.features?.providerUsageList) {
151
214
  try {
152
- const u = await this.sdk.listProviderUsage();
153
- usage = { fetchedAt: u.fetchedAt, providers: u.providers.slice(0, 16).map(p => ({ providerId: p.providerId.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), 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), used: b.used ?? null, remaining: b.remaining ?? null, limit: b.limit ?? null, unit: b.unit, resetsAt: b.resetsAt ?? null })) })) };
215
+ usage = projectUsage(await this.sdk.listProviderUsage());
154
216
  }
155
217
  catch {
156
218
  usage = null;
157
219
  }
158
220
  }
159
- return { version: 1, daemonServerId: info.serverId, hostName: (info.hostname || hostname()).slice(0, 256), measuredAt: Date.now(), tasks: agents.map(a => ({ agentId: a.id, title: a.title?.slice(0, 160) || null, status: a.status, updatedAt: a.updatedAt, requiresAttention: a.requiresAttention || false, attentionReason: a.attentionReason || null, pendingRequests: a.pendingPermissions.slice(0, 10).map(request => ({ requestId: request.id, request })) })), usage };
221
+ return { version: 1, daemonServerId: info.serverId, hostName: (info.hostname || hostname()).slice(0, 256), measuredAt: Date.now(), tasks: agents.map(projectTask), usage };
160
222
  }
161
- async close() { this.unlisten?.(); await this.subscription?.release().catch(() => { }); await this.sdk.close(); }
223
+ async close() { this.terminalReads.clear(); this.unlisten?.(); await this.subscription?.release().catch(() => { }); await this.sdk.close(); }
162
224
  }
@@ -10,10 +10,13 @@ export declare function projectSnapshot(source: Awaited<ReturnType<OfficialClien
10
10
  }[];
11
11
  agentId: string;
12
12
  title: string | null;
13
- status: "error" | "initializing" | "idle" | "running" | "closed";
13
+ status: "error" | "running" | "idle" | "closed" | "initializing";
14
14
  updatedAt: string;
15
+ lastUserMessageAt: string | null;
16
+ activeTurnStartedAt: string | null;
17
+ cwd: string | null;
15
18
  requiresAttention: boolean;
16
- attentionReason: "permission" | "finished" | "error" | null;
19
+ attentionReason: "permission" | "error" | "finished" | null;
17
20
  }[];
18
21
  tasksTruncated: boolean;
19
22
  version: number;
package/dist/resources.js CHANGED
@@ -242,7 +242,8 @@ export function writePrivateAtomic(path, value) {
242
242
  export function assertTaskResource(dir, platform = process.platform) {
243
243
  if (platform !== 'win32')
244
244
  throw Error('FOREIGN_TASK_RESOURCE');
245
- const text = readPrivateText(join(dir, 'moremote-cli-task.xml'), 131072, 'utf16le').text;
245
+ const encoded = readPrivateText(join(dir, 'moremote-cli-task.xml'), 131072, 'utf16le').text;
246
+ const text = encoded.startsWith('\uFEFF') ? encoded.slice(1) : encoded;
246
247
  const marker = 'Managed by moremote-cli; per-user ownership v1; owner=' + createHash('sha256').update(dir).digest('hex');
247
248
  if (!text.startsWith('<?xml version="1.0" encoding="UTF-16"?>') || !text.includes('<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">') || !text.includes('<Description>' + marker + '</Description>') || !text.trimEnd().endsWith('</Task>'))
248
249
  throw Error('FOREIGN_TASK_RESOURCE');