@moxuli/moremote 0.0.0-stage → 0.1.0

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 (65) 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 +308 -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.d.ts +3 -0
  15. package/dist/control.js +226 -0
  16. package/dist/controls.d.ts +15 -0
  17. package/dist/controls.js +36 -0
  18. package/dist/crypto.d.ts +23 -0
  19. package/dist/crypto.js +68 -0
  20. package/dist/evidence.d.ts +19 -0
  21. package/dist/evidence.js +4 -0
  22. package/dist/journal.d.ts +104 -0
  23. package/dist/journal.js +132 -0
  24. package/dist/limits.d.ts +21 -0
  25. package/dist/limits.js +8 -0
  26. package/dist/official-client.d.ts +120 -0
  27. package/dist/official-client.js +162 -0
  28. package/dist/operations.d.ts +71 -0
  29. package/dist/operations.js +210 -0
  30. package/dist/pairing.d.ts +19 -0
  31. package/dist/pairing.js +68 -0
  32. package/dist/permission.d.ts +9 -0
  33. package/dist/permission.js +66 -0
  34. package/dist/projection.d.ts +24 -0
  35. package/dist/projection.js +35 -0
  36. package/dist/resources.d.ts +76 -0
  37. package/dist/resources.js +299 -0
  38. package/dist/runtime.d.ts +8 -0
  39. package/dist/runtime.js +375 -0
  40. package/dist/service.d.ts +21 -0
  41. package/dist/service.js +310 -0
  42. package/dist/supervisor.d.ts +15 -0
  43. package/dist/supervisor.js +175 -0
  44. package/dist/update-state.d.ts +30 -0
  45. package/dist/update-state.js +158 -0
  46. package/dist/updater.d.ts +9 -0
  47. package/dist/updater.js +152 -0
  48. package/docs/README.md +23 -0
  49. package/docs/STATE.md +132 -0
  50. package/docs/configuration.md +37 -0
  51. package/docs/conventions.md +9 -0
  52. package/docs/decisions/0001-managed-updates.md +19 -0
  53. package/docs/plans/2026-11-10-managed-updates.md +26 -0
  54. package/docs/plans/2026-11-10-notification-delivery.md +118 -0
  55. package/docs/releasing.md +38 -0
  56. package/docs/specs/01-architecture.md +102 -0
  57. package/docs/specs/02-encrypted-delivery.md +194 -0
  58. package/docs/specs/03-api-contract.md +397 -0
  59. package/docs/specs/04-control-and-receipt-lifecycle.md +175 -0
  60. package/docs/specs/05-endpoint-and-lifecycle.md +57 -0
  61. package/docs/specs/06-managed-updates.md +49 -0
  62. package/licenses/Paseo-0.15.3.txt +211 -0
  63. package/package.json +37 -4
  64. package/vectors/bearer-v1.json +6 -0
  65. package/vectors/envelope-v1.json +24 -0
