@moxuli/moremote 0.1.1 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +85 -7
  2. package/bin/moremote-cli.js +11 -4
  3. package/dist/activity.d.ts +79 -0
  4. package/dist/activity.js +193 -0
  5. package/dist/cli.js +36 -41
  6. package/dist/cloud-client.d.ts +13 -4
  7. package/dist/cloud-client.js +60 -15
  8. package/dist/config.d.ts +7 -0
  9. package/dist/config.js +23 -4
  10. package/dist/control.d.ts +1 -0
  11. package/dist/control.js +9 -0
  12. package/dist/crypto.d.ts +1 -1
  13. package/dist/crypto.js +2 -2
  14. package/dist/enrollment-files.d.ts +37 -0
  15. package/dist/enrollment-files.js +225 -0
  16. package/dist/enrollment-protocol.d.ts +50 -0
  17. package/dist/enrollment-protocol.js +44 -0
  18. package/dist/journal.js +2 -1
  19. package/dist/local-enrollment.d.ts +25 -0
  20. package/dist/local-enrollment.js +160 -0
  21. package/dist/official-client.d.ts +87 -6
  22. package/dist/official-client.js +135 -32
  23. package/dist/operations.d.ts +1 -0
  24. package/dist/operations.js +24 -4
  25. package/dist/projection.d.ts +7 -2
  26. package/dist/resources.d.ts +2 -1
  27. package/dist/resources.js +69 -32
  28. package/dist/runtime.d.ts +10 -1
  29. package/dist/runtime.js +111 -10
  30. package/dist/service.js +43 -8
  31. package/dist/setup-upgrade.d.ts +2 -0
  32. package/dist/setup-upgrade.js +65 -0
  33. package/dist/setup.d.ts +12 -0
  34. package/dist/setup.js +38 -0
  35. package/dist/supervisor.d.ts +1 -0
  36. package/dist/supervisor.js +44 -1
  37. package/docs/README.md +4 -3
  38. package/docs/STATE.md +327 -10
  39. package/docs/configuration.md +119 -5
  40. package/docs/plans/2026-11-11-native-service-acceptance.md +168 -0
  41. package/docs/specs/03-api-contract.md +122 -2
  42. package/docs/specs/04-control-and-receipt-lifecycle.md +12 -0
  43. package/docs/specs/05-endpoint-and-lifecycle.md +126 -2
  44. package/docs/specs/06-managed-updates.md +34 -1
  45. package/package.json +2 -2
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.2**); 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
@@ -21,7 +21,7 @@ alone stays manual. No command starts/upgrades the official daemon.
21
21
 
22
22
  ## Build and foreground use
23
23
 
24
- Requires Node **24.13.0 or later on Node 24** and npm. No installer scripts or service registration run during setup.
24
+ Requires Node **24.13.0 or later on Node 24** and npm. Dependency installation and builds do not register a service; only explicit lifecycle commands do.
25
25
 
26
26
  ```sh
27
27
  npm ci --ignore-scripts
@@ -34,15 +34,92 @@ 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
- For a separately operated relay:
37
+ ## Connect once through official Paseo
38
+
39
+ Single-pairing setup requires **MoRemote CLI0.1.4 or later**. Update an older
40
+ CLI before using this command. Publication and platform acceptance receipts are
41
+ recorded in `docs/STATE.md`.
42
+
43
+ With the official Paseo daemon already running:
38
44
 
39
45
  ```sh
40
- node bin/moremote-cli.js configure --api-origin https://relay.example.test --cloud-on
41
- node bin/moremote-cli.js pair
42
- node bin/moremote-cli.js run
46
+ moremote-cli setup --yes
47
+ ```
48
+
49
+ This explicit command authenticates the existing official daemon, enables cloud
50
+ and automatic local enrollment, and installs/starts only the CLI's owned per-user
51
+ background service. It preserves configured targets/custom HTTPS origins, active
52
+ and revoked phones, and existing update preferences. With no origin configured,
53
+ it selects `https://moremote-cloud-ingress.pages.dev`. It never starts, modifies
54
+ or upgrades Paseo or global tools. Source-checkout setup without managed state
55
+ binds the current source frontend and retains manual updates. Installed packages
56
+ or retained managed state require an enrollment-capable runtime: explicit setup
57
+ can install the exact current CLI version into owned private state, preserving
58
+ the automatic-update opt-out. A missing current package/capability fails clearly
59
+ before enabling enrollment, never by substituting old public code. The immutable
60
+ old package stays retained; its selected runtime/bootstrap move to capable code.
61
+
62
+ Pair the computer **only in official Paseo**. A compatible MoRemote app uses
63
+ that already authenticated connection's ordinary file channel to discover the
64
+ optional CLI and enroll its own phone automatically, even before a workspace
65
+ exists. There is no second QR, paste field, terminal, hidden workspace or relay.
66
+ Missing installation appears only in the enhancement surface. A previously
67
+ disabled/revoked phone is not silently re-enabled.
68
+
69
+ Discovery is private local state under
70
+ `<home>/.moremote-cli-connect/<sha256(daemonServerId)>/`. Descriptor origins are
71
+ pinned through that authenticated file channel; each bounded immutable request
72
+ gets its original per-phone offer and unchanged endpoint proof handshake. Secret
73
+ responses are never printed and are removed on activation/expiry. See the
74
+ [complete version-1 contract](docs/specs/05-endpoint-and-lifecycle.md#single-pairing-local-enrollment-v1-unreleased).
75
+
76
+ For an advanced custom authority, configure it before explicit setup:
77
+
78
+ ```sh
79
+ moremote-cli configure --api-origin https://relay.example.test
80
+ moremote-cli setup --yes
43
81
  ```
44
82
 
45
- `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).
83
+ Plain config loads, `check` and `status` stay passive; only `check --connect`
84
+ makes a read-only official connection. They do not enable cloud, enroll a phone,
85
+ create discovery or install a service.
86
+
87
+ ### Expert-only manual enrollment
88
+
89
+ `moremote-cli pair` remains an explicit expert tool, not the normal app flow.
90
+ It prints a **secret**, ten-minute, one-phone QR/link (`--json` prints canonical
91
+ offer JSON), enables cloud on the configured/default origin and waits for the
92
+ original encrypted claim/activation proof. Never share screenshots or log its
93
+ output. It installs no service. Existing custom origins and per-phone authority
94
+ remain unchanged. Published 0.1.2 requires explicit origin/cloud configuration
95
+ before using that legacy manual path.
96
+
97
+ ## Optional activities and widget reloads — unreleased source
98
+
99
+ Local source adds per-task encrypted Live Activity state and keyed widget-change
100
+ fingerprints. These changes are **not in published 0.1.1**; the package version
101
+ has not changed. They require a compatible native app and separately configured
102
+ relay/APNs capabilities; installing the CLI alone enables neither surface.
103
+ Cloud remains off by default.
104
+
105
+ The phone owns task selection, encrypted read-only interest and native push
106
+ tokens; the companion authenticates that interest against the pinned daemon and
107
+ publishes bounded official task measurements. Up to eight interests per pairing
108
+ expire within eight hours; activity states expire within ten minutes. Missing
109
+ tasks are not reported finished. Acknowledged ongoing state renews from fresh
110
+ measurements around every eight minutes; lost acknowledgements preserve exact
111
+ ciphertext until expiry. Commands and controls do not await the optional activity
112
+ lane. Widget reloads depend on meaningful snapshot changes, use the existing
113
+ encrypted snapshot and are opportunistic, not realtime delivery.
114
+
115
+ The relay sees opaque routing/equality tags, registration identities, tokens,
116
+ environment, envelope metadata and ciphertext—not decrypted task titles or
117
+ usage. Apple receives the token and push payload: encrypted activity content or
118
+ a generic widget-change signal. Device rendering, widget freshness/offline
119
+ behavior and APNs delivery for these new surfaces remain **pending acceptance**;
120
+ APNs HTTP 200 means provider admission only. See [operator limits and failure
121
+ semantics](docs/configuration.md#optional-activity-and-widget-surfaces-unreleased)
122
+ and the [living wire contract](docs/specs/03-api-contract.md#opt-in-task-activities-and-widget-reloads).
46
123
 
47
124
  ## What leaves the computer
48
125
 
@@ -54,6 +131,7 @@ Endpoint cancellation/revocation uses authenticated encrypted controls and durab
54
131
  ## Lifecycle and ownership
55
132
 
56
133
  - `status` and `check` are redacted. Only explicit `check --connect` contacts the selected official daemon (read-only).
134
+ - `setup --yes`: explicit automatic-enrollment/cloud opt-in plus only the owned per-user background service; no second user pairing or official changes. Existing custom authorities, phone records and update opt-out survive.
57
135
  - `service-install --yes`: explicit per-user LaunchAgent on macOS, systemd user unit on Linux, or least-privilege interactive-user **logon task** on Windows (not an administrator Windows Service). Foreground `run` needs none of these. No sudo/admin installation.
58
136
  - `stop`: stop only the owned companion registration/runtime; never signal an official process. Linux/Windows registration remains available for a future login; macOS bootout leaves its owned plist available for explicit reinstallation.
59
137
  - `unpair --pair-id <exact-id>`: revoke one phone, leaving other phones unchanged. Stop the runtime first.
@@ -1,23 +1,30 @@
1
1
  #!/usr/bin/env node
2
- import {resolve} from 'node:path';
2
+ import {resolve,join,dirname} from 'node:path';
3
3
  import {fileURLToPath} from 'node:url';
4
4
  import {spawn} from 'node:child_process';
5
- import {realpath} from 'node:fs/promises';
5
+ import {realpath,readFile} from 'node:fs/promises';
6
6
  async function main(){
7
7
  const {dataDirectory}=await import('../dist/config.js');
8
8
  const {readUpdateState}=await import('../dist/update-state.js');
9
9
  const {managedEntry}=await import('../dist/service.js');
10
10
  // Dispatch before parsing: an old global frontend must accept a newer
11
11
  // selected CLI's flags, including --version. Never overwrite that frontend.
12
- let dir=dataDirectory();const args=process.argv.slice(2);
12
+ let dir=dataDirectory(),action;const args=process.argv.slice(2);
13
13
  for(let i=0;i<args.length&&args[i]!=='--';i++){
14
14
  if(args[i]==='--data-dir'&&args[i+1])dir=args[++i];
15
15
  else if(args[i].startsWith('--data-dir='))dir=args[i].slice(11);
16
+ else if(!args[i].startsWith('-')&&action===undefined)action=args[i];
16
17
  }
17
18
  const state=readUpdateState(resolve(dir));
19
+ const currentPackage=JSON.parse(await readFile(new URL('../package.json',import.meta.url),'utf8'));
20
+ // A retained selected runtime can predate setup. The current capability-owning
21
+ // package must handle that explicit migration instead of forwarding to old code.
22
+ const currentSetup=action==='setup'&&currentPackage.moremote?.localEnrollment===1;
18
23
  if(state&&!process.env.MOREMOTE_MANAGED_CHILD){
19
24
  const entry=await managedEntry(resolve(dir),state.active);
20
- if(await realpath(entry)!==await realpath(fileURLToPath(import.meta.url))){
25
+ const selectedPackage=currentSetup?JSON.parse(await readFile(join(dirname(dirname(entry)),'package.json'),'utf8')):undefined;
26
+ const selectedSetup=selectedPackage?.moremote?.localEnrollment===1&&selectedPackage.moremote.configBytes>=currentPackage.moremote.configBytes;
27
+ if((!currentSetup||selectedSetup)&&await realpath(entry)!==await realpath(fileURLToPath(import.meta.url))){
21
28
  const child=spawn(process.execPath,[entry,...args],{stdio:['inherit','inherit','inherit','ipc'],shell:false,windowsHide:true});
22
29
  const result=Promise.withResolvers();child.once('error',result.reject);child.once('exit',code=>result.resolve(code??1));
23
30
  const ready=message=>{if(message&&typeof message==='object'&&message.kind==='moremote-ready'&&typeof message.version==='string'&&process.send&&process.connected)process.send({kind:'moremote-ready',version:message.version},undefined,undefined,()=>{})};
@@ -0,0 +1,79 @@
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
+ provider?: string;
12
+ createdAt?: string | null;
13
+ lastUserMessageAt?: string | null;
14
+ activeTurnStartedAt?: string | null;
15
+ cwd?: string | null;
16
+ pendingRequests?: readonly {
17
+ requestId: string;
18
+ }[];
19
+ }
20
+ export interface ActivitySnapshot {
21
+ daemonServerId: string;
22
+ hostName: string;
23
+ measuredAt: number;
24
+ tasks: readonly ActivityTask[];
25
+ usage: unknown;
26
+ }
27
+ export interface ActivitySubscription {
28
+ id: string;
29
+ registrationId: string;
30
+ topic: string;
31
+ interest: Envelope;
32
+ expiresAt: number;
33
+ }
34
+ export interface ActivityState {
35
+ version: 1;
36
+ subscriptionId: string;
37
+ daemonServerId: string;
38
+ agentId: string;
39
+ title: string;
40
+ hostName: string;
41
+ phase: 'running' | 'waiting' | 'finished' | 'error' | 'idle';
42
+ startedAt: number | null;
43
+ measuredAt: number;
44
+ expiresAt: number;
45
+ requiresAttention: boolean;
46
+ isTerminal: boolean;
47
+ }
48
+ type ActivityCloud = Pick<CloudClient, 'activities' | 'activityState'>;
49
+ export interface ActivityPassOptions {
50
+ signal?: AbortSignal;
51
+ terminalOnly?: boolean;
52
+ }
53
+ /** Do not make absence from a bounded recent-task list a terminal event. */
54
+ export declare function taskActivityState(snapshot: ActivitySnapshot, task: ActivityTask, subscriptionId: string, expiresAt: number): ActivityState;
55
+ /** Keyed opaque equality token; no raw task, usage, or title enters cloud metadata. */
56
+ export declare function widgetFingerprint(pair: Pick<Pair, 'pairId' | 'rootKey'>, snapshot: ActivitySnapshot): Promise<string>;
57
+ export declare function openActivityInterest(pair: Pick<Pair, 'pairId' | 'rootKey'>, value: unknown, daemonServerId: string, now: number): Promise<ActivitySubscription & {
58
+ agentId: string;
59
+ }>;
60
+ /** One bounded pass on the existing snapshot cadence. Never sends official mutations.
61
+ * Lost acknowledgements retry the same ciphertext; no alert/presence precondition.
62
+ */
63
+ export declare class ActivityPublisher {
64
+ private pairs;
65
+ retain(pairIds: readonly string[]): void;
66
+ publish(pair: Pair, cloud: ActivityCloud, snapshot: ActivitySnapshot, now?: number, readTask?: (agentId: string, signal?: AbortSignal) => Promise<ActivityTask | null>, options?: ActivityPassOptions): Promise<void>;
67
+ }
68
+ /** One owned optional lane, independent of the critical command/control loop.
69
+ * Network requests receive cancellation; SDK fallback reads have a 250ms timeout.
70
+ * close joins the real work rather than abandoning a raced promise.
71
+ */
72
+ export declare class ActivityWorkLane {
73
+ private running;
74
+ private controller;
75
+ private closed;
76
+ start(work: (signal: AbortSignal) => Promise<void>, onError: (error: unknown) => void, parentSignal?: AbortSignal): boolean;
77
+ close(): Promise<void>;
78
+ }
79
+ 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, provider: task.provider ?? null, createdAt: task.createdAt ?? null, 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
@@ -9,19 +9,21 @@ import { OfficialClient } from './official-client.js';
9
9
  import { CloudClient } from './cloud-client.js';
10
10
  import { makeOffer, tokenHash, activatePending } from './pairing.js';
11
11
  import { runRuntime } from './runtime.js';
12
- import { requestControl } from './control.js';
12
+ import { requestControl, runtimeHasLiveOwner } 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();
18
+ import { setupEnrollment } from './setup.js';
19
+ import { setupServiceEntry } from './setup-upgrade.js';
19
20
  const HELP = `MoRemote CLI ${VERSION} — optional Paseo 0.15.3 enhancement
20
21
  Usage: moremote-cli <command> [options]
22
+ setup --yes Enable automatic enrollment and own background service
21
23
  configure --target <official-target> --api-origin <https-origin> [--cloud-on]
22
24
  [--paseo-home <directory>] [--allow-loopback-http]
23
25
  check [--connect] Redacted local checks; --connect is read-only
24
- pair [--json] Display one secret phone QR/link; wait for activation
26
+ pair [--json] Expert-only private one-phone offer and activation
25
27
  run Foreground observer and scoped command consumer
26
28
  status Redacted runtime/config/owned-service/update state
27
29
  service-install --yes Explicit per-user managed CLI login registration
@@ -48,37 +50,7 @@ const args = parsed.values;
48
50
  const action = parsed.positionals[0];
49
51
  async function stopped(dir) { if (await requestControl(dir, 'status'))
50
52
  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) {
58
- requestSupervisorStop(dir);
59
- let legacyUnavailable = false;
60
- try {
61
- await stopRuntime(dir);
62
- }
63
- catch (error) {
64
- if (error instanceof Error && error.message === 'LEGACY_WINDOWS_CONTROL_UNAVAILABLE' && readUpdateState(dir))
65
- legacyUnavailable = true;
66
- else
67
- throw error;
68
- }
69
- if (readUpdateState(dir))
70
- for (let i = 0; i < 900; i++) {
71
- if (!supervisorRunning(dir)) {
72
- if (legacyUnavailable && await requestControl(dir, 'status'))
73
- throw Error('STOP_TIMEOUT');
74
- return;
75
- }
76
- await sleep(200);
77
- }
78
- if (readUpdateState(dir) && supervisorRunning(dir))
79
- throw Error('SUPERVISOR_STOP_TIMEOUT');
80
- }
81
- async function stopOwned(dir, definition) { await stopService(definition); await stopManaged(dir); }
53
+ async function stopOwned(dir, definition) { await stopService(definition); await stopManagedRuntime(dir); }
82
54
  async function main() {
83
55
  if (args.help || !action) {
84
56
  console.log(HELP);
@@ -122,7 +94,8 @@ async function main() {
122
94
  return;
123
95
  }
124
96
  if (action === 'run') {
125
- await saveConfig(dir, config);
97
+ if (runtimeHasLiveOwner(dir))
98
+ throw Error('CLI_ALREADY_RUNNING');
126
99
  if (process.env.MOREMOTE_MANAGED_CHILD) {
127
100
  try {
128
101
  await runRuntime(dir, VERSION);
@@ -152,6 +125,27 @@ async function main() {
152
125
  console.log('MoRemote CLI stopped; official Paseo unchanged.');
153
126
  return;
154
127
  }
128
+ if (action === 'setup') {
129
+ let preparedEntry;
130
+ await setupEnrollment(dir, { yes: !!args.yes, stopOwned: () => stopOwned(dir, definition), authenticate: async (current) => {
131
+ const official = new OfficialClient(current);
132
+ try {
133
+ await official.connect();
134
+ return { serverId: official.info().serverId };
135
+ }
136
+ finally {
137
+ await official.close();
138
+ }
139
+ }, prepare: async () => {
140
+ preparedEntry = await setupServiceEntry(dir, fileURLToPath(new URL('../bin/moremote-cli.js', import.meta.url)));
141
+ }, install: async () => {
142
+ if (!preparedEntry)
143
+ throw Error('SETUP_CAPABILITY_REQUIRED');
144
+ await installService(currentDefinition(preparedEntry, dir));
145
+ } });
146
+ console.log('MoRemote CLI automatic enrollment and owned per-user service enabled. Official Paseo unchanged.');
147
+ return;
148
+ }
155
149
  if (action === 'configure') {
156
150
  await stopped(dir);
157
151
  pruneRetiredPairs(config);
@@ -183,20 +177,21 @@ async function main() {
183
177
  }
184
178
  if (action === 'pair') {
185
179
  await stopped(dir);
186
- if (!config.apiOrigin || !config.cloudEnabled)
187
- throw Error('CONFIGURE_AND_OPT_IN_CLOUD_FIRST');
188
180
  if (config.pairs.length >= 16)
189
181
  throw Error('PAIRING_LIMIT');
182
+ const origin = validateOrigin(config.apiOrigin ?? 'https://moremote-cloud-ingress.pages.dev', config.allowLoopbackHttp);
190
183
  const official = new OfficialClient(config);
191
184
  try {
192
185
  await official.connect();
193
186
  const info = official.info();
187
+ config.apiOrigin = origin;
188
+ config.cloudEnabled = true;
194
189
  config.daemonServerId = info.serverId;
195
- const { pair, offer } = makeOffer(config.apiOrigin);
190
+ const { pair, offer } = makeOffer(origin);
196
191
  pair.daemonServerId = info.serverId;
197
192
  config.pairs.push(pair);
198
193
  await saveConfig(dir, config);
199
- const cloud = new CloudClient(config.apiOrigin, pair.pairId, pair.hostToken, config.allowLoopbackHttp);
194
+ const cloud = new CloudClient(origin, pair.pairId, pair.hostToken, config.allowLoopbackHttp);
200
195
  await cloud.create({ pairId: pair.pairId, hostTokenHash: tokenHash(pair.hostToken), enrollmentTokenHash: tokenHash(pair.enrollmentToken), expiresAt: pair.expiresAt });
201
196
  const offerJSON = JSON.stringify(offer);
202
197
  if (args.json)
@@ -307,7 +302,7 @@ async function main() {
307
302
  throw error;
308
303
  }
309
304
  await removeService(definition);
310
- await stopManaged(dir);
305
+ await stopManagedRuntime(dir);
311
306
  if (!args.purge)
312
307
  await saveConfig(dir, config);
313
308
  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,9 +20,9 @@ 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
- create(body: unknown): Promise<Record<string, unknown>>;
25
+ create(body: unknown, signal?: AbortSignal): Promise<Record<string, unknown>>;
24
26
  pair(): Promise<Record<string, unknown>>;
25
27
  activate(body: unknown): Promise<Record<string, unknown>>;
26
28
  revoke(): 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
  }