@moxuli/moremote 0.0.0-stage → 0.1.1

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 (67) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +31 -0
  3. package/README.md +73 -2
  4. package/bin/moremote-cli.js +34 -0
  5. package/bin/moremote-service.js +7 -0
  6. package/dist/bindings.d.ts +6 -0
  7. package/dist/bindings.js +4 -0
  8. package/dist/cli.d.ts +1 -0
  9. package/dist/cli.js +325 -0
  10. package/dist/cloud-client.d.ts +43 -0
  11. package/dist/cloud-client.js +128 -0
  12. package/dist/config.d.ts +36 -0
  13. package/dist/config.js +68 -0
  14. package/dist/control-transport.d.ts +4 -0
  15. package/dist/control-transport.js +68 -0
  16. package/dist/control.d.ts +3 -0
  17. package/dist/control.js +297 -0
  18. package/dist/controls.d.ts +15 -0
  19. package/dist/controls.js +36 -0
  20. package/dist/crypto.d.ts +23 -0
  21. package/dist/crypto.js +68 -0
  22. package/dist/evidence.d.ts +19 -0
  23. package/dist/evidence.js +4 -0
  24. package/dist/journal.d.ts +104 -0
  25. package/dist/journal.js +132 -0
  26. package/dist/limits.d.ts +21 -0
  27. package/dist/limits.js +8 -0
  28. package/dist/official-client.d.ts +120 -0
  29. package/dist/official-client.js +162 -0
  30. package/dist/operations.d.ts +71 -0
  31. package/dist/operations.js +210 -0
  32. package/dist/pairing.d.ts +19 -0
  33. package/dist/pairing.js +68 -0
  34. package/dist/permission.d.ts +9 -0
  35. package/dist/permission.js +66 -0
  36. package/dist/projection.d.ts +24 -0
  37. package/dist/projection.js +35 -0
  38. package/dist/resources.d.ts +76 -0
  39. package/dist/resources.js +299 -0
  40. package/dist/runtime.d.ts +8 -0
  41. package/dist/runtime.js +375 -0
  42. package/dist/service.d.ts +21 -0
  43. package/dist/service.js +310 -0
  44. package/dist/supervisor.d.ts +15 -0
  45. package/dist/supervisor.js +175 -0
  46. package/dist/update-state.d.ts +30 -0
  47. package/dist/update-state.js +158 -0
  48. package/dist/updater.d.ts +9 -0
  49. package/dist/updater.js +152 -0
  50. package/docs/README.md +23 -0
  51. package/docs/STATE.md +155 -0
  52. package/docs/configuration.md +37 -0
  53. package/docs/conventions.md +9 -0
  54. package/docs/decisions/0001-managed-updates.md +19 -0
  55. package/docs/plans/2026-11-10-managed-updates.md +26 -0
  56. package/docs/plans/2026-11-10-notification-delivery.md +118 -0
  57. package/docs/releasing.md +34 -0
  58. package/docs/specs/01-architecture.md +102 -0
  59. package/docs/specs/02-encrypted-delivery.md +194 -0
  60. package/docs/specs/03-api-contract.md +397 -0
  61. package/docs/specs/04-control-and-receipt-lifecycle.md +175 -0
  62. package/docs/specs/05-endpoint-and-lifecycle.md +57 -0
  63. package/docs/specs/06-managed-updates.md +55 -0
  64. package/licenses/Paseo-0.15.3.txt +211 -0
  65. package/package.json +37 -4
  66. package/vectors/bearer-v1.json +6 -0
  67. package/vectors/envelope-v1.json +24 -0