@@ -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>;
@@ -0,0 +1,210 @@
1
+ import { exact, object, text, LIMITS } from './limits.js';
2
+ import { decode, openEnvelope, sealEnvelope, validateEnvelope } from './crypto.js';
3
+ import { occurrenceBinding } from './bindings.js';
4
+ import { validatePermissionInput } from './permission.js';
5
+ import { evidenceForCommand } from './evidence.js';
6
+ export function parseCommand(value, id) {
7
+ const c = object(value);
8
+ text(c.agentId);
9
+ if (c.type === 'send') {
10
+ exact(c, ['type', 'agentId', 'text', 'messageId']);
11
+ text(c.text, 60000);
12
+ if (c.messageId !== id)
13
+ throw Error('MESSAGE_ID_MISMATCH');
14
+ }
15
+ else if (c.type === 'permission') {
16
+ exact(c, ['type', 'agentId', 'requestId', 'requestBinding', 'response']);
17
+ text(c.requestId);
18
+ decode(c.requestBinding, 32);
19
+ const r = object(c.response);
20
+ if (r.behavior === 'allow') {
21
+ exact(r, ['behavior', 'selectedActionId', 'updatedInput', 'updatedPermissions']);
22
+ if (r.updatedInput !== undefined)
23
+ object(r.updatedInput);
24
+ if (r.updatedPermissions !== undefined && (!Array.isArray(r.updatedPermissions) || r.updatedPermissions.length > 20 || r.updatedPermissions.some(v => !v || typeof v !== 'object' || Array.isArray(v))))
25
+ throw Error('INVALID_PERMISSIONS');
26
+ }
27
+ else if (r.behavior === 'deny') {
28
+ exact(r, ['behavior', 'selectedActionId', 'message', 'interrupt']);
29
+ if (r.message !== undefined)
30
+ text(r.message, 8192);
31
+ if (r.interrupt !== undefined && typeof r.interrupt !== 'boolean')
32
+ throw Error('INVALID_RESPONSE');
33
+ }
34
+ else
35
+ throw Error('INVALID_RESPONSE');
36
+ if (r.selectedActionId !== undefined)
37
+ text(r.selectedActionId);
38
+ }
39
+ else
40
+ throw Error('UNSUPPORTED_COMMAND');
41
+ if (Buffer.byteLength(JSON.stringify(c)) > LIMITS.plainBytes)
42
+ throw Error('COMMAND_LIMIT');
43
+ return c;
44
+ }
45
+ export function validateCommand(value, id, current) {
46
+ const c = parseCommand(value, id);
47
+ if (!current || current.id !== c.agentId)
48
+ throw Error('AGENT_NOT_CURRENT');
49
+ if (c.type === 'permission') {
50
+ const request = current.pendingPermissions?.find(r => r.id === c.requestId);
51
+ if (!request || request.requestBinding !== c.requestBinding)
52
+ throw Error('STALE_REQUEST_INSTANCE');
53
+ const action = c.response.selectedActionId;
54
+ if (!request.actions?.length || !action || !request.actions.some(a => a.id === action && a.behavior === c.response.behavior))
55
+ throw Error('STALE_ACTION');
56
+ validatePermissionInput(request, c.response);
57
+ }
58
+ return c;
59
+ }
60
+ export async function boundCurrent(ctx, agentId) { const current = await ctx.official.current(agentId); if (!current)
61
+ return null; const source = ctx.official.requestContext?.(); if (!source)
62
+ return current; const requests = current.pendingPermissions || []; ctx.journal.syncRequests(source.serverId, agentId, source.generation, requests); return { ...current, pendingPermissions: await Promise.all(requests.map(async (r) => { const occurrence = ctx.journal.currentOccurrence(source.serverId, agentId, r.id); if (!occurrence)
63
+ return { ...r, requestBinding: undefined }; return { ...r, occurrence, requestBinding: await occurrenceBinding(ctx.pair, occurrence) }; })) }; }
64
+ async function outcome(ctx, e, state, now, code) {
65
+ const old = ctx.journal.get(e.pairId, e.id);
66
+ if (old.state === 'accepted' && state === 'unknown')
67
+ state = 'accepted';
68
+ if (old.state === 'resolved' || old.state === 'rejected')
69
+ state = old.state;
70
+ if (old.receipt && old.state === state) {
71
+ if (old.sentRevision < old.revision) {
72
+ await ctx.cloud.receipt(e.id, { state, revision: old.revision, envelope: old.receipt });
73
+ ctx.journal.receiptSent(e.pairId, e.id, old.revision);
74
+ }
75
+ return;
76
+ }
77
+ if (now >= e.expiresAt + LIMITS.retentionMs)
78
+ return;
79
+ const revision = old.revision + 1;
80
+ const envelope = await sealEnvelope(decode(ctx.pair.rootKey, 32), { version: 1, pairId: e.pairId, id: e.id, channel: 'receipt', issuedAt: now, expiresAt: now + LIMITS.snapshotMs }, { operationId: e.id, state, revision, ...(code ? { code } : {}) });
81
+ ctx.journal.outcome(e.pairId, e.id, state, envelope, code, revision);
82
+ await ctx.cloud.receipt(e.id, { state, revision, envelope });
83
+ ctx.journal.receiptSent(e.pairId, e.id, revision);
84
+ }
85
+ /** Read-only recovery, including after command payload expiry or pairing revoke. */
86
+ export async function reconcileJournal(ctx, now = Date.now()) {
87
+ let failed = false;
88
+ for (const record of ctx.journal.pending(ctx.pair.pairId)) {
89
+ if (record.state === 'prepared')
90
+ continue;
91
+ try {
92
+ const state = record.evidence && ctx.official.reconcileEvidence ? await ctx.official.reconcileEvidence(record.evidence, ctx.pair) : null;
93
+ await outcome(ctx, record, state || 'unknown', now, state ? undefined : 'UNCONFIRMED');
94
+ }
95
+ catch {
96
+ failed = true;
97
+ }
98
+ finally {
99
+ ctx.journal.reconciled(record.pairId, record.id, now);
100
+ }
101
+ }
102
+ return failed;
103
+ }
104
+ export async function executeOperation(ctx, input, now) {
105
+ const clock = ctx.clock || (now === undefined ? Date.now : () => now);
106
+ now = now ?? clock();
107
+ const e = validateEnvelope(input, now);
108
+ if (e.channel !== 'command' || e.pairId !== ctx.pair.pairId || !ctx.pair.active || ctx.pair.relayRetiredAt !== undefined)
109
+ throw Error('PAIR_NOT_ACTIVE');
110
+ const value = await openEnvelope(decode(ctx.pair.rootKey, 32), e, now);
111
+ const command = parseCommand(value, e.id);
112
+ const { record, fresh } = ctx.journal.prepare(e);
113
+ if (fresh)
114
+ ctx.journal.evidence(e.pairId, e.id, evidenceForCommand(command, ctx.official.requestContext?.().serverId || ''));
115
+ if (!fresh) {
116
+ if (record.state === 'prepared')
117
+ return;
118
+ if (record.receipt && (record.state === 'accepted' || record.state === 'resolved' || record.state === 'rejected')) {
119
+ await outcome(ctx, e, record.state, now);
120
+ return;
121
+ }
122
+ const reconciled = await ctx.official.reconcile(command, ctx.pair);
123
+ await outcome(ctx, e, reconciled || 'unknown', now, reconciled ? undefined : 'UNCONFIRMED');
124
+ return;
125
+ }
126
+ if (ctx.journal.blocked(e.pairId, e.id))
127
+ return;
128
+ const current = await boundCurrent(ctx, command.agentId);
129
+ let invalid = false;
130
+ try {
131
+ validateCommand(value, e.id, current);
132
+ }
133
+ catch {
134
+ invalid = true;
135
+ }
136
+ if (command.type === 'permission') {
137
+ const occurrence = current?.pendingPermissions?.find(r => r.id === command.requestId)?.occurrence;
138
+ if (occurrence)
139
+ ctx.journal.evidenceOccurrence(e.pairId, e.id, occurrence.occurrenceId);
140
+ }
141
+ if (e.expiresAt <= clock() || ctx.journal.blocked(e.pairId, e.id))
142
+ return;
143
+ // Irrevocable local commit before cloud dispatch. Recovery cannot reacquire or replay it.
144
+ ctx.journal.dispatched(e.pairId, e.id);
145
+ let boundary;
146
+ try {
147
+ boundary = await ctx.cloud.dispatch(e.id);
148
+ }
149
+ catch {
150
+ await outcome(ctx, e, 'unknown', clock(), 'DISPATCH_UNCONFIRMED');
151
+ return;
152
+ }
153
+ if (!boundary.dispatchAllowed) {
154
+ await outcome(ctx, e, 'unknown', clock(), 'DISPATCH_DENIED');
155
+ return;
156
+ }
157
+ if (e.expiresAt <= clock() || ctx.journal.blocked(e.pairId, e.id)) {
158
+ await outcome(ctx, e, 'rejected', clock(), 'EXPIRED_OR_LOCALLY_REVOKED');
159
+ return;
160
+ }
161
+ if (invalid) {
162
+ await outcome(ctx, e, 'rejected', clock(), 'STALE_OR_INVALID_REQUEST');
163
+ return;
164
+ }
165
+ let refreshed;
166
+ try {
167
+ refreshed = await boundCurrent(ctx, command.agentId);
168
+ }
169
+ catch {
170
+ await outcome(ctx, e, 'rejected', clock(), 'OFFICIAL_UNAVAILABLE');
171
+ return;
172
+ }
173
+ try {
174
+ validateCommand(value, e.id, refreshed);
175
+ }
176
+ catch {
177
+ await outcome(ctx, e, 'rejected', clock(), 'STALE_OR_INVALID_REQUEST');
178
+ return;
179
+ }
180
+ if (command.type === 'permission' && ctx.official.requestContext) {
181
+ const occurrence = refreshed?.pendingPermissions?.find(r => r.id === command.requestId)?.occurrence;
182
+ if (!occurrence || !ctx.journal.isCurrent(occurrence)) {
183
+ await outcome(ctx, e, 'rejected', clock(), 'STALE_REQUEST_INSTANCE');
184
+ return;
185
+ }
186
+ }
187
+ if (e.expiresAt <= clock() || ctx.journal.blocked(e.pairId, e.id)) {
188
+ await outcome(ctx, e, 'rejected', clock(), 'EXPIRED_OR_LOCALLY_REVOKED');
189
+ return;
190
+ }
191
+ let state;
192
+ let code;
193
+ try {
194
+ if (command.type === 'send') {
195
+ await ctx.official.send(command);
196
+ state = 'accepted';
197
+ }
198
+ else {
199
+ await ctx.official.permission(command);
200
+ state = 'resolved';
201
+ }
202
+ }
203
+ catch {
204
+ state = await ctx.official.reconcile(command, ctx.pair).catch(() => null) || 'unknown';
205
+ if (state === 'unknown')
206
+ code = 'OFFICIAL_UNCONFIRMED';
207
+ }
208
+ // Receipt transport failure cannot erase a separately persisted positive admission fact.
209
+ await outcome(ctx, e, state, clock(), code);
210
+ }
@@ -0,0 +1,19 @@
1
+ import { CloudClient } from './cloud-client.js';
2
+ import { type Pair, type Config } from './config.js';
3
+ export declare function tokenHash(token: string): string;
4
+ export declare function makeOffer(apiOrigin: string, now?: number): {
5
+ pair: Pair;
6
+ offer: {
7
+ version: number;
8
+ apiOrigin: string;
9
+ pairId: string;
10
+ enrollmentToken: string | undefined;
11
+ rootKey: string;
12
+ expiresAt: number | undefined;
13
+ };
14
+ };
15
+ export declare function verifyClaim(pair: Pick<Pair, 'pairId' | 'rootKey' | 'expiresAt'>, pending: unknown, now?: number): Promise<{
16
+ claimId: string;
17
+ phoneTokenHash: string;
18
+ }>;
19
+ export declare function activatePending(config: Config, dir: string, pair: Pair, cloud: CloudClient, daemonServerId: string, hostName?: string): Promise<boolean>;