@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/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  Optional, independent Apache-2.0 computer companion for MoRemote and an **unmodified Paseo 0.15.3** daemon. Existing official-only clients keep working without this project or its cloud.
4
4
 
5
5
  Canonical repository/command: `moremote-cli`; public npm package:
6
- **`@moxuli/moremote`**; source entry: `bin/moremote-cli.js`.
6
+ **`@moxuli/moremote`** (published **0.1.1**); source entry: `bin/moremote-cli.js`.
7
7
  There is no unscoped npm alias or automatic adoption of foreign/old state.
8
8
 
9
9
  ## Install the published package
@@ -34,6 +34,26 @@ node bin/moremote-cli.js run
34
34
 
35
35
  The example endpoint is synthetic. Omit `--target` to use the official `paseo.pid` listen address under `PASEO_HOME` (otherwise the platform home’s `.paseo`). Auth follows the official CLI: target password, then `PASEO_PASSWORD`, otherwise a rotating local credential only when the selected target exactly matches the pid listen address after official normalization. Credentials are never printed or uploaded. No automatic daemon start or upgrade.
36
36
 
37
+ ## Connect to the hosted MoRemote service
38
+
39
+ After the published package is installed, explicitly enable the optional cloud
40
+ connection while leaving the official Paseo daemon unchanged:
41
+
42
+ ```sh
43
+ moremote-cli configure --api-origin https://moremote-cloud-ingress.pages.dev --cloud-on
44
+ moremote-cli check --connect
45
+ moremote-cli pair
46
+ moremote-cli run
47
+ ```
48
+
49
+ Scan the private one-use offer in MoRemote's system integration setup. Keep
50
+ `run` in the foreground, or separately choose background installation with
51
+ `moremote-cli service install --yes`. Configuration and package installation do
52
+ not silently register a service. The hosted backend operates continuously;
53
+ cloud participation remains off until each CLI user explicitly enables it.
54
+ Production TestFlight tokens use production APNs, not a sandbox backend.
55
+
56
+
37
57
  For a separately operated relay:
38
58
 
39
59
  ```sh
@@ -44,6 +64,33 @@ node bin/moremote-cli.js run
44
64
 
45
65
  `pair` explicitly prints a **secret**, ten-minute, one-phone QR/link. Do not share screenshots or put it in logs. `--json` emits the canonical offer for explicit paste. It waits for the one-use claim and verifies the phone’s encrypted proof before activating that phone, within the original offer deadline. Each phone gets its own local 32-byte root key; only the phone receives it, never the relay. See [wire contracts](docs/specs/02-encrypted-delivery.md), [endpoint controls](docs/specs/04-control-and-receipt-lifecycle.md) and [endpoint behavior](docs/specs/05-endpoint-and-lifecycle.md).
46
66
 
67
+ ## Optional activities and widget reloads — unreleased source
68
+
69
+ Local source adds per-task encrypted Live Activity state and keyed widget-change
70
+ fingerprints. These changes are **not in published 0.1.1**; the package version
71
+ has not changed. They require a compatible native app and separately configured
72
+ relay/APNs capabilities; installing the CLI alone enables neither surface.
73
+ Cloud remains off by default.
74
+
75
+ The phone owns task selection, encrypted read-only interest and native push
76
+ tokens; the companion authenticates that interest against the pinned daemon and
77
+ publishes bounded official task measurements. Up to eight interests per pairing
78
+ expire within eight hours; activity states expire within ten minutes. Missing
79
+ tasks are not reported finished. Acknowledged ongoing state renews from fresh
80
+ measurements around every eight minutes; lost acknowledgements preserve exact
81
+ ciphertext until expiry. Commands and controls do not await the optional activity
82
+ lane. Widget reloads depend on meaningful snapshot changes, use the existing
83
+ encrypted snapshot and are opportunistic, not realtime delivery.
84
+
85
+ The relay sees opaque routing/equality tags, registration identities, tokens,
86
+ environment, envelope metadata and ciphertext—not decrypted task titles or
87
+ usage. Apple receives the token and push payload: encrypted activity content or
88
+ a generic widget-change signal. Device rendering, widget freshness/offline
89
+ behavior and APNs delivery for these new surfaces remain **pending acceptance**;
90
+ APNs HTTP 200 means provider admission only. See [operator limits and failure
91
+ semantics](docs/configuration.md#optional-activity-and-widget-surfaces-unreleased)
92
+ and the [living wire contract](docs/specs/03-api-contract.md#opt-in-task-activities-and-widget-reloads).
93
+
47
94
  ## What leaves the computer
48
95
 
49
96
  The cloud sees pairing/operation/event identities, times, sizes, bounded transport states, scoped capability hashes and encrypted command/control/receipt/state/attention bodies. Attention routing includes a separately derived opaque conversation tag; default push text is generic. Endpoint-encrypted snapshots include verified daemon identity, host name, bounded task/title/current raw request metadata and actual available usage. Original supported question/approval forms are included only within strict bounds, to answer that exact request. No complete chat/history, code files, model keys or official Paseo passwords/local credentials are uploaded. The relay cannot decrypt or manufacture accepted commands. This is not forward secrecy.
@@ -70,5 +117,5 @@ Default CLI state uses `LOCALAPPDATA/MoRemoteCLI` on Windows, `~/Library/Applica
70
117
 
71
118
  [Docs](docs/README.md) · [Contributing](CONTRIBUTING.md) · [License](LICENSE) · [Notices](NOTICE)
72
119
 
73
- Public release prerequisites, OIDC trust setup and exact verification commands:
120
+ Public release prerequisites, existing-secret setup and exact verification commands:
74
121
  [releasing](docs/releasing.md). Checked-in workflows are not proof of a published package.
@@ -0,0 +1,77 @@
1
+ import { type Envelope } from './crypto.js';
2
+ import type { Pair } from './config.js';
3
+ import { type CloudClient } from './cloud-client.js';
4
+ export interface ActivityTask {
5
+ agentId: string;
6
+ title: string | null;
7
+ status: string;
8
+ updatedAt: string;
9
+ requiresAttention: boolean;
10
+ attentionReason: string | null;
11
+ lastUserMessageAt?: string | null;
12
+ activeTurnStartedAt?: string | null;
13
+ cwd?: string | null;
14
+ pendingRequests?: readonly {
15
+ requestId: string;
16
+ }[];
17
+ }
18
+ export interface ActivitySnapshot {
19
+ daemonServerId: string;
20
+ hostName: string;
21
+ measuredAt: number;
22
+ tasks: readonly ActivityTask[];
23
+ usage: unknown;
24
+ }
25
+ export interface ActivitySubscription {
26
+ id: string;
27
+ registrationId: string;
28
+ topic: string;
29
+ interest: Envelope;
30
+ expiresAt: number;
31
+ }
32
+ export interface ActivityState {
33
+ version: 1;
34
+ subscriptionId: string;
35
+ daemonServerId: string;
36
+ agentId: string;
37
+ title: string;
38
+ hostName: string;
39
+ phase: 'running' | 'waiting' | 'finished' | 'error' | 'idle';
40
+ startedAt: number | null;
41
+ measuredAt: number;
42
+ expiresAt: number;
43
+ requiresAttention: boolean;
44
+ isTerminal: boolean;
45
+ }
46
+ type ActivityCloud = Pick<CloudClient, 'activities' | 'activityState'>;
47
+ export interface ActivityPassOptions {
48
+ signal?: AbortSignal;
49
+ terminalOnly?: boolean;
50
+ }
51
+ /** Do not make absence from a bounded recent-task list a terminal event. */
52
+ export declare function taskActivityState(snapshot: ActivitySnapshot, task: ActivityTask, subscriptionId: string, expiresAt: number): ActivityState;
53
+ /** Keyed opaque equality token; no raw task, usage, or title enters cloud metadata. */
54
+ export declare function widgetFingerprint(pair: Pick<Pair, 'pairId' | 'rootKey'>, snapshot: ActivitySnapshot): Promise<string>;
55
+ export declare function openActivityInterest(pair: Pick<Pair, 'pairId' | 'rootKey'>, value: unknown, daemonServerId: string, now: number): Promise<ActivitySubscription & {
56
+ agentId: string;
57
+ }>;
58
+ /** One bounded pass on the existing snapshot cadence. Never sends official mutations.
59
+ * Lost acknowledgements retry the same ciphertext; no alert/presence precondition.
60
+ */
61
+ export declare class ActivityPublisher {
62
+ private pairs;
63
+ retain(pairIds: readonly string[]): void;
64
+ publish(pair: Pair, cloud: ActivityCloud, snapshot: ActivitySnapshot, now?: number, readTask?: (agentId: string, signal?: AbortSignal) => Promise<ActivityTask | null>, options?: ActivityPassOptions): Promise<void>;
65
+ }
66
+ /** One owned optional lane, independent of the critical command/control loop.
67
+ * Network requests receive cancellation; SDK fallback reads have a 250ms timeout.
68
+ * close joins the real work rather than abandoning a raced promise.
69
+ */
70
+ export declare class ActivityWorkLane {
71
+ private running;
72
+ private controller;
73
+ private closed;
74
+ start(work: (signal: AbortSignal) => Promise<void>, onError: (error: unknown) => void, parentSignal?: AbortSignal): boolean;
75
+ close(): Promise<void>;
76
+ }
77
+ export {};
@@ -0,0 +1,193 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { decode, openEnvelope, presenceTopic, sealEnvelope, validateEnvelope } from './crypto.js';
3
+ import { exact, LIMITS, object, text, UUID } from './limits.js';
4
+ import { CloudError } from './cloud-client.js';
5
+ /** Do not make absence from a bounded recent-task list a terminal event. */
6
+ export function taskActivityState(snapshot, task, subscriptionId, expiresAt) {
7
+ let phase = 'idle';
8
+ // A running turn supersedes an old attention flag retained by the daemon.
9
+ if (task.status === 'error')
10
+ phase = 'error';
11
+ else if (task.status === 'closed')
12
+ phase = 'finished';
13
+ else if (task.requiresAttention && task.attentionReason === 'permission')
14
+ phase = 'waiting';
15
+ else if (task.status === 'running' || task.status === 'initializing')
16
+ phase = 'running';
17
+ else if (task.requiresAttention && task.attentionReason === 'error')
18
+ phase = 'error';
19
+ else if (task.requiresAttention && task.attentionReason === 'finished')
20
+ phase = 'finished';
21
+ const candidate = Date.parse(task.activeTurnStartedAt || task.lastUserMessageAt || '');
22
+ const startedAt = Number.isSafeInteger(candidate) && candidate >= 0 && candidate <= snapshot.measuredAt ? candidate : null;
23
+ return { version: 1, subscriptionId, daemonServerId: snapshot.daemonServerId, agentId: task.agentId,
24
+ title: (task.title || '').slice(0, 160), hostName: snapshot.hostName.slice(0, 80), phase, startedAt,
25
+ measuredAt: snapshot.measuredAt, expiresAt, requiresAttention: task.requiresAttention, isTerminal: phase === 'finished' || phase === 'error' };
26
+ }
27
+ function semanticState(state) { const { measuredAt, expiresAt, ...semantic } = state; return JSON.stringify(semantic); }
28
+ function usageValues(value) {
29
+ if (Array.isArray(value))
30
+ return value.map(usageValues);
31
+ if (value && typeof value === 'object')
32
+ return Object.fromEntries(Object.entries(value).filter(([key]) => key !== 'fetchedAt').map(([key, item]) => [key, usageValues(item)]));
33
+ return value;
34
+ }
35
+ /** Keyed opaque equality token; no raw task, usage, or title enters cloud metadata. */
36
+ export async function widgetFingerprint(pair, snapshot) {
37
+ const tasks = snapshot.tasks.map(task => ({ agentId: task.agentId, title: task.title, status: task.status,
38
+ requiresAttention: task.requiresAttention, attentionReason: task.attentionReason,
39
+ lastUserMessageAt: task.lastUserMessageAt ?? null, activeTurnStartedAt: task.activeTurnStartedAt ?? null,
40
+ cwd: task.cwd ?? null, pendingRequestIds: task.pendingRequests?.map(p => p.requestId).sort() ?? [] })).sort((a, b) => a.agentId.localeCompare(b.agentId));
41
+ return presenceTopic(decode(pair.rootKey, 32), pair.pairId, JSON.stringify(['widgetSnapshot', { daemonServerId: snapshot.daemonServerId, hostName: snapshot.hostName, tasks, usage: usageValues(snapshot.usage) }]));
42
+ }
43
+ export async function openActivityInterest(pair, value, daemonServerId, now) {
44
+ const row = object(value);
45
+ exact(row, ['id', 'registrationId', 'topic', 'interest', 'expiresAt']);
46
+ if (Object.keys(row).length !== 5 || typeof row.id !== 'string' || !UUID.test(row.id) || typeof row.registrationId !== 'string' || !UUID.test(row.registrationId) || typeof row.topic !== 'string' || !Number.isSafeInteger(row.expiresAt))
47
+ throw Error('INVALID_ACTIVITY_SUBSCRIPTION');
48
+ decode(row.topic, 32);
49
+ const interest = validateEnvelope(row.interest, now);
50
+ if (interest.pairId !== pair.pairId || interest.id !== row.id || interest.channel !== 'activityInterest' || row.expiresAt !== interest.expiresAt)
51
+ throw Error('ACTIVITY_INTEREST_CONTEXT');
52
+ const plain = object(await openEnvelope(decode(pair.rootKey, 32), interest, now));
53
+ exact(plain, ['version', 'subscriptionId', 'daemonServerId', 'agentId']);
54
+ if (Object.keys(plain).length !== 4 || plain.version !== 1 || plain.subscriptionId !== row.id || plain.daemonServerId !== daemonServerId)
55
+ throw Error('ACTIVITY_INTEREST_CONTEXT');
56
+ const agentId = text(plain.agentId, 256);
57
+ if (await presenceTopic(decode(pair.rootKey, 32), pair.pairId, agentId) !== row.topic)
58
+ throw Error('ACTIVITY_TOPIC_MISMATCH');
59
+ return { id: row.id, registrationId: row.registrationId, topic: row.topic, interest, expiresAt: interest.expiresAt, agentId };
60
+ }
61
+ /** One bounded pass on the existing snapshot cadence. Never sends official mutations.
62
+ * Lost acknowledgements retry the same ciphertext; no alert/presence precondition.
63
+ */
64
+ export class ActivityPublisher {
65
+ pairs = new Map();
66
+ retain(pairIds) { const retained = new Set(pairIds); for (const id of this.pairs.keys())
67
+ if (!retained.has(id))
68
+ this.pairs.delete(id); }
69
+ async publish(pair, cloud, snapshot, now = Date.now(), readTask, options = {}) {
70
+ const context = JSON.stringify([snapshot.daemonServerId, pair.rootKey]);
71
+ let state = this.pairs.get(pair.pairId);
72
+ if (!state || state.context !== context) {
73
+ state = { lastPoll: -Infinity, lastTerminalMeasurement: -Infinity, context, cursor: 0, subscriptions: [], publications: new Map() };
74
+ this.pairs.set(pair.pairId, state);
75
+ }
76
+ const current = () => { options.signal?.throwIfAborted(); if (this.pairs.get(pair.pairId) !== state)
77
+ throw Error('ACTIVITY_PAIR_RETIRED'); };
78
+ current();
79
+ if (options.terminalOnly) {
80
+ if (state.lastTerminalMeasurement >= snapshot.measuredAt)
81
+ return;
82
+ state.lastTerminalMeasurement = snapshot.measuredAt;
83
+ }
84
+ if (!options.terminalOnly) {
85
+ if (now - state.lastPoll < 30000)
86
+ return;
87
+ state.lastPoll = now;
88
+ const rows = await cloud.activities(options.signal);
89
+ current();
90
+ if (rows.length > 8)
91
+ throw Error('ACTIVITY_SUBSCRIPTION_LIMIT');
92
+ const subscriptions = [];
93
+ for (const row of rows) {
94
+ try {
95
+ subscriptions.push(await openActivityInterest(pair, row, snapshot.daemonServerId, now));
96
+ }
97
+ catch { /* Unauthenticated read-only interests never become authority. */ }
98
+ current();
99
+ }
100
+ state.subscriptions = subscriptions;
101
+ }
102
+ const subscriptions = state.subscriptions.filter(row => row.expiresAt > now);
103
+ const ids = new Set(subscriptions.map(row => row.id));
104
+ for (const id of state.publications.keys())
105
+ if (!ids.has(id))
106
+ state.publications.delete(id);
107
+ let failure;
108
+ const ordered = [...subscriptions.slice(state.cursor), ...subscriptions.slice(0, state.cursor)];
109
+ for (const subscription of ordered) {
110
+ try {
111
+ current();
112
+ state.cursor = (subscriptions.indexOf(subscription) + 1) % Math.max(1, subscriptions.length);
113
+ let publication = state.publications.get(subscription.id);
114
+ if (publication && (publication.body.registrationId !== subscription.registrationId || !publication.acknowledged && publication.body.envelope.expiresAt <= now))
115
+ publication = undefined;
116
+ let task = snapshot.tasks.find(task => task.agentId === subscription.agentId);
117
+ // Terminal recovery uses only cached authenticated interests and fresh source
118
+ // facts. Normal discovery/fallback work cannot consume its reserved path.
119
+ if (!task && readTask && !options.terminalOnly)
120
+ task = await readTask(subscription.agentId, options.signal) ?? undefined;
121
+ current();
122
+ if (!task || task.agentId !== subscription.agentId)
123
+ continue;
124
+ const expiresAt = Math.min(snapshot.measuredAt + LIMITS.snapshotMs, subscription.expiresAt);
125
+ if (expiresAt <= now)
126
+ continue;
127
+ const payload = taskActivityState(snapshot, task, subscription.id, expiresAt), fingerprint = semanticState(payload);
128
+ if (options.terminalOnly && !payload.isTerminal)
129
+ continue;
130
+ const renew = publication?.acknowledged && !payload.isTerminal && publication.body.envelope.expiresAt - now <= 120000 && snapshot.measuredAt > publication.body.envelope.issuedAt;
131
+ if (publication?.fingerprint === fingerprint && publication.acknowledged && !renew)
132
+ continue;
133
+ // Unknown admissions preserve immutable bytes. Fresh acknowledged running
134
+ // state renews at most once per eight minutes, before the ten-minute expiry.
135
+ if (!publication || publication.fingerprint !== fingerprint || renew) {
136
+ const envelope = await sealEnvelope(decode(pair.rootKey, 32), { version: 1, pairId: pair.pairId, id: randomUUID(), channel: 'activityState', issuedAt: snapshot.measuredAt, expiresAt }, payload);
137
+ current();
138
+ if (Buffer.byteLength(JSON.stringify(envelope)) > 3000)
139
+ throw Error('ACTIVITY_PAYLOAD_LIMIT');
140
+ publication = { fingerprint, body: { registrationId: subscription.registrationId, topic: subscription.topic, event: payload.isTerminal ? 'end' : 'update', envelope }, acknowledged: false };
141
+ state.publications.set(subscription.id, publication);
142
+ }
143
+ current();
144
+ if (!publication.acknowledged) {
145
+ await cloud.activityState(subscription.id, publication.body, options.signal);
146
+ current();
147
+ publication.acknowledged = true;
148
+ }
149
+ }
150
+ catch (error) {
151
+ if (options.signal?.aborted)
152
+ throw error;
153
+ // An authenticated rejection invalidates this cached target, not a new
154
+ // registration. Do not repeatedly consume recovery on a retired interest.
155
+ if (error instanceof CloudError && [404, 409].includes(error.status)) {
156
+ state.subscriptions = state.subscriptions.filter(row => row.id !== subscription.id);
157
+ state.publications.delete(subscription.id);
158
+ }
159
+ failure ??= error;
160
+ }
161
+ }
162
+ if (failure)
163
+ throw failure;
164
+ }
165
+ }
166
+ /** One owned optional lane, independent of the critical command/control loop.
167
+ * Network requests receive cancellation; SDK fallback reads have a 250ms timeout.
168
+ * close joins the real work rather than abandoning a raced promise.
169
+ */
170
+ export class ActivityWorkLane {
171
+ running;
172
+ controller;
173
+ closed = false;
174
+ start(work, onError, parentSignal) {
175
+ if (this.closed || this.running || parentSignal?.aborted)
176
+ return false;
177
+ const controller = new AbortController();
178
+ this.controller = controller;
179
+ const signal = AbortSignal.any([controller.signal, ...(parentSignal ? [parentSignal] : [])]);
180
+ const timer = setTimeout(() => controller.abort(Error('ACTIVITY_PASS_DEADLINE')), 2000);
181
+ timer.unref();
182
+ this.running = Promise.resolve().then(() => work(signal)).catch(error => { if (!signal.aborted)
183
+ onError(error); }).finally(() => {
184
+ clearTimeout(timer);
185
+ if (this.controller === controller) {
186
+ this.running = undefined;
187
+ this.controller = undefined;
188
+ }
189
+ });
190
+ return true;
191
+ }
192
+ async close() { this.closed = true; this.controller?.abort(Error('ACTIVITY_LANE_CLOSED')); await this.running; }
193
+ }
package/dist/cli.js CHANGED
@@ -12,8 +12,7 @@ import { runRuntime } from './runtime.js';
12
12
  import { requestControl } from './control.js';
13
13
  import { currentDefinition, installService, removeService, stopService, serviceStatus } from './service.js';
14
14
  import { ensureManaged, packageManaged, packageVersion, queueUpdate, setAutoUpdate, readUpdateState, serviceEntry } from './updater.js';
15
- import { runSupervisor } from './supervisor.js';
16
- import { requestSupervisorStop, supervisorRunning } from './update-state.js';
15
+ import { runSupervisor, stopManagedRuntime } from './supervisor.js';
17
16
  import { OperationJournal } from './journal.js';
18
17
  const VERSION = await packageVersion();
19
18
  const HELP = `MoRemote CLI ${VERSION} — optional Paseo 0.15.3 enhancement
@@ -48,20 +47,7 @@ const args = parsed.values;
48
47
  const action = parsed.positionals[0];
49
48
  async function stopped(dir) { if (await requestControl(dir, 'status'))
50
49
  throw Error('STOP_CLI_BEFORE_CONFIGURATION'); }
51
- async function stopRuntime(dir) { if (!await requestControl(dir, 'stop'))
52
- return; for (let i = 0; i < 300; i++) {
53
- await sleep(200);
54
- if (!await requestControl(dir, 'status'))
55
- return;
56
- } throw Error('STOP_TIMEOUT'); }
57
- async function stopManaged(dir) { requestSupervisorStop(dir); await stopRuntime(dir); if (readUpdateState(dir))
58
- for (let i = 0; i < 900; i++) {
59
- if (!supervisorRunning(dir))
60
- return;
61
- await sleep(200);
62
- } if (readUpdateState(dir) && supervisorRunning(dir))
63
- throw Error('SUPERVISOR_STOP_TIMEOUT'); }
64
- async function stopOwned(dir, definition) { await stopService(definition); await stopManaged(dir); }
50
+ async function stopOwned(dir, definition) { await stopService(definition); await stopManagedRuntime(dir); }
65
51
  async function main() {
66
52
  if (args.help || !action) {
67
53
  console.log(HELP);
@@ -290,7 +276,7 @@ async function main() {
290
276
  throw error;
291
277
  }
292
278
  await removeService(definition);
293
- await stopManaged(dir);
279
+ await stopManagedRuntime(dir);
294
280
  if (!args.purge)
295
281
  await saveConfig(dir, config);
296
282
  await rm(join(dir, 'managed'), { recursive: true, force: true });
@@ -3,11 +3,13 @@ import type { ReceiptState } from './journal.js';
3
3
  export declare class CloudError extends Error {
4
4
  readonly status: number;
5
5
  readonly retryAt?: number | undefined;
6
+ readonly pauseScope: 'origin' | 'normal';
6
7
  readonly code: string;
7
- constructor(code: string, status: number, retryAt?: number | undefined);
8
+ constructor(code: string, status: number, retryAt?: number | undefined, pauseScope?: 'origin' | 'normal');
8
9
  }
9
10
  export interface CloudRetryState {
10
11
  error?: CloudError;
12
+ normalError?: CloudError;
11
13
  }
12
14
  export declare class CloudClient {
13
15
  readonly pairId: string;
@@ -18,7 +20,7 @@ export declare class CloudClient {
18
20
  private cycleFence?;
19
21
  readonly origin: string;
20
22
  constructor(origin: string, pairId: string, token: string, allowLoopback?: boolean, fetcher?: typeof fetch, signal?: AbortSignal | undefined, retryState?: CloudRetryState, cycleFence?: CloudRetryState | undefined);
21
- request(method: string, path: string, body?: unknown): Promise<Record<string, unknown>>;
23
+ request(method: string, path: string, body?: unknown, signal?: AbortSignal): Promise<Record<string, unknown>>;
22
24
  private path;
23
25
  create(body: unknown): Promise<Record<string, unknown>>;
24
26
  pair(): Promise<Record<string, unknown>>;
@@ -33,11 +35,18 @@ export declare class CloudClient {
33
35
  revision: number;
34
36
  envelope: Envelope;
35
37
  }): Promise<Record<string, unknown>>;
36
- state(envelope: Envelope): Promise<Record<string, unknown>>;
38
+ state(envelope: Envelope, widgetFingerprint?: string): Promise<Record<string, unknown>>;
37
39
  attention(body: unknown): Promise<Record<string, unknown>>;
38
40
  controls(): Promise<Envelope[]>;
39
41
  controlReceipt(id: string, body: {
40
42
  envelope: Envelope;
41
43
  }): Promise<Record<string, unknown>>;
42
44
  resolveAttention(id: string, resolvedAt: number): Promise<Record<string, unknown>>;
45
+ activities(signal?: AbortSignal): Promise<unknown[]>;
46
+ activityState(id: string, body: {
47
+ registrationId: string;
48
+ topic: string;
49
+ event: 'update' | 'end';
50
+ envelope: Envelope;
51
+ }, signal?: AbortSignal): Promise<Record<string, unknown>>;
43
52
  }
@@ -3,12 +3,14 @@ import { LIMITS, object } from './limits.js';
3
3
  export class CloudError extends Error {
4
4
  status;
5
5
  retryAt;
6
+ pauseScope;
6
7
  code;
7
- constructor(code, status, retryAt) {
8
+ constructor(code, status, retryAt, pauseScope = 'origin') {
8
9
  const safe = /^[A-Z0-9_]{1,64}$/.test(code) ? code : 'CLOUD_HTTP_ERROR';
9
10
  super(safe);
10
11
  this.status = status;
11
12
  this.retryAt = retryAt;
13
+ this.pauseScope = pauseScope;
12
14
  this.code = safe;
13
15
  }
14
16
  }
@@ -31,6 +33,20 @@ function retryDeadline(value, status, now) {
31
33
  return;
32
34
  return Math.min(date, now + maxDelay);
33
35
  }
36
+ function recoveryRequest(method, path) {
37
+ const parts = path.split('/').filter(Boolean), suffix = parts.slice(2);
38
+ if (parts[0] !== 'pairs')
39
+ return false;
40
+ if (method === 'DELETE' && !suffix.length)
41
+ return true;
42
+ if (suffix[0] === 'controls')
43
+ return suffix.length === 1 && ['GET', 'POST'].includes(method) || suffix.length === 2 && method === 'GET' || suffix.length === 3 && suffix[2] === 'receipt' && method === 'POST';
44
+ if (suffix[0] === 'commands')
45
+ return suffix.length === 2 && method === 'GET' || suffix.length === 3 && suffix[2] === 'receipt' && method === 'POST';
46
+ return suffix[0] === 'attention' && suffix.length === 3 && suffix[2] === 'resolve' && method === 'POST'
47
+ || suffix[0] === 'activities' && (suffix.length === 2 && method === 'DELETE' || suffix.length === 3 && suffix[2] === 'end' && method === 'PUT')
48
+ || suffix[0] === 'widget-device' && suffix.length === 2 && method === 'DELETE';
49
+ }
34
50
  export class CloudClient {
35
51
  pairId;
36
52
  token;
@@ -48,9 +64,10 @@ export class CloudClient {
48
64
  this.cycleFence = cycleFence;
49
65
  this.origin = validateOrigin(origin, allowLoopback);
50
66
  }
51
- async request(method, path, body) {
67
+ async request(method, path, body, signal) {
52
68
  // A runtime cycle that observed a pause must reacquire controls in a new
53
69
  // cycle, even if an intervening SDK call outlasted the wall-clock deadline.
70
+ signal?.throwIfAborted();
54
71
  if (this.cycleFence?.error)
55
72
  throw this.cycleFence.error;
56
73
  const paused = this.retryState.error;
@@ -60,17 +77,22 @@ export class CloudClient {
60
77
  throw paused;
61
78
  }
62
79
  this.retryState.error = undefined;
80
+ if (!recoveryRequest(method, path)) {
81
+ if (this.cycleFence?.normalError)
82
+ throw this.cycleFence.normalError;
83
+ const normal = this.retryState.normalError;
84
+ if (normal?.retryAt !== undefined && normal.retryAt > Date.now()) {
85
+ if (this.cycleFence)
86
+ this.cycleFence.normalError = normal;
87
+ throw normal;
88
+ }
89
+ this.retryState.normalError = undefined;
90
+ }
63
91
  const json = body === undefined ? undefined : JSON.stringify(body);
64
92
  if (json && Buffer.byteLength(json) > LIMITS.envelopeBytes)
65
93
  throw Error('REQUEST_LIMIT');
66
- const response = await this.fetcher(this.origin + '/v1' + path, { method, headers: { authorization: 'Bearer ' + this.token, ...(json ? { 'content-type': 'application/json' } : {}) }, body: json, signal: AbortSignal.any([AbortSignal.timeout(20000), ...(this.signal ? [this.signal] : [])]), redirect: 'error' });
94
+ const response = await this.fetcher(this.origin + '/v1' + path, { method, headers: { authorization: 'Bearer ' + this.token, ...(json ? { 'content-type': 'application/json' } : {}) }, body: json, signal: AbortSignal.any([AbortSignal.timeout(20000), ...(this.signal ? [this.signal] : []), ...(signal ? [signal] : [])]), redirect: 'error' });
67
95
  const retryAt = retryDeadline(response.headers.get('Retry-After'), response.status, Date.now());
68
- if (retryAt !== undefined) {
69
- const failure = new CloudError('CLOUD_HTTP_ERROR', response.status, retryAt);
70
- this.retryState.error = failure;
71
- if (this.cycleFence)
72
- this.cycleFence.error = failure;
73
- }
74
96
  const reader = response.body?.getReader();
75
97
  let size = 0;
76
98
  const chunks = [];
@@ -86,6 +108,15 @@ export class CloudClient {
86
108
  chunks.push(r.value);
87
109
  }
88
110
  }
111
+ catch (error) {
112
+ if (retryAt !== undefined) {
113
+ const failure = new CloudError('CLOUD_HTTP_ERROR', response.status, retryAt);
114
+ this.retryState.error = failure;
115
+ if (this.cycleFence)
116
+ this.cycleFence.error = failure;
117
+ }
118
+ throw error;
119
+ }
89
120
  finally {
90
121
  await reader.cancel();
91
122
  }
@@ -95,15 +126,26 @@ export class CloudClient {
95
126
  result = object(JSON.parse(Buffer.concat(chunks).toString('utf8')));
96
127
  }
97
128
  catch {
129
+ if (retryAt !== undefined) {
130
+ const failure = new CloudError('CLOUD_HTTP_ERROR', response.status, retryAt);
131
+ this.retryState.error = failure;
132
+ if (this.cycleFence)
133
+ this.cycleFence.error = failure;
134
+ }
98
135
  throw Error('INVALID_CLOUD_RESPONSE');
99
136
  }
100
137
  if (!response.ok || result.ok !== true) {
101
- const error = result.error && typeof result.error === 'object' ? result.error : {};
102
- const failure = new CloudError(typeof error.code === 'string' ? error.code : 'CLOUD_HTTP_ERROR', response.status, retryAt);
138
+ const error = result.error && typeof result.error === 'object' ? result.error : {}, resetHeader = response.headers.get('x-moremote-reset'), reset = Number(resetHeader);
139
+ // Only an explicit, internally consistent daily normal-quota rejection can
140
+ // leave recovery open. Missing/malformed hints and outages remain origin-wide.
141
+ const normalOnly = response.status === 429 && error.code === 'daily_work_limit' && response.headers.get('x-moremote-budget') === 'normal'
142
+ && retryAt !== undefined && resetHeader !== null && /^\d{1,16}$/.test(resetHeader) && Number.isSafeInteger(reset) && reset > Date.now() && Math.abs(reset - retryAt) <= 1000;
143
+ const failure = new CloudError(typeof error.code === 'string' ? error.code : 'CLOUD_HTTP_ERROR', response.status, retryAt, normalOnly ? 'normal' : 'origin');
103
144
  if (retryAt !== undefined) {
104
- this.retryState.error = failure;
145
+ const field = normalOnly ? 'normalError' : 'error';
146
+ this.retryState[field] = failure;
105
147
  if (this.cycleFence)
106
- this.cycleFence.error = failure;
148
+ this.cycleFence[field] = failure;
107
149
  }
108
150
  throw failure;
109
151
  }
@@ -119,10 +161,13 @@ export class CloudClient {
119
161
  async dispatch(id) { const r = await this.request('POST', this.path('/commands/' + id + '/dispatch'), {}); if (typeof r.dispatchAllowed !== 'boolean')
120
162
  throw Error('INVALID_DISPATCH_RESPONSE'); return { dispatchAllowed: r.dispatchAllowed }; }
121
163
  receipt(id, body) { return this.request('POST', this.path('/commands/' + id + '/receipt'), body); }
122
- state(envelope) { return this.request('PUT', this.path('/state'), { envelope }); }
164
+ state(envelope, widgetFingerprint) { return this.request('PUT', this.path('/state'), { envelope, ...(widgetFingerprint ? { widgetFingerprint } : {}) }); }
123
165
  attention(body) { return this.request('POST', this.path('/attention'), body); }
124
166
  async controls() { const result = await this.request('GET', this.path('/controls')); if (!Array.isArray(result.controls) || result.controls.length > 100)
125
167
  throw Error('INVALID_CONTROL_PAGE'); return result.controls.map(row => object(row).envelope).filter(Boolean); }
126
168
  controlReceipt(id, body) { return this.request('POST', this.path('/controls/' + id + '/receipt'), body); }
127
169
  resolveAttention(id, resolvedAt) { return this.request('POST', this.path('/attention/' + id + '/resolve'), { resolvedAt }); }
170
+ async activities(signal) { const result = await this.request('GET', this.path('/activities'), undefined, signal); if (!Array.isArray(result.subscriptions) || result.subscriptions.length > 8)
171
+ throw Error('INVALID_ACTIVITY_PAGE'); return result.subscriptions; }
172
+ activityState(id, body, signal) { return this.request('PUT', this.path('/activities/' + id + (body.event === 'end' ? '/end' : '/state')), body, signal); }
128
173
  }
@@ -0,0 +1,4 @@
1
+ import { type ResourceIdentity, type RuntimeOwner } from './resources.js';
2
+ export declare function controlFraming(dir: string, owner: RuntimeOwner): 'legacy-eof' | 'json-lines-v1';
3
+ export declare function publishControlTransport(dir: string, owner: RuntimeOwner): Promise<ResourceIdentity>;
4
+ export declare function removeControlTransport(dir: string, identity: ResourceIdentity, owner: RuntimeOwner): boolean;
@@ -0,0 +1,68 @@
1
+ import { join } from 'node:path';
2
+ import { openSync, closeSync, fsyncSync, renameSync } from 'node:fs';
3
+ import { createHash, randomUUID } from 'node:crypto';
4
+ import { privateManagedDirectory } from './config.js';
5
+ import { managedRoot } from './update-state.js';
6
+ import { inspectResource, readPrivateText, createPrivateFile, removeOwnedResource, sameResource } from './resources.js';
7
+ const OWNER = 'MoRemote CLI control transport';
8
+ function readDescriptor(dir) {
9
+ if (!inspectResource(join(dir, 'managed'), 'directory', true))
10
+ return null;
11
+ const root = managedRoot(dir), path = join(root, 'runtime-transport.json');
12
+ if (!inspectResource(path, 'file', true))
13
+ return null;
14
+ const file = readPrivateText(path, 2048);
15
+ let value;
16
+ try {
17
+ value = JSON.parse(file.text);
18
+ }
19
+ catch {
20
+ throw Error('INVALID_CONTROL_TRANSPORT');
21
+ }
22
+ if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).length !== 7 || value.owner !== OWNER || value.version !== 1 || value.framing !== 'json-lines-v1' || typeof value.instanceId !== 'string' || !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value.instanceId) || !Number.isSafeInteger(value.pid) || value.pid < 1 || value.pid > 2147483647 || !Number.isSafeInteger(value.startedAt) || value.startedAt < 1 || typeof value.tokenHash !== 'string' || !/^[0-9a-f]{64}$/.test(value.tokenHash))
23
+ throw Error('INVALID_CONTROL_TRANSPORT');
24
+ return { ...file, value };
25
+ }
26
+ function matches(value, owner) { return value.instanceId === owner.instanceId && value.pid === owner.pid && value.startedAt === owner.startedAt && value.tokenHash === createHash('sha256').update(owner.token).digest('hex'); }
27
+ export function controlFraming(dir, owner) {
28
+ const descriptor = readDescriptor(dir);
29
+ return descriptor && matches(descriptor.value, owner) ? 'json-lines-v1' : 'legacy-eof';
30
+ }
31
+ export async function publishControlTransport(dir, owner) {
32
+ // Nested managed resources are understood/ignored by the published 0.1.0
33
+ // root reader; its exact six/seven-key runtime lock/record stays unchanged.
34
+ await privateManagedDirectory(join(dir, 'managed'));
35
+ const root = managedRoot(dir), path = join(root, 'runtime-transport.json'), before = readDescriptor(dir);
36
+ const value = { owner: OWNER, version: 1, framing: 'json-lines-v1', instanceId: owner.instanceId, pid: owner.pid, startedAt: owner.startedAt, tokenHash: createHash('sha256').update(owner.token).digest('hex') };
37
+ const temp = path + '.' + randomUUID() + '.tmp', identity = createPrivateFile(temp, JSON.stringify(value) + '\n');
38
+ try {
39
+ const current = readDescriptor(dir);
40
+ if (before ? (!current || !sameResource(before.identity, current.identity) || before.text !== current.text) : current !== null)
41
+ throw Error('CONTROL_TRANSPORT_CHANGED');
42
+ renameSync(temp, path);
43
+ if (process.platform !== 'win32') {
44
+ const fd = openSync(root, 'r');
45
+ try {
46
+ fsyncSync(fd);
47
+ }
48
+ finally {
49
+ closeSync(fd);
50
+ }
51
+ }
52
+ return identity;
53
+ }
54
+ finally {
55
+ removeOwnedResource(temp, identity);
56
+ }
57
+ }
58
+ export function removeControlTransport(dir, identity, owner) {
59
+ try {
60
+ const current = readDescriptor(dir);
61
+ if (!current || !sameResource(current.identity, identity) || !matches(current.value, owner))
62
+ return false;
63
+ return removeOwnedResource(join(managedRoot(dir), 'runtime-transport.json'), identity);
64
+ }
65
+ catch {
66
+ return false;
67
+ }
68
+ }
package/dist/control.d.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  export declare function controlEndpoint(dir: string): string;
2
+ export declare function runtimeHasLiveOwner(dir: string): boolean;
2
3
  export declare function requestControl(dir: string, action: 'status' | 'stop'): Promise<Record<string, unknown> | null>;
3
4
  export declare function ownRuntime(dir: string, status: () => unknown, stop: () => void): Promise<() => Promise<void>>;