@@ -0,0 +1,132 @@
1
+ import { openOwnedJournal } from './resources.js';
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { LIMITS } from './limits.js';
4
+ export function digest(value) { return createHash('sha256').update(JSON.stringify(value)).digest('hex'); }
5
+ export function canonical(value) { if (value === null || typeof value !== 'object')
6
+ return JSON.stringify(value) ?? 'null'; if (Array.isArray(value))
7
+ return '[' + value.map(canonical).join(',') + ']'; return '{' + Object.keys(value).filter(k => value[k] !== undefined).sort().map(k => JSON.stringify(k) + ':' + canonical(value[k])).join(',') + '}'; }
8
+ export class OperationJournal {
9
+ db;
10
+ constructor(path) {
11
+ this.db = openOwnedJournal(path);
12
+ try {
13
+ this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA busy_timeout=5000;
14
+ CREATE TABLE IF NOT EXISTS operations(pairId TEXT NOT NULL,id TEXT NOT NULL,digest TEXT NOT NULL,expiresAt INTEGER NOT NULL,state TEXT NOT NULL,envelope TEXT,receipt TEXT,code TEXT,revision INTEGER NOT NULL DEFAULT 0,evidence TEXT,sentRevision INTEGER NOT NULL DEFAULT 0,reconciledAt INTEGER NOT NULL DEFAULT 0,PRIMARY KEY(pairId,id));
15
+ CREATE TABLE IF NOT EXISTS attention(pairId TEXT NOT NULL,id TEXT NOT NULL,expiresAt INTEGER NOT NULL,body TEXT NOT NULL,sent INTEGER NOT NULL DEFAULT 0,agentId TEXT,requestId TEXT,requestBinding TEXT,resolvedAt INTEGER,resolveSent INTEGER NOT NULL DEFAULT 0,PRIMARY KEY(pairId,id));
16
+ CREATE TABLE IF NOT EXISTS controls(pairId TEXT NOT NULL,id TEXT NOT NULL,digest TEXT NOT NULL,expiresAt INTEGER NOT NULL,receipt TEXT,state TEXT,type TEXT NOT NULL,operationId TEXT,receiptSent INTEGER NOT NULL DEFAULT 0,PRIMARY KEY(pairId,id));
17
+ CREATE TABLE IF NOT EXISTS pair_revocations(pairId TEXT PRIMARY KEY,at INTEGER NOT NULL);
18
+ CREATE TABLE IF NOT EXISTS cancellations(pairId TEXT NOT NULL,id TEXT NOT NULL,at INTEGER NOT NULL,expiresAt INTEGER NOT NULL,PRIMARY KEY(pairId,id));
19
+ CREATE TABLE IF NOT EXISTS occurrences(occurrenceId TEXT PRIMARY KEY,serverId TEXT NOT NULL,agentId TEXT NOT NULL,requestId TEXT NOT NULL,generation TEXT NOT NULL,fingerprint TEXT NOT NULL,active INTEGER NOT NULL,createdAt INTEGER NOT NULL);
20
+ CREATE INDEX IF NOT EXISTS occurrence_current ON occurrences(serverId,agentId,requestId,active);
21
+ CREATE TABLE IF NOT EXISTS resolutions(occurrenceId TEXT PRIMARY KEY,response TEXT NOT NULL,at INTEGER NOT NULL);`);
22
+ }
23
+ catch (error) {
24
+ this.db.close();
25
+ throw error;
26
+ }
27
+ }
28
+ get(pairId, id) { const r = this.db.prepare('SELECT * FROM operations WHERE pairId=? AND id=?').get(pairId, id); return r ? { ...r, envelope: r.envelope ? JSON.parse(r.envelope) : null, receipt: r.receipt ? JSON.parse(r.receipt) : null, evidence: r.evidence ? JSON.parse(r.evidence) : null } : undefined; }
29
+ prepare(e) { const old = this.get(e.pairId, e.id); if (old) {
30
+ if (old.digest !== digest(e))
31
+ throw Error('OPERATION_CONFLICT');
32
+ return { record: old, fresh: false };
33
+ } const count = this.db.prepare('SELECT count(*) AS n FROM operations WHERE pairId=?').get(e.pairId); if (count.n >= LIMITS.operations)
34
+ throw Error('JOURNAL_LIMIT'); this.db.prepare('INSERT INTO operations(pairId,id,digest,expiresAt,state,envelope) VALUES(?,?,?,?,?,?)').run(e.pairId, e.id, digest(e), e.expiresAt, 'prepared', JSON.stringify(e)); return { record: this.get(e.pairId, e.id), fresh: true }; }
35
+ dispatched(pairId, id) { this.db.prepare("UPDATE operations SET state='dispatched' WHERE pairId=? AND id=? AND state='prepared'").run(pairId, id); }
36
+ outcome(pairId, id, state, receipt, code, revision) { const old = this.get(pairId, id); if (!old)
37
+ throw Error('MISSING_OPERATION'); if ((old.state === 'resolved' || old.state === 'rejected') && old.state !== state || old.state === 'accepted' && state === 'unknown')
38
+ throw Error('RECEIPT_REGRESSION'); const next = revision ?? old.revision + 1; if (next <= old.revision)
39
+ throw Error('RECEIPT_REVISION_REGRESSION'); this.db.prepare('UPDATE operations SET state=?,receipt=?,code=?,revision=? WHERE pairId=? AND id=?').run(state, JSON.stringify(receipt), code || null, next, pairId, id); }
40
+ pending(pairId) { return this.db.prepare("SELECT id FROM operations WHERE pairId=? AND state IN ('dispatched','unknown') ORDER BY reconciledAt,expiresAt LIMIT 100").all(pairId).map(r => this.get(pairId, r.id)); }
41
+ receipts(pairId, now) { return this.db.prepare('SELECT id FROM operations WHERE pairId=? AND receipt IS NOT NULL AND revision>sentRevision AND expiresAt>? ORDER BY expiresAt LIMIT 100').all(pairId, now - LIMITS.retentionMs).map(r => this.get(pairId, r.id)); }
42
+ receiptSent(pairId, id, revision) { this.db.prepare('UPDATE operations SET sentRevision=MAX(sentRevision,?) WHERE pairId=? AND id=?').run(revision, pairId, id); }
43
+ evidence(pairId, id, evidence) { this.db.prepare('UPDATE operations SET evidence=? WHERE pairId=? AND id=? AND evidence IS NULL').run(JSON.stringify(evidence), pairId, id); }
44
+ evidenceOccurrence(pairId, id, occurrenceId) { this.db.prepare("UPDATE operations SET evidence=json_set(evidence,'$.occurrenceId',?) WHERE pairId=? AND id=? AND evidence IS NOT NULL").run(occurrenceId, pairId, id); }
45
+ reconciled(pairId, id, now) { this.db.prepare('UPDATE operations SET reconciledAt=? WHERE pairId=? AND id=?').run(now, pairId, id); }
46
+ revokePair(pairId, now = Date.now()) { if (!this.pairRevoked(pairId)) {
47
+ const count = this.db.prepare('SELECT count(*) AS n FROM pair_revocations').get();
48
+ if (count.n >= LIMITS.revocations)
49
+ throw Error('REVOCATION_LIMIT');
50
+ } this.db.prepare('INSERT OR IGNORE INTO pair_revocations(pairId,at) VALUES(?,?)').run(pairId, now); }
51
+ pairRevoked(pairId) { return !!this.db.prepare('SELECT pairId FROM pair_revocations WHERE pairId=?').get(pairId); }
52
+ revocationTime(pairId) { return this.db.prepare('SELECT at FROM pair_revocations WHERE pairId=?').get(pairId)?.at; }
53
+ retirementDeadline(pairId, revokedAt) { const child = this.db.prepare('SELECT MAX(expiresAt) AS latest FROM (SELECT expiresAt FROM operations WHERE pairId=? UNION ALL SELECT expiresAt FROM controls WHERE pairId=? UNION ALL SELECT expiresAt FROM attention WHERE pairId=? UNION ALL SELECT expiresAt FROM cancellations WHERE pairId=?)').get(pairId, pairId, pairId, pairId); return Math.max(revokedAt, child.latest ?? 0) + LIMITS.retentionMs; }
54
+ cleanupRevocations(retainedPairIds, now) { for (const row of this.db.prepare('SELECT pairId,at FROM pair_revocations').all())
55
+ if (!retainedPairIds.includes(row.pairId) && this.retirementDeadline(row.pairId, row.at) <= now)
56
+ this.db.prepare('DELETE FROM pair_revocations WHERE pairId=?').run(row.pairId); }
57
+ blocked(pairId, id) { return this.pairRevoked(pairId) || !!this.db.prepare('SELECT id FROM cancellations WHERE pairId=? AND id=?').get(pairId, id); }
58
+ applyControl(e, type, operationId, now) {
59
+ const old = this.db.prepare('SELECT digest,receipt FROM controls WHERE pairId=? AND id=?').get(e.pairId, e.id);
60
+ if (old) {
61
+ if (old.digest !== digest(e))
62
+ throw Error('CONTROL_CONFLICT');
63
+ return old.receipt ? JSON.parse(old.receipt) : null;
64
+ }
65
+ const count = this.db.prepare('SELECT count(*) AS n FROM controls WHERE pairId=?').get(e.pairId);
66
+ if (count.n >= LIMITS.operations)
67
+ throw Error('CONTROL_LIMIT');
68
+ this.db.exec('BEGIN IMMEDIATE');
69
+ try {
70
+ let state;
71
+ if (type === 'revoke') {
72
+ this.revokePair(e.pairId, now);
73
+ state = 'revoked';
74
+ }
75
+ else {
76
+ const operation = this.get(e.pairId, operationId);
77
+ state = operation && operation.state !== 'prepared' ? 'tooLate' : 'cancelled';
78
+ if (state === 'cancelled')
79
+ this.db.prepare('INSERT OR IGNORE INTO cancellations(pairId,id,at,expiresAt) VALUES(?,?,?,?)').run(e.pairId, operationId, now, e.expiresAt);
80
+ }
81
+ this.db.prepare('INSERT INTO controls(pairId,id,digest,expiresAt,state,type,operationId) VALUES(?,?,?,?,?,?,?)').run(e.pairId, e.id, digest(e), e.expiresAt, state, type, operationId || null);
82
+ this.db.exec('COMMIT');
83
+ }
84
+ catch (error) {
85
+ this.db.exec('ROLLBACK');
86
+ throw error;
87
+ }
88
+ return null;
89
+ }
90
+ control(pairId, id) { const r = this.db.prepare('SELECT state,receipt,expiresAt,type,operationId FROM controls WHERE pairId=? AND id=?').get(pairId, id); return r ? { ...r, receipt: r.receipt ? JSON.parse(r.receipt) : null } : undefined; }
91
+ controlReceipt(pairId, id, receipt) { this.db.prepare('UPDATE controls SET receipt=? WHERE pairId=? AND id=? AND receipt IS NULL').run(JSON.stringify(receipt), pairId, id); }
92
+ controlReceipts(pairId, now) { return this.db.prepare('SELECT id FROM controls WHERE pairId=? AND receiptSent=0 AND expiresAt>? LIMIT 100').all(pairId, now - LIMITS.retentionMs); }
93
+ controlReceiptSent(pairId, id) { this.db.prepare('UPDATE controls SET receiptSent=1 WHERE pairId=? AND id=?').run(pairId, id); }
94
+ observe(serverId, agentId, generation, request, now = Date.now()) { const requestId = String(request.id); const fingerprint = digest(canonical(request)); const old = this.currentOccurrence(serverId, agentId, requestId); if (old && old.generation === generation && old.fingerprint === fingerprint)
95
+ return old; this.retire(serverId, agentId, requestId); const occurrenceId = randomUUID(); this.db.prepare('INSERT INTO occurrences VALUES(?,?,?,?,?,?,1,?)').run(occurrenceId, serverId, agentId, requestId, generation, fingerprint, now); return this.currentOccurrence(serverId, agentId, requestId); }
96
+ currentOccurrence(serverId, agentId, requestId) { return this.db.prepare('SELECT * FROM occurrences WHERE serverId=? AND agentId=? AND requestId=? AND active=1').get(serverId, agentId, requestId); }
97
+ isCurrent(occurrence) { const current = this.currentOccurrence(occurrence.serverId, occurrence.agentId, occurrence.requestId); return !!current && current.occurrenceId === occurrence.occurrenceId && current.generation === occurrence.generation && current.fingerprint === occurrence.fingerprint; }
98
+ syncRequests(serverId, agentId, generation, requests) { for (const r of this.db.prepare('SELECT requestId,generation FROM occurrences WHERE serverId=? AND agentId=? AND active=1').all(serverId, agentId))
99
+ if (r.generation !== generation || !requests.some(request => request.id === r.requestId))
100
+ this.retire(serverId, agentId, r.requestId); for (const r of requests)
101
+ this.observe(serverId, agentId, generation, r); }
102
+ retire(serverId, agentId, requestId) { this.db.prepare('UPDATE occurrences SET active=0 WHERE serverId=? AND agentId=? AND requestId=?').run(serverId, agentId, requestId); this.db.prepare('UPDATE attention SET resolvedAt=? WHERE agentId=? AND requestId=? AND resolvedAt IS NULL').run(Date.now(), agentId, requestId); }
103
+ retireGeneration(serverId, generation) { for (const r of this.db.prepare('SELECT agentId,requestId FROM occurrences WHERE serverId=? AND generation!=? AND active=1').all(serverId, generation))
104
+ this.retire(serverId, r.agentId, r.requestId); }
105
+ syncAttention(agentId, requiresAttention, timestamp) { if (!requiresAttention)
106
+ this.db.prepare('UPDATE attention SET resolvedAt=? WHERE agentId=? AND resolvedAt IS NULL').run(Date.now(), agentId);
107
+ else if (timestamp !== null)
108
+ this.db.prepare("UPDATE attention SET resolvedAt=? WHERE agentId=? AND requestId IS NULL AND resolvedAt IS NULL AND body!='' AND json_extract(body,'$.envelope.issuedAt')!=?").run(Date.now(), agentId, timestamp); }
109
+ resolution(serverId, agentId, requestId, generation, response, now = Date.now()) { const occurrence = this.currentOccurrence(serverId, agentId, requestId); if (occurrence?.generation === generation)
110
+ this.db.prepare('INSERT OR IGNORE INTO resolutions VALUES(?,?,?)').run(occurrence.occurrenceId, createHash('sha256').update(canonical(response)).digest('hex'), now); this.retire(serverId, agentId, requestId); }
111
+ resolutionFacts(serverId, agentId, requestId) { return this.db.prepare('SELECT o.*,r.response FROM occurrences o JOIN resolutions r USING(occurrenceId) WHERE serverId=? AND agentId=? AND requestId=?').all(serverId, agentId, requestId); }
112
+ queueAttention(pairId, id, expiresAt, body, event) { const old = this.db.prepare('SELECT id FROM attention WHERE pairId=? AND id=?').get(pairId, id); if (old)
113
+ return; const count = this.db.prepare('SELECT count(*) AS n FROM attention WHERE pairId=?').get(pairId); if (count.n >= LIMITS.attention)
114
+ throw Error('ATTENTION_LIMIT'); this.db.prepare('INSERT INTO attention(pairId,id,expiresAt,body,agentId,requestId,requestBinding) VALUES(?,?,?,?,?,?,?)').run(pairId, id, expiresAt, JSON.stringify(body), event.agentId, event.requestId || null, event.requestBinding || null); }
115
+ attention(pairId, now) { return this.db.prepare('SELECT id,body FROM attention WHERE pairId=? AND expiresAt>? AND sent=0 AND resolvedAt IS NULL LIMIT 50').all(pairId, now).map(r => ({ id: r.id, body: JSON.parse(r.body) })); }
116
+ attentionSent(pairId, id) { this.db.prepare('UPDATE attention SET sent=1 WHERE pairId=? AND id=?').run(pairId, id); }
117
+ attentionRecords(pairId) { return this.db.prepare('SELECT id,agentId,requestId,requestBinding FROM attention WHERE pairId=? AND resolvedAt IS NULL').all(pairId); }
118
+ resolveAttention(pairId, id, now) { this.db.prepare('UPDATE attention SET resolvedAt=? WHERE pairId=? AND id=? AND resolvedAt IS NULL').run(now, pairId, id); }
119
+ attentionResolutions(pairId) { return this.db.prepare('SELECT id,resolvedAt FROM attention WHERE pairId=? AND resolvedAt IS NOT NULL AND resolveSent=0 LIMIT 100').all(pairId); }
120
+ attentionResolutionSent(pairId, id) { this.db.prepare('UPDATE attention SET resolveSent=1 WHERE pairId=? AND id=?').run(pairId, id); }
121
+ cleanup(now) {
122
+ this.db.prepare('UPDATE operations SET envelope=NULL WHERE expiresAt<=?').run(now);
123
+ this.db.prepare('DELETE FROM operations WHERE expiresAt<?').run(now - LIMITS.retentionMs);
124
+ this.db.prepare("UPDATE attention SET body='' WHERE expiresAt<=?").run(now);
125
+ this.db.prepare('DELETE FROM attention WHERE expiresAt<?').run(now - LIMITS.retentionMs);
126
+ this.db.prepare('DELETE FROM controls WHERE expiresAt<?').run(now - LIMITS.retentionMs);
127
+ this.db.prepare('DELETE FROM cancellations WHERE expiresAt<?').run(now - LIMITS.retentionMs);
128
+ this.db.prepare("DELETE FROM resolutions WHERE at<? AND NOT EXISTS(SELECT 1 FROM operations WHERE json_extract(evidence,'$.occurrenceId')=resolutions.occurrenceId)").run(now - LIMITS.retentionMs);
129
+ this.db.prepare("DELETE FROM occurrences WHERE active=0 AND createdAt<? AND NOT EXISTS(SELECT 1 FROM resolutions WHERE resolutions.occurrenceId=occurrences.occurrenceId) AND NOT EXISTS(SELECT 1 FROM operations WHERE json_extract(evidence,'$.occurrenceId')=occurrences.occurrenceId)").run(now - LIMITS.retentionMs);
130
+ }
131
+ close() { this.db.close(); }
132
+ }
@@ -0,0 +1,21 @@
1
+ export declare const LIMITS: Readonly<{
2
+ envelopeBytes: 131072;
3
+ responseBytes: number;
4
+ receiptBytes: 8192;
5
+ plainBytes: 65536;
6
+ commandMs: 300000;
7
+ enrollmentMs: 600000;
8
+ snapshotMs: 600000;
9
+ futureMs: 120000;
10
+ retentionMs: 86400000;
11
+ tasks: 100;
12
+ operations: 1000;
13
+ attention: 1000;
14
+ revocations: 4096;
15
+ pollMs: 3000;
16
+ maxBackoffMs: 30000;
17
+ }>;
18
+ export declare const UUID: RegExp;
19
+ export declare function object(value: unknown): Record<string, unknown>;
20
+ export declare function exact(value: Record<string, unknown>, keys: readonly string[]): void;
21
+ export declare function text(value: unknown, max?: number): string;
package/dist/limits.js ADDED
@@ -0,0 +1,8 @@
1
+ export const LIMITS = Object.freeze({ envelopeBytes: 131072, responseBytes: 5 * 1024 * 1024, receiptBytes: 8192, plainBytes: 65536, commandMs: 300000, enrollmentMs: 600000, snapshotMs: 600000, futureMs: 120000, retentionMs: 86400000, tasks: 100, operations: 1000, attention: 1000, revocations: 4096, pollMs: 3000, maxBackoffMs: 30000 });
2
+ export const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
3
+ export function object(value) { if (!value || typeof value !== 'object' || Array.isArray(value))
4
+ throw Error('INVALID_OBJECT'); return value; }
5
+ export function exact(value, keys) { if (Object.keys(value).some(k => !keys.includes(k)))
6
+ throw Error('UNKNOWN_FIELD'); }
7
+ export function text(value, max = 256) { if (typeof value !== 'string' || !value.length || Buffer.byteLength(value) > max)
8
+ throw Error('INVALID_TEXT'); return value; }
@@ -0,0 +1,120 @@
1
+ import type { DaemonClient } from '@getpaseo/client/internal/daemon-client';
2
+ import type { ServerInfoStatusPayload } from '@getpaseo/protocol/messages';
3
+ import type { Config, Pair } from './config.js';
4
+ import type { Command, OfficialOperations } from './operations.js';
5
+ import { type ReceiptState, type OperationJournal } from './journal.js';
6
+ import { type Evidence } from './evidence.js';
7
+ export interface Attention {
8
+ agentId: string;
9
+ requestId?: string;
10
+ requestBinding?: string;
11
+ kind: 'finished' | 'question' | 'permission' | 'error';
12
+ timestamp: number;
13
+ }
14
+ export declare function localListen(home: string): string;
15
+ export declare function readLocalCredentialForTarget(home: string, target: string): string | undefined;
16
+ export declare class OfficialClient implements OfficialOperations {
17
+ readonly config: Config;
18
+ private journal?;
19
+ readonly sdk: DaemonClient;
20
+ private subscription;
21
+ readonly generation: `${string}-${string}-${string}-${string}-${string}`;
22
+ private serverId;
23
+ private callbacks;
24
+ private unlisten;
25
+ constructor(config: Config, journal?: OperationJournal | undefined);
26
+ connect(): Promise<void>;
27
+ info(): ServerInfoStatusPayload | null;
28
+ private emit;
29
+ onAttention(callback: (event: Attention) => void): () => void;
30
+ requestContext(): {
31
+ serverId: string;
32
+ generation: `${string}-${string}-${string}-${string}-${string}`;
33
+ };
34
+ current(agentId: string): Promise<{
35
+ id: string;
36
+ provider: string;
37
+ cwd: string;
38
+ model: string | null;
39
+ createdAt: string;
40
+ updatedAt: string;
41
+ lastUserMessageAt: string | null;
42
+ status: "error" | "initializing" | "idle" | "running" | "closed";
43
+ capabilities: import("@getpaseo/protocol/agent-types").AgentCapabilityFlags;
44
+ currentModeId: string | null;
45
+ availableModes: import("@getpaseo/protocol/agent-types").AgentMode[];
46
+ pendingPermissions: import("@getpaseo/protocol/agent-types").AgentPermissionRequest[];
47
+ persistence: import("@getpaseo/protocol/agent-types").AgentPersistenceHandle | null;
48
+ title: string | null;
49
+ labels: Record<string, string>;
50
+ workspaceId?: string | undefined;
51
+ features?: ({
52
+ type: "toggle";
53
+ id: string;
54
+ label: string;
55
+ value: boolean;
56
+ description?: string | undefined;
57
+ tooltip?: string | undefined;
58
+ icon?: string | undefined;
59
+ } | {
60
+ type: "select";
61
+ id: string;
62
+ label: string;
63
+ value: string | null;
64
+ options: {
65
+ id: string;
66
+ label: string;
67
+ description?: string | undefined;
68
+ isDefault?: boolean | undefined;
69
+ metadata?: Record<string, unknown> | undefined;
70
+ }[];
71
+ description?: string | undefined;
72
+ tooltip?: string | undefined;
73
+ icon?: string | undefined;
74
+ desktopTrigger?: "label" | "icon" | undefined;
75
+ })[] | undefined;
76
+ thinkingOptionId?: string | null | undefined;
77
+ effectiveThinkingOptionId?: string | null | undefined;
78
+ activeTurn?: {
79
+ turnId: string;
80
+ startedAt: string | null;
81
+ } | null | undefined;
82
+ runtimeInfo?: import("@getpaseo/protocol/agent-types").AgentRuntimeInfo | undefined;
83
+ lastUsage?: import("@getpaseo/protocol/agent-types").AgentUsage | undefined;
84
+ lastError?: string | undefined;
85
+ requiresAttention?: boolean | undefined;
86
+ attentionReason?: "permission" | "finished" | "error" | null | undefined;
87
+ attentionTimestamp?: string | null | undefined;
88
+ archivedAt?: string | null | undefined;
89
+ providerUnavailable?: boolean | undefined;
90
+ internal?: boolean | undefined;
91
+ } | null>;
92
+ send(command: Extract<Command, {
93
+ type: 'send';
94
+ }>): Promise<void>;
95
+ permission(command: Extract<Command, {
96
+ type: 'permission';
97
+ }>): Promise<void>;
98
+ reconcile(command: Command, pair?: Pick<Pair, 'pairId' | 'rootKey'>): Promise<ReceiptState | null>;
99
+ reconcileEvidence(evidence: Evidence, pair?: Pick<Pair, 'pairId' | 'rootKey'>): Promise<ReceiptState | null>;
100
+ snapshot(): Promise<{
101
+ version: number;
102
+ daemonServerId: string;
103
+ hostName: string;
104
+ measuredAt: number;
105
+ tasks: {
106
+ agentId: string;
107
+ title: string | null;
108
+ status: "error" | "initializing" | "idle" | "running" | "closed";
109
+ updatedAt: string;
110
+ requiresAttention: boolean;
111
+ attentionReason: "permission" | "finished" | "error" | null;
112
+ pendingRequests: {
113
+ requestId: string;
114
+ request: import("@getpaseo/protocol/agent-types").AgentPermissionRequest;
115
+ }[];
116
+ }[];
117
+ usage: unknown;
118
+ }>;
119
+ close(): Promise<void>;
120
+ }
@@ -0,0 +1,162 @@
1
+ // MoRemote adaptation: bounded read-only local credential selection and independent identity.
2
+ // Upstream portions: Copyright (c) 2025-present Mohamed Boudra, Apache-2.0.
3
+ // Changed for this companion; retained release license/provenance: licenses/Paseo-0.15.3.txt and NOTICE.
4
+ import { readFileSync, statSync } from 'node:fs';
5
+ import { randomUUID } from 'node:crypto';
6
+ import { join } from 'node:path';
7
+ import { hostname } from 'node:os';
8
+ import { isDeepStrictEqual } from 'node:util';
9
+ import { createHostClient, parseHostTarget } from '@getpaseo/client/node';
10
+ import { normalizeLoopbackToLocalhost, parseConnectionUri } from '@getpaseo/protocol/daemon-endpoints';
11
+ import { occurrenceBinding } from './bindings.js';
12
+ import { LIMITS } from './limits.js';
13
+ import { evidenceForCommand, contentDigest } from './evidence.js';
14
+ function boundedFile(path, max) { if (statSync(path).size > max)
15
+ throw Error('OFFICIAL_FILE_LIMIT'); const raw = readFileSync(path, 'utf8'); if (Buffer.byteLength(raw) > max)
16
+ throw Error('OFFICIAL_FILE_LIMIT'); return raw; }
17
+ function normalizeTarget(target) { try {
18
+ const t = target.trim();
19
+ if (t.startsWith('tcp://')) {
20
+ const p = parseConnectionUri(t);
21
+ return normalizeLoopbackToLocalhost(p.isIpv6 ? '[' + p.host + ']:' + p.port : p.host + ':' + p.port);
22
+ }
23
+ if (t.startsWith('unix://') || t.startsWith('pipe://'))
24
+ return t;
25
+ if (t.startsWith('/'))
26
+ return 'unix://' + t;
27
+ if (t.startsWith('\\\\.\\pipe\\'))
28
+ return 'pipe://' + t;
29
+ if (/^\d+$/.test(t))
30
+ return 'localhost:' + t;
31
+ return normalizeLoopbackToLocalhost(t);
32
+ }
33
+ catch {
34
+ return null;
35
+ } }
36
+ export function localListen(home) { const lock = JSON.parse(boundedFile(join(home, 'paseo.pid'), 65536)); if (typeof lock.listen !== 'string' || lock.listen.length > 4096)
37
+ throw Error('INVALID_OFFICIAL_PID'); return lock.listen; }
38
+ export function readLocalCredentialForTarget(home, target) { try {
39
+ const a = normalizeTarget(target), b = normalizeTarget(localListen(home));
40
+ if (!a || !b || a !== b)
41
+ return undefined;
42
+ const token = boundedFile(join(home, 'local-credential'), 256).trim();
43
+ return /^[A-Za-z0-9_-]{43}$/.test(token) ? token : undefined;
44
+ }
45
+ catch {
46
+ return undefined;
47
+ } }
48
+ export class OfficialClient {
49
+ config;
50
+ journal;
51
+ sdk;
52
+ subscription;
53
+ generation = randomUUID();
54
+ serverId = '';
55
+ callbacks = new Set();
56
+ unlisten;
57
+ constructor(config, journal) {
58
+ this.config = config;
59
+ this.journal = journal;
60
+ const target = config.target || localListen(config.paseoHome);
61
+ const password = parseHostTarget(target).password || process.env.PASEO_PASSWORD;
62
+ this.sdk = createHostClient(target, { clientId: config.clientId, clientType: 'cli', appVersion: 'moremote-cli/0.1.0', ...(password ? { password } : { localCredential: () => readLocalCredentialForTarget(config.paseoHome, target) }), reconnect: { enabled: false }, connectTimeoutMs: 15000, logger: { debug() { }, info() { }, warn() { }, error() { } } });
63
+ }
64
+ async connect() {
65
+ await this.sdk.connect();
66
+ const info = this.info();
67
+ if (!info || info.features?.explicitEventSubscriptions !== true) {
68
+ await this.sdk.close();
69
+ throw Error('EXPLICIT_SUBSCRIPTIONS_REQUIRED');
70
+ }
71
+ if (this.config.daemonServerId && info.serverId !== this.config.daemonServerId) {
72
+ await this.sdk.close();
73
+ throw Error('DAEMON_IDENTITY_CHANGED');
74
+ }
75
+ this.serverId = info.serverId;
76
+ this.journal?.retireGeneration(info.serverId, this.generation);
77
+ this.unlisten = this.sdk.subscribeRawMessages(message => {
78
+ if (message.type === 'agent_attention_required') {
79
+ const p = message.payload;
80
+ if (p.reason !== 'permission')
81
+ this.emit({ agentId: p.agentId, kind: p.reason, timestamp: Date.parse(p.timestamp) });
82
+ }
83
+ if (message.type === 'agent_permission_request') {
84
+ const p = message.payload;
85
+ void this.current(p.agentId).then(agent => { const r = agent?.pendingPermissions?.find(r => r.id === p.request.id); if (!r)
86
+ return; const ts = Date.parse(agent?.attentionTimestamp || agent?.updatedAt || ''); if (Number.isFinite(ts))
87
+ this.emit({ agentId: p.agentId, requestId: r.id, kind: r.kind === 'question' ? 'question' : 'permission', timestamp: ts }); }).catch(() => { });
88
+ }
89
+ if (message.type === 'agent_permission_resolved') {
90
+ const p = message.payload;
91
+ this.journal?.resolution(this.serverId, p.agentId, p.requestId, this.generation, p.resolution);
92
+ }
93
+ });
94
+ this.subscription = this.sdk.observeEvents(['agent_attention_required', 'agent_permission_request', 'agent_permission_resolved', 'status.server_info'], { notifications: false });
95
+ await this.subscription.ready;
96
+ }
97
+ info() { return this.sdk.getLastServerInfoMessage(); }
98
+ emit(event) { if (Number.isSafeInteger(event.timestamp) && event.timestamp >= 0)
99
+ for (const cb of this.callbacks)
100
+ cb(event); }
101
+ onAttention(callback) { this.callbacks.add(callback); return () => { this.callbacks.delete(callback); }; }
102
+ 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; }
104
+ async send(command) { if (!this.sdk.isConnected)
105
+ throw Error('OFFICIAL_DISCONNECTED'); await this.sdk.sendAgentMessage(command.agentId, command.text, { messageId: command.messageId }); }
106
+ async permission(command) { if (!this.sdk.isConnected)
107
+ throw Error('OFFICIAL_DISCONNECTED'); const result = await this.sdk.respondToPermissionAndWait(command.agentId, command.requestId, command.response, 15000); if (!isDeepStrictEqual(result.resolution, command.response))
108
+ throw Error('RESOLUTION_MISMATCH'); }
109
+ async reconcile(command, pair) { return this.reconcileEvidence(evidenceForCommand(command, this.serverId), pair); }
110
+ async reconcileEvidence(evidence, pair) {
111
+ if (evidence.serverId !== this.serverId)
112
+ return null;
113
+ if (evidence.type === 'permission') {
114
+ if (!pair || !this.journal)
115
+ return null;
116
+ for (const fact of this.journal.resolutionFacts(this.serverId, evidence.agentId, evidence.requestId))
117
+ if (await occurrenceBinding(pair, fact) === evidence.requestBinding && fact.response === evidence.responseDigest)
118
+ return 'resolved';
119
+ return null;
120
+ }
121
+ if (!this.sdk.isConnected)
122
+ return null;
123
+ const timeline = await this.sdk.fetchAgentTimeline(evidence.agentId, { direction: 'tail', projection: 'canonical', limit: 100, timeout: 15000 });
124
+ if (timeline.agentId !== evidence.agentId)
125
+ return null;
126
+ return timeline.entries.some(e => e.item.type === 'user_message' && e.item.clientMessageId === evidence.messageId && contentDigest(e.item.text) === evidence.textDigest) ? 'accepted' : null;
127
+ }
128
+ async snapshot() {
129
+ const info = this.info();
130
+ if (!info)
131
+ throw Error('OFFICIAL_IDENTITY_UNAVAILABLE');
132
+ const result = await this.sdk.fetchAgents({ page: { limit: LIMITS.tasks }, filter: { includeArchived: false, includeInternal: false }, sort: [{ key: 'updated_at', direction: 'desc' }], timeout: 15000 });
133
+ const agents = result.entries.slice(0, LIMITS.tasks).map(entry => entry.agent);
134
+ for (const a of agents) {
135
+ this.journal?.syncRequests(this.serverId, a.id, this.generation, a.pendingPermissions);
136
+ this.journal?.syncAttention(a.id, a.requiresAttention === true, a.attentionTimestamp ? Date.parse(a.attentionTimestamp) : null);
137
+ }
138
+ for (const a of agents) {
139
+ if (a.requiresAttention && a.attentionReason && a.attentionTimestamp) {
140
+ const timestamp = Date.parse(a.attentionTimestamp);
141
+ if (a.attentionReason === 'permission') {
142
+ for (const r of a.pendingPermissions)
143
+ this.emit({ agentId: a.id, requestId: r.id, kind: r.kind === 'question' ? 'question' : 'permission', timestamp });
144
+ }
145
+ else
146
+ this.emit({ agentId: a.id, kind: a.attentionReason, timestamp });
147
+ }
148
+ }
149
+ let usage = null;
150
+ if (info.features?.providerUsageList) {
151
+ 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 })) })) };
154
+ }
155
+ catch {
156
+ usage = null;
157
+ }
158
+ }
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 };
160
+ }
161
+ async close() { this.unlisten?.(); await this.subscription?.release().catch(() => { }); await this.sdk.close(); }
162
+ }
@@ -0,0 +1,71 @@
1
+ import type { AgentPermissionResponse } from '@getpaseo/protocol/agent-types';
2
+ import { type Envelope } from './crypto.js';
3
+ import { OperationJournal, type ReceiptState, type Occurrence } from './journal.js';
4
+ import type { Pair } from './config.js';
5
+ import { type Evidence } from './evidence.js';
6
+ export type Command = {
7
+ type: 'send';
8
+ agentId: string;
9
+ text: string;
10
+ messageId: string;
11
+ } | {
12
+ type: 'permission';
13
+ agentId: string;
14
+ requestId: string;
15
+ requestBinding: string;
16
+ response: AgentPermissionResponse;
17
+ };
18
+ export interface PendingRequest {
19
+ id: string;
20
+ kind?: string;
21
+ requestBinding?: string;
22
+ occurrence?: Occurrence;
23
+ actions?: {
24
+ id: string;
25
+ behavior: string;
26
+ }[];
27
+ input?: unknown;
28
+ suggestions?: unknown[];
29
+ }
30
+ export interface CurrentAgent {
31
+ id: string;
32
+ pendingPermissions?: PendingRequest[];
33
+ }
34
+ export interface OfficialOperations {
35
+ current(id: string): Promise<CurrentAgent | null>;
36
+ send(c: Extract<Command, {
37
+ type: 'send';
38
+ }>): Promise<void>;
39
+ permission(c: Extract<Command, {
40
+ type: 'permission';
41
+ }>): Promise<void>;
42
+ reconcile(c: Command, pair?: Pick<Pair, 'pairId' | 'rootKey'>): Promise<ReceiptState | null>;
43
+ reconcileEvidence?(evidence: Evidence, pair: Pick<Pair, 'pairId' | 'rootKey'>): Promise<ReceiptState | null>;
44
+ requestContext?(): {
45
+ serverId: string;
46
+ generation: string;
47
+ };
48
+ }
49
+ export interface OperationCloud {
50
+ dispatch(id: string): Promise<{
51
+ dispatchAllowed: boolean;
52
+ }>;
53
+ receipt(id: string, body: {
54
+ state: ReceiptState;
55
+ revision: number;
56
+ envelope: Envelope;
57
+ }): Promise<unknown>;
58
+ }
59
+ export interface OperationContext {
60
+ pair: Pick<Pair, 'pairId' | 'rootKey' | 'hostToken' | 'active' | 'relayRetiredAt'>;
61
+ journal: OperationJournal;
62
+ official: OfficialOperations;
63
+ cloud: OperationCloud;
64
+ clock?: () => number;
65
+ }
66
+ export declare function parseCommand(value: unknown, id: string): Command;
67
+ export declare function validateCommand(value: unknown, id: string, current: CurrentAgent | null): Command;
68
+ export declare function boundCurrent(ctx: Pick<OperationContext, 'pair' | 'journal' | 'official'>, agentId: string): Promise<CurrentAgent | null>;
69
+ /** Read-only recovery, including after command payload expiry or pairing revoke. */
70
+ export declare function reconcileJournal(ctx: OperationContext, now?: number): Promise<boolean>;
71
+ export declare function executeOperation(ctx: OperationContext, input: unknown, now?: number): Promise<void>;