@moxuli/moremote 0.1.1 → 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.
@@ -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');
package/dist/runtime.js CHANGED
@@ -13,12 +13,15 @@ import { occurrenceBinding } from './bindings.js';
13
13
  import { projectSnapshot } from './projection.js';
14
14
  import { ownRuntime } from './control.js';
15
15
  import { LIMITS, object } from './limits.js';
16
+ import { ActivityPublisher, ActivityWorkLane, widgetFingerprint } from './activity.js';
16
17
  function stableId(value) { const h = createHash('sha256').update(JSON.stringify(value)).digest('hex').slice(0, 32); return h.slice(0, 8) + '-' + h.slice(8, 12) + '-' + h.slice(12, 16) + '-' + h.slice(16, 20) + '-' + h.slice(20); }
17
18
  export async function queueAttention(journal, pair, event, now = Date.now()) {
18
19
  if (event.timestamp + LIMITS.snapshotMs <= now || event.timestamp > now + LIMITS.futureMs)
19
20
  return;
20
21
  const payload = { agentId: event.agentId, kind: event.kind, timestamp: event.timestamp, ...(event.requestId ? { requestId: event.requestId } : {}), ...(event.requestBinding ? { requestBinding: event.requestBinding } : {}) };
21
- const id = stableId([pair.pairId, event.agentId, event.kind, event.requestId || '', event.sourceFingerprint || '', event.requestId && !event.sourceFingerprint ? null : event.timestamp]);
22
+ // A bound request notice belongs to its exact occurrence, not its snapshot clock.
23
+ // Keep the legacy source identity for callers without authoritative occurrences.
24
+ const id = event.requestId && event.occurrence ? stableId([pair.pairId, event.agentId, event.kind, event.requestId, 'occurrence', event.occurrence.occurrenceId]) : stableId([pair.pairId, event.agentId, event.kind, event.requestId || '', event.sourceFingerprint || '', event.requestId && !event.sourceFingerprint ? null : event.timestamp]);
22
25
  const issuedAt = event.timestamp;
23
26
  const envelope = await sealEnvelope(decode(pair.rootKey, 32), { version: 1, pairId: pair.pairId, id, channel: 'attention', issuedAt, expiresAt: issuedAt + LIMITS.snapshotMs }, payload);
24
27
  const topic = await presenceTopic(decode(pair.rootKey, 32), pair.pairId, event.agentId);
@@ -82,6 +85,8 @@ export async function runRuntime(dir, version) {
82
85
  const parentGone = () => { draining = true; drainWake.abort(); };
83
86
  let detach, closeJournal;
84
87
  const release = await ownRuntime(dir, () => ({ stage, lastError, activePairs, version: version ?? null }), stop);
88
+ const activityLane = new ActivityWorkLane();
89
+ let activityFailure = null, activityPairCursor = 0;
85
90
  try {
86
91
  const journal = new OperationJournal(join(dir, 'journal.sqlite'));
87
92
  closeJournal = () => journal.close();
@@ -98,6 +103,7 @@ export async function runRuntime(dir, version) {
98
103
  let measuredAt = 0;
99
104
  let snapshot;
100
105
  const statePublications = new Map();
106
+ const activityPublisher = new ActivityPublisher();
101
107
  const retryStates = new Map();
102
108
  const pollOrigins = new Set();
103
109
  process.once('SIGINT', stop);
@@ -108,7 +114,8 @@ export async function runRuntime(dir, version) {
108
114
  journal.cleanup(now);
109
115
  const config = await loadConfig(dir);
110
116
  pollOrigins.clear();
111
- let failure = null;
117
+ let failure = activityFailure;
118
+ activityFailure = null;
112
119
  let acquisitionFailed = false;
113
120
  const clouds = new Map();
114
121
  const cycleFences = new Map();
@@ -129,6 +136,7 @@ export async function runRuntime(dir, version) {
129
136
  for (const pairId of statePublications.keys())
130
137
  if (!config.pairs.some(pair => pair.pairId === pairId))
131
138
  statePublications.delete(pairId);
139
+ activityPublisher.retain(config.cloudEnabled ? config.pairs.filter(pair => pair.active && pair.relayRetiredAt === undefined && !journal.pairRevoked(pair.pairId)).map(pair => pair.pairId) : []);
132
140
  for (const origin of retryStates.keys())
133
141
  if (!config.pairs.some(pair => (pair.apiOrigin || config.apiOrigin) === origin))
134
142
  retryStates.delete(origin);
@@ -238,6 +246,33 @@ export async function runRuntime(dir, version) {
238
246
  if (bound)
239
247
  await queueAttention(journal, pair, bound);
240
248
  }
249
+ if (!stopped && !draining) {
250
+ const candidates = config.pairs.filter(pair => pair.active && pair.relayRetiredAt === undefined && !journal.pairRevoked(pair.pairId) && clouds.has(pair.pairId));
251
+ const ordered = [...candidates.slice(activityPairCursor), ...candidates.slice(0, activityPairCursor)], activitySnapshot = snapshot, activityOfficial = official;
252
+ // Schedule cached terminal recovery before any optional normal discovery.
253
+ // The owned lane never delays command acquisition and is aborted/joined on drain.
254
+ if (activityLane.start(async (signal) => {
255
+ let optionalFailure;
256
+ for (const terminalOnly of [true, false])
257
+ for (const pair of ordered) {
258
+ signal.throwIfAborted();
259
+ if (!pair.active || journal.pairRevoked(pair.pairId))
260
+ continue;
261
+ const cloud = clouds.get(pair.pairId);
262
+ try {
263
+ await activityPublisher.publish(pair, cloud, activitySnapshot, Date.now(), (agentId, readSignal) => activityOfficial.activityTask(agentId, readSignal), { signal, terminalOnly });
264
+ }
265
+ catch (error) {
266
+ if (signal.aborted)
267
+ throw error;
268
+ optionalFailure ??= error;
269
+ }
270
+ }
271
+ if (optionalFailure)
272
+ throw optionalFailure;
273
+ }, error => { activityFailure = error; }, AbortSignal.any([controller.signal, drainWake.signal])))
274
+ activityPairCursor = (activityPairCursor + 1) % Math.max(1, candidates.length);
275
+ }
241
276
  for (const pair of config.pairs) {
242
277
  if (stopped)
243
278
  break;
@@ -265,11 +300,11 @@ export async function runRuntime(dir, version) {
265
300
  if (!publication || publication.envelope.expiresAt <= Date.now() || (publication.acknowledged && publication.envelope.issuedAt !== snapshot.measuredAt)) {
266
301
  const payload = await projectSnapshot(snapshot, pair, journal, official.generation);
267
302
  const envelope = await sealEnvelope(decode(pair.rootKey, 32), { version: 1, pairId: pair.pairId, id: randomUUID(), channel: 'state', issuedAt: snapshot.measuredAt, expiresAt: snapshot.measuredAt + LIMITS.snapshotMs }, payload);
268
- publication = { envelope, acknowledged: false };
303
+ publication = { envelope, widgetFingerprint: await widgetFingerprint(pair, payload), acknowledged: false };
269
304
  statePublications.set(pair.pairId, publication);
270
305
  }
271
306
  if (!publication.acknowledged) {
272
- await cloud.state(publication.envelope);
307
+ await cloud.state(publication.envelope, publication.widgetFingerprint);
273
308
  publication.acknowledged = true;
274
309
  }
275
310
  }
@@ -360,6 +395,7 @@ export async function runRuntime(dir, version) {
360
395
  process.removeListener('message', parentMessage);
361
396
  process.removeListener('disconnect', parentGone);
362
397
  try {
398
+ await activityLane.close();
363
399
  detach?.();
364
400
  await official?.close().catch(() => { });
365
401
  }
package/dist/service.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { createHash, randomUUID } from 'node:crypto';
3
3
  import { join, dirname } from 'node:path';
4
- import { homedir, userInfo } from 'node:os';
4
+ import { homedir, userInfo, tmpdir } from 'node:os';
5
5
  import { constants } from 'node:fs';
6
- import { mkdir, readFile, unlink, access, lstat, open, rename, link, mkdtemp, rm } from 'node:fs/promises';
6
+ import { mkdir, readFile, unlink, access, lstat, open, rename, link, mkdtemp, rm, realpath } from 'node:fs/promises';
7
7
  import { privateDirectory, privateManagedDirectory } from './config.js';
8
8
  import { PACKAGE, exactVersion, updateLock } from './update-state.js';
9
9
  const taskName = '\\MoRemoteCLI';
@@ -90,6 +90,21 @@ function xmlValue(content, element) {
90
90
  const value = content.match(new RegExp('<' + element + '(?:\\s[^>]*)?>([\\s\\S]*?)</' + element + '>'))?.[1];
91
91
  return value?.replaceAll('&quot;', '"').replaceAll('&apos;', "'").replaceAll('&lt;', '<').replaceAll('&gt;', '>').replaceAll('&amp;', '&');
92
92
  }
93
+ async function sameRegistrationPath(actual, expected) {
94
+ if (actual === expected)
95
+ return true;
96
+ if (!actual)
97
+ return false;
98
+ try {
99
+ const [loaded, file] = await Promise.all([lstat(actual), lstat(expected)]);
100
+ return loaded.isFile() && !loaded.isSymbolicLink() && file.isFile() && !file.isSymbolicLink()
101
+ && loaded.dev === file.dev && loaded.ino === file.ino
102
+ && await realpath(actual) === await realpath(expected);
103
+ }
104
+ catch {
105
+ return false;
106
+ }
107
+ }
93
108
  async function registration(def, content) {
94
109
  if (def.platform === 'darwin') {
95
110
  let raw;
@@ -102,7 +117,7 @@ async function registration(def, content) {
102
117
  throw error;
103
118
  }
104
119
  const path = raw.match(/^\s*path = (.+)\s*$/m)?.[1]?.trim();
105
- if (path !== def.path)
120
+ if (!await sameRegistrationPath(path, def.path))
106
121
  throw Error('FOREIGN_SERVICE_REGISTRATION');
107
122
  }
108
123
  else if (def.platform === 'linux') {
@@ -110,7 +125,7 @@ async function registration(def, content) {
110
125
  const path = raw.match(/^FragmentPath=(.*)$/m)?.[1], load = raw.match(/^LoadState=(.*)$/m)?.[1];
111
126
  if (path === '' && load === 'not-found')
112
127
  return 'absent';
113
- if (path !== def.path)
128
+ if (!await sameRegistrationPath(path, def.path))
114
129
  throw Error(path ? 'FOREIGN_SERVICE_REGISTRATION' : 'SERVICE_MANAGER_INVALID_RESPONSE');
115
130
  }
116
131
  else if (def.platform === 'win32') {
@@ -154,6 +169,8 @@ async function writeDefinition(def) {
154
169
  const temp = def.path + '.' + randomUUID() + '.tmp';
155
170
  const handle = await open(temp, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
156
171
  try {
172
+ // Retained public runtimes read this ownership file without stripping a BOM.
173
+ // The native-only import below supplies the scheduler's required byte order.
157
174
  try {
158
175
  await handle.writeFile(def.content, def.platform === 'win32' ? 'utf16le' : 'utf8');
159
176
  await handle.sync();
@@ -179,6 +196,26 @@ async function writeDefinition(def) {
179
196
  await rm(temp, { force: true });
180
197
  }
181
198
  }
199
+ async function registerWindowsService(def) {
200
+ // Keep native import bytes outside the shared state consumed by old runtimes.
201
+ const temporary = await mkdtemp(join(tmpdir(), 'moremote-cli-task-')), path = join(temporary, 'task.xml');
202
+ try {
203
+ const handle = await open(path, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
204
+ try {
205
+ await handle.writeFile('\uFEFF' + def.content, 'utf16le');
206
+ await handle.sync();
207
+ }
208
+ finally {
209
+ await handle.close();
210
+ }
211
+ await command('schtasks', ['/Create', '/TN', taskName, '/XML', path, '/F']);
212
+ }
213
+ finally {
214
+ await rm(temporary, { recursive: true, force: true });
215
+ }
216
+ // Never leave the native-import copy present when the retained runtime starts.
217
+ await command('schtasks', ['/Run', '/TN', taskName]);
218
+ }
182
219
  export async function installService(def) {
183
220
  const status = await serviceStatus(def);
184
221
  requireKnown(status);
@@ -192,10 +229,8 @@ export async function installService(def) {
192
229
  await command('systemctl', ['--user', 'daemon-reload']);
193
230
  await command('systemctl', ['--user', 'enable', '--now', 'moremote-cli.service']);
194
231
  }
195
- else {
196
- await command('schtasks', ['/Create', '/TN', taskName, '/XML', def.path, '/F']);
197
- await command('schtasks', ['/Run', '/TN', taskName]);
198
- }
232
+ else
233
+ await registerWindowsService(def);
199
234
  }
200
235
  export async function stopService(def) {
201
236
  const status = await serviceStatus(def);
@@ -8,6 +8,7 @@ export interface ManagedRuntime {
8
8
  export declare function launchRuntime(entry: string, dir: string, onReady?: () => void): ManagedRuntime;
9
9
  export declare function drainRuntime(runtime: ManagedRuntime): Promise<number>;
10
10
  export declare function startupHealthy(runtime: ManagedRuntime, signal?: AbortSignal, grace?: number, deadline?: number, cancel?: () => boolean): Promise<boolean>;
11
+ export declare function stopManagedRuntime(dir: string): Promise<void>;
11
12
  export declare function runSupervisor(dir: string, timing?: {
12
13
  pollMs?: number;
13
14
  startupGraceMs?: number;
@@ -2,7 +2,8 @@ import { spawn } from 'node:child_process';
2
2
  import { setTimeout as sleep } from 'node:timers/promises';
3
3
  import { managedEntry } from './service.js';
4
4
  import { checkForUpdate, compatibleEntry } from './updater.js';
5
- import { readUpdateState, writeUpdateState, updateLock, supervisorStopRequested } from './update-state.js';
5
+ import { readUpdateState, writeUpdateState, updateLock, supervisorStopRequested, requestSupervisorStop, supervisorRunning } from './update-state.js';
6
+ import { requestControl, runtimeHasLiveOwner } from './control.js';
6
7
  export function launchRuntime(entry, dir, onReady = () => { }) {
7
8
  const child = spawn(process.execPath, [entry, 'run', '--data-dir', dir], { stdio: ['ignore', 'inherit', 'inherit', 'ipc'], windowsHide: true, env: { ...process.env, MOREMOTE_MANAGED_CHILD: '1' } });
8
9
  let ready = false, closed = false;
@@ -32,6 +33,48 @@ export async function startupHealthy(runtime, signal, grace = 10000, deadline =
32
33
  }
33
34
  return false;
34
35
  }
36
+ async function stopRuntime(dir) {
37
+ if (!await requestControl(dir, 'stop'))
38
+ return;
39
+ for (let i = 0; i < 300; i++) {
40
+ await sleep(200);
41
+ if (!await requestControl(dir, 'status'))
42
+ return;
43
+ }
44
+ throw Error('STOP_TIMEOUT');
45
+ }
46
+ export async function stopManagedRuntime(dir) {
47
+ requestSupervisorStop(dir);
48
+ let controlUnavailable = false;
49
+ // Native service shutdown may close IPC before its owned records are retired.
50
+ // A transport's absent generation is not proof that no replacement is alive.
51
+ try {
52
+ await stopRuntime(dir);
53
+ }
54
+ catch (error) {
55
+ if (error instanceof Error && (error.message === 'LEGACY_WINDOWS_CONTROL_UNAVAILABLE' || error.message === 'CONTROL_CONNECTION_CLOSED') && readUpdateState(dir))
56
+ controlUnavailable = true;
57
+ else
58
+ throw error;
59
+ }
60
+ if (!readUpdateState(dir)) {
61
+ if (runtimeHasLiveOwner(dir))
62
+ throw Error('STOP_TIMEOUT');
63
+ return;
64
+ }
65
+ for (let i = 0; i < 900; i++) {
66
+ if (!supervisorRunning(dir)) {
67
+ if (controlUnavailable && await requestControl(dir, 'status'))
68
+ throw Error('STOP_TIMEOUT');
69
+ // Revalidate synchronously after the awaited probe, including lock-only startup.
70
+ if (supervisorRunning(dir) || runtimeHasLiveOwner(dir))
71
+ throw Error('STOP_TIMEOUT');
72
+ return;
73
+ }
74
+ await sleep(200);
75
+ }
76
+ throw Error('SUPERVISOR_STOP_TIMEOUT');
77
+ }
35
78
  export async function runSupervisor(dir, timing = {}) {
36
79
  return updateLock(dir, async () => {
37
80
  let state = readUpdateState(dir);
package/docs/README.md CHANGED
@@ -1,9 +1,10 @@
1
1
  # Documentation index
2
2
 
3
3
  **MoRemote CLI**: independent optional `moremote-cli` repository/command,
4
- public npm `@moxuli/moremote`, over unmodified Paseo.
5
- STATE distinguishes historical pre-rename acceptance, renamed-tree checks and
6
- separately gated cloud/Apple activation.
4
+ public npm `@moxuli/moremote`0.1.1, over unmodified Paseo.
5
+ Activity/widget support is local unreleased source, not part of that published
6
+ package. [[STATE]] separates targeted local evidence from native/device/live
7
+ cloud acceptance, which remains pending for these new surfaces; cloud is disabled.
7
8
 
8
9
  - [Current state and external gates](STATE.md)
9
10
  - [Architecture](specs/01-architecture.md)