@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.
- package/README.md +85 -7
- package/bin/moremote-cli.js +11 -4
- package/dist/activity.d.ts +79 -0
- package/dist/activity.js +193 -0
- package/dist/cli.js +36 -41
- package/dist/cloud-client.d.ts +13 -4
- package/dist/cloud-client.js +60 -15
- package/dist/config.d.ts +7 -0
- package/dist/config.js +23 -4
- package/dist/control.d.ts +1 -0
- package/dist/control.js +9 -0
- package/dist/crypto.d.ts +1 -1
- package/dist/crypto.js +2 -2
- package/dist/enrollment-files.d.ts +37 -0
- package/dist/enrollment-files.js +225 -0
- package/dist/enrollment-protocol.d.ts +50 -0
- package/dist/enrollment-protocol.js +44 -0
- package/dist/journal.js +2 -1
- package/dist/local-enrollment.d.ts +25 -0
- package/dist/local-enrollment.js +160 -0
- package/dist/official-client.d.ts +87 -6
- package/dist/official-client.js +135 -32
- package/dist/operations.d.ts +1 -0
- package/dist/operations.js +24 -4
- package/dist/projection.d.ts +7 -2
- package/dist/resources.d.ts +2 -1
- package/dist/resources.js +69 -32
- package/dist/runtime.d.ts +10 -1
- package/dist/runtime.js +111 -10
- package/dist/service.js +43 -8
- package/dist/setup-upgrade.d.ts +2 -0
- package/dist/setup-upgrade.js +65 -0
- package/dist/setup.d.ts +12 -0
- package/dist/setup.js +38 -0
- package/dist/supervisor.d.ts +1 -0
- package/dist/supervisor.js +44 -1
- package/docs/README.md +4 -3
- package/docs/STATE.md +327 -10
- package/docs/configuration.md +119 -5
- package/docs/plans/2026-11-11-native-service-acceptance.md +168 -0
- package/docs/specs/03-api-contract.md +122 -2
- package/docs/specs/04-control-and-receipt-lifecycle.md +12 -0
- package/docs/specs/05-endpoint-and-lifecycle.md +126 -2
- package/docs/specs/06-managed-updates.md +34 -1
- package/package.json +2 -2
package/dist/journal.js
CHANGED
|
@@ -102,8 +102,9 @@ export class OperationJournal {
|
|
|
102
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
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
104
|
this.retire(serverId, r.agentId, r.requestId); }
|
|
105
|
+
// Pending requests are authoritative even when the agent attention flag is false.
|
|
105
106
|
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
|
+
this.db.prepare('UPDATE attention SET resolvedAt=? WHERE agentId=? AND requestId IS NULL AND resolvedAt IS NULL').run(Date.now(), agentId);
|
|
107
108
|
else if (timestamp !== null)
|
|
108
109
|
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
110
|
resolution(serverId, agentId, requestId, generation, response, now = Date.now()) { const occurrence = this.currentOccurrence(serverId, agentId, requestId); if (occurrence?.generation === generation)
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { type Config, type Pair } from './config.js';
|
|
2
|
+
import { CloudClient } from './cloud-client.js';
|
|
3
|
+
import { EnrollmentFiles, type DiscoveryOptions } from './enrollment-files.js';
|
|
4
|
+
export declare const DEFAULT_API_ORIGIN = "https://moremote-cloud-ingress.pages.dev";
|
|
5
|
+
export interface LocalEnrollmentOptions {
|
|
6
|
+
clock?: () => number;
|
|
7
|
+
files?: (options: DiscoveryOptions) => EnrollmentFiles;
|
|
8
|
+
persist?: (directory: string, config: Config) => Promise<void>;
|
|
9
|
+
}
|
|
10
|
+
export type EnrollmentCloudFactory = (pair: Pair) => Pick<CloudClient, 'create'>;
|
|
11
|
+
export declare class LocalEnrollment {
|
|
12
|
+
private directory;
|
|
13
|
+
private options;
|
|
14
|
+
private files;
|
|
15
|
+
private config;
|
|
16
|
+
private cursor;
|
|
17
|
+
private readonly clock;
|
|
18
|
+
private readonly persist;
|
|
19
|
+
constructor(directory: string, options?: LocalEnrollmentOptions);
|
|
20
|
+
private storage;
|
|
21
|
+
cleanup(config: Config): Promise<void>;
|
|
22
|
+
cycle(config: Config, daemonServerId: string, cloud: EnrollmentCloudFactory): Promise<void>;
|
|
23
|
+
private response;
|
|
24
|
+
close(): void;
|
|
25
|
+
}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { saveConfig, validateOrigin } from './config.js';
|
|
2
|
+
import { makeOffer, tokenHash } from './pairing.js';
|
|
3
|
+
import { EnrollmentFiles } from './enrollment-files.js';
|
|
4
|
+
import { parseEnrollmentRequest, requestFingerprint } from './enrollment-protocol.js';
|
|
5
|
+
export const DEFAULT_API_ORIGIN = 'https://moremote-cloud-ingress.pages.dev';
|
|
6
|
+
// The runtime's existing serialized cycle owns this consumer and its Config.
|
|
7
|
+
// No watcher, background config writer, listener or official mutation is added.
|
|
8
|
+
export class LocalEnrollment {
|
|
9
|
+
directory;
|
|
10
|
+
options;
|
|
11
|
+
files;
|
|
12
|
+
config;
|
|
13
|
+
cursor = 0;
|
|
14
|
+
clock;
|
|
15
|
+
persist;
|
|
16
|
+
constructor(directory, options = {}) {
|
|
17
|
+
this.directory = directory;
|
|
18
|
+
this.options = options;
|
|
19
|
+
this.clock = options.clock ?? Date.now;
|
|
20
|
+
this.persist = options.persist ?? saveConfig;
|
|
21
|
+
}
|
|
22
|
+
storage(config) {
|
|
23
|
+
if (!config.localEnrollment || !config.daemonServerId)
|
|
24
|
+
return;
|
|
25
|
+
this.files ??= (this.options.files ?? (options => new EnrollmentFiles(options)))({ home: config.localEnrollment.home, stateDirectory: this.directory, daemonServerId: config.daemonServerId });
|
|
26
|
+
this.files.open(config.enrollmentRequests ?? []);
|
|
27
|
+
return this.files;
|
|
28
|
+
}
|
|
29
|
+
async cleanup(config) {
|
|
30
|
+
this.config = config;
|
|
31
|
+
const files = this.storage(config);
|
|
32
|
+
if (!files)
|
|
33
|
+
return;
|
|
34
|
+
const now = this.clock(), records = config.enrollmentRequests ?? [];
|
|
35
|
+
let changed = false;
|
|
36
|
+
for (const record of records) {
|
|
37
|
+
const pair = config.pairs.find(pair => pair.pairId === record.pairId);
|
|
38
|
+
if (!config.cloudEnabled || pair?.active || pair?.revokedAt !== undefined || pair?.relayRetiredAt !== undefined || now >= record.offer.expiresAt)
|
|
39
|
+
files.removeResponse(record);
|
|
40
|
+
if (config.cloudEnabled && now < record.offer.expiresAt && (pair?.revokedAt !== undefined || pair?.relayRetiredAt !== undefined))
|
|
41
|
+
files.writeResponse(record, this.response(record, 'disabled'));
|
|
42
|
+
if (pair?.active || now >= record.offer.expiresAt) {
|
|
43
|
+
const name = record.request.id + '.json';
|
|
44
|
+
try {
|
|
45
|
+
const file = files.readRequest(name);
|
|
46
|
+
if (file.text === record.bytes)
|
|
47
|
+
files.removeRequest(name, file.identity);
|
|
48
|
+
}
|
|
49
|
+
catch (error) {
|
|
50
|
+
if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT'))
|
|
51
|
+
throw error;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
const retained = records.filter(record => now < record.offer.expiresAt);
|
|
56
|
+
if (retained.length !== records.length) {
|
|
57
|
+
config.enrollmentRequests = retained;
|
|
58
|
+
changed = true;
|
|
59
|
+
}
|
|
60
|
+
if (changed)
|
|
61
|
+
await this.persist(this.directory, config);
|
|
62
|
+
}
|
|
63
|
+
async cycle(config, daemonServerId, cloud) {
|
|
64
|
+
if (!config.localEnrollment)
|
|
65
|
+
return;
|
|
66
|
+
if (!config.daemonServerId || config.daemonServerId !== daemonServerId)
|
|
67
|
+
throw Error('ENROLLMENT_DAEMON_MISMATCH');
|
|
68
|
+
await this.cleanup(config);
|
|
69
|
+
const files = this.storage(config);
|
|
70
|
+
const origin = validateOrigin(config.apiOrigin ?? DEFAULT_API_ORIGIN, false), now = this.clock();
|
|
71
|
+
files.publish(config.cloudEnabled, origin, now);
|
|
72
|
+
if (!config.cloudEnabled)
|
|
73
|
+
return;
|
|
74
|
+
const names = files.requestNames();
|
|
75
|
+
if (!names.length)
|
|
76
|
+
return;
|
|
77
|
+
const start = this.cursor % names.length, selected = [...names.slice(start), ...names.slice(0, start)].slice(0, 16);
|
|
78
|
+
this.cursor = (start + selected.length) % names.length;
|
|
79
|
+
let failure, creationAttempted = false;
|
|
80
|
+
for (const name of selected) {
|
|
81
|
+
try {
|
|
82
|
+
const file = files.readRequest(name), record = config.enrollmentRequests?.find(record => record.request.id === name.slice(0, -5));
|
|
83
|
+
if (record && record.bytes !== file.text) {
|
|
84
|
+
files.removeResponse(record);
|
|
85
|
+
throw Error('ENROLLMENT_REQUEST_CONFLICT');
|
|
86
|
+
}
|
|
87
|
+
if (file.text === '')
|
|
88
|
+
continue; // Official create/write is a two-step transaction.
|
|
89
|
+
const request = parseEnrollmentRequest(file.text);
|
|
90
|
+
if (request.id + '.json' !== name || request.daemonServerId !== daemonServerId)
|
|
91
|
+
throw Error('ENROLLMENT_DAEMON_MISMATCH');
|
|
92
|
+
if (request.expiresAt <= this.clock()) {
|
|
93
|
+
files.removeRequest(name, file.identity);
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
files.assertResponseAvailable(request.id, record);
|
|
97
|
+
if (request.issuedAt > this.clock())
|
|
98
|
+
throw Error('ENROLLMENT_REQUEST_FROM_FUTURE');
|
|
99
|
+
let owned = record;
|
|
100
|
+
if (!owned) {
|
|
101
|
+
if (creationAttempted)
|
|
102
|
+
continue;
|
|
103
|
+
if (config.pairs.some(pair => pair.automaticRequestId === request.id))
|
|
104
|
+
throw Error('ENROLLMENT_REQUEST_CONFLICT');
|
|
105
|
+
if (config.pairs.some(pair => pair.automaticClientId === request.clientId && pair.daemonServerId === daemonServerId && pair.revokedAt === undefined && pair.relayRetiredAt === undefined && (pair.active || pair.expiresAt === undefined || pair.expiresAt > this.clock())))
|
|
106
|
+
throw Error('ENROLLMENT_CLIENT_ALREADY_BOUND');
|
|
107
|
+
if (config.pairs.length >= 16 || (config.enrollmentRequests?.length ?? 0) >= 16)
|
|
108
|
+
throw Error('PAIRING_LIMIT');
|
|
109
|
+
const generated = makeOffer(origin, this.clock());
|
|
110
|
+
generated.pair.expiresAt = Math.min(generated.pair.expiresAt, request.expiresAt);
|
|
111
|
+
const pair = { ...generated.pair, daemonServerId, automaticClientId: request.clientId, automaticRequestId: request.id };
|
|
112
|
+
const offer = { ...generated.offer, version: 1, enrollmentToken: pair.enrollmentToken, expiresAt: pair.expiresAt };
|
|
113
|
+
const createBytes = JSON.stringify({ pairId: pair.pairId, hostTokenHash: tokenHash(pair.hostToken), enrollmentTokenHash: tokenHash(offer.enrollmentToken), expiresAt: offer.expiresAt });
|
|
114
|
+
owned = { request, bytes: file.text, fingerprint: requestFingerprint(file.text), pairId: pair.pairId, offer, createBytes, created: false };
|
|
115
|
+
config.pairs.push(pair);
|
|
116
|
+
(config.enrollmentRequests ??= []).push(owned);
|
|
117
|
+
await this.persist(this.directory, config); // Original keys/request precede all cloud I/O.
|
|
118
|
+
}
|
|
119
|
+
const pair = config.pairs.find(pair => pair.pairId === owned.pairId);
|
|
120
|
+
if (!pair)
|
|
121
|
+
throw Error('ENROLLMENT_PAIR_MISSING');
|
|
122
|
+
if (pair.active) {
|
|
123
|
+
files.removeResponse(owned);
|
|
124
|
+
files.removeRequest(name, file.identity);
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
if (pair.revokedAt !== undefined || pair.relayRetiredAt !== undefined) {
|
|
128
|
+
files.writeResponse(owned, this.response(owned, 'disabled'));
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
if (!owned.created) {
|
|
132
|
+
if (creationAttempted)
|
|
133
|
+
continue;
|
|
134
|
+
creationAttempted = true;
|
|
135
|
+
await cloud(pair).create(JSON.parse(owned.createBytes), AbortSignal.timeout(3000));
|
|
136
|
+
owned.created = true;
|
|
137
|
+
await this.persist(this.directory, config);
|
|
138
|
+
}
|
|
139
|
+
// An unknown create acknowledgement retries the same original body. Recheck
|
|
140
|
+
// the immutable local request and deadline after network/persistence awaits.
|
|
141
|
+
if (this.clock() >= owned.offer.expiresAt) {
|
|
142
|
+
files.removeResponse(owned);
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
if (files.readRequest(name).text !== owned.bytes) {
|
|
146
|
+
files.removeResponse(owned);
|
|
147
|
+
throw Error('ENROLLMENT_REQUEST_CONFLICT');
|
|
148
|
+
}
|
|
149
|
+
files.writeResponse(owned, { ...this.response(owned, 'offer'), offer: owned.offer });
|
|
150
|
+
}
|
|
151
|
+
catch (error) {
|
|
152
|
+
failure ??= error;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
if (failure)
|
|
156
|
+
throw failure;
|
|
157
|
+
}
|
|
158
|
+
response(record, status) { return { version: 1, id: record.request.id, clientId: record.request.clientId, daemonServerId: record.request.daemonServerId, expiresAt: record.offer.expiresAt, status }; }
|
|
159
|
+
close() { this.files?.close(this.config?.enrollmentRequests ?? []); this.files = undefined; }
|
|
160
|
+
}
|
|
@@ -1,18 +1,65 @@
|
|
|
1
1
|
import type { DaemonClient } from '@getpaseo/client/internal/daemon-client';
|
|
2
|
-
import type { ServerInfoStatusPayload } from '@getpaseo/protocol/messages';
|
|
2
|
+
import type { ServerInfoStatusPayload, AgentSnapshotPayload, ProviderUsage } from '@getpaseo/protocol/messages';
|
|
3
3
|
import type { Config, Pair } from './config.js';
|
|
4
4
|
import type { Command, OfficialOperations } from './operations.js';
|
|
5
|
-
import { type ReceiptState, type OperationJournal } from './journal.js';
|
|
5
|
+
import { type ReceiptState, type OperationJournal, type Occurrence } from './journal.js';
|
|
6
6
|
import { type Evidence } from './evidence.js';
|
|
7
7
|
export interface Attention {
|
|
8
8
|
agentId: string;
|
|
9
9
|
requestId?: string;
|
|
10
10
|
requestBinding?: string;
|
|
11
|
+
occurrence?: Occurrence;
|
|
11
12
|
kind: 'finished' | 'question' | 'permission' | 'error';
|
|
12
13
|
timestamp: number;
|
|
13
14
|
}
|
|
14
15
|
export declare function localListen(home: string): string;
|
|
15
16
|
export declare function readLocalCredentialForTarget(home: string, target: string): string | undefined;
|
|
17
|
+
export declare function projectTask(a: AgentSnapshotPayload): {
|
|
18
|
+
agentId: string;
|
|
19
|
+
provider: string;
|
|
20
|
+
title: string | null;
|
|
21
|
+
status: "error" | "running" | "idle" | "closed" | "initializing";
|
|
22
|
+
createdAt: string;
|
|
23
|
+
updatedAt: string;
|
|
24
|
+
lastUserMessageAt: string | null;
|
|
25
|
+
activeTurnStartedAt: string | null;
|
|
26
|
+
cwd: string | null;
|
|
27
|
+
requiresAttention: boolean;
|
|
28
|
+
attentionReason: "permission" | "error" | "finished" | null;
|
|
29
|
+
pendingRequests: {
|
|
30
|
+
requestId: string;
|
|
31
|
+
request: import("@getpaseo/protocol/agent-types").AgentPermissionRequest;
|
|
32
|
+
}[];
|
|
33
|
+
};
|
|
34
|
+
export interface OfficialUsage {
|
|
35
|
+
fetchedAt: string;
|
|
36
|
+
providers: ProviderUsage[];
|
|
37
|
+
}
|
|
38
|
+
export declare function projectUsage(u: OfficialUsage): {
|
|
39
|
+
fetchedAt: string;
|
|
40
|
+
providers: {
|
|
41
|
+
providerId: string;
|
|
42
|
+
displayName: string;
|
|
43
|
+
status: "error" | "unavailable" | "available";
|
|
44
|
+
fetchedAt: string;
|
|
45
|
+
windows: {
|
|
46
|
+
id: string;
|
|
47
|
+
label: string;
|
|
48
|
+
usedPct: number | null;
|
|
49
|
+
remainingPct: number | null;
|
|
50
|
+
resetsAt: string | null;
|
|
51
|
+
}[];
|
|
52
|
+
balances: {
|
|
53
|
+
id: string;
|
|
54
|
+
label: string;
|
|
55
|
+
used: number | null;
|
|
56
|
+
remaining: number | null;
|
|
57
|
+
limit: number | null;
|
|
58
|
+
unit: "tokens" | "usd" | "credits" | "requests";
|
|
59
|
+
resetsAt: string | null;
|
|
60
|
+
}[] | undefined;
|
|
61
|
+
}[];
|
|
62
|
+
};
|
|
16
63
|
export declare class OfficialClient implements OfficialOperations {
|
|
17
64
|
readonly config: Config;
|
|
18
65
|
private journal?;
|
|
@@ -22,15 +69,27 @@ export declare class OfficialClient implements OfficialOperations {
|
|
|
22
69
|
private serverId;
|
|
23
70
|
private callbacks;
|
|
24
71
|
private unlisten;
|
|
72
|
+
private terminalReads;
|
|
73
|
+
private requestReads;
|
|
74
|
+
private observationOrder;
|
|
25
75
|
constructor(config: Config, journal?: OperationJournal | undefined);
|
|
26
76
|
connect(): Promise<void>;
|
|
27
77
|
info(): ServerInfoStatusPayload | null;
|
|
28
78
|
private emit;
|
|
79
|
+
private emitRequest;
|
|
80
|
+
private readTerminal;
|
|
81
|
+
private terminalTimestamp;
|
|
82
|
+
private fenceTerminalRead;
|
|
29
83
|
onAttention(callback: (event: Attention) => void): () => void;
|
|
30
84
|
requestContext(): {
|
|
31
85
|
serverId: string;
|
|
32
86
|
generation: `${string}-${string}-${string}-${string}-${string}`;
|
|
87
|
+
journal: OperationJournal | undefined;
|
|
33
88
|
};
|
|
89
|
+
private beginRequestRead;
|
|
90
|
+
private fenceRequestReads;
|
|
91
|
+
private acceptRequestRead;
|
|
92
|
+
private readCurrent;
|
|
34
93
|
current(agentId: string): Promise<{
|
|
35
94
|
id: string;
|
|
36
95
|
provider: string;
|
|
@@ -39,7 +98,7 @@ export declare class OfficialClient implements OfficialOperations {
|
|
|
39
98
|
createdAt: string;
|
|
40
99
|
updatedAt: string;
|
|
41
100
|
lastUserMessageAt: string | null;
|
|
42
|
-
status: "error" | "
|
|
101
|
+
status: "error" | "running" | "idle" | "closed" | "initializing";
|
|
43
102
|
capabilities: import("@getpaseo/protocol/agent-types").AgentCapabilityFlags;
|
|
44
103
|
currentModeId: string | null;
|
|
45
104
|
availableModes: import("@getpaseo/protocol/agent-types").AgentMode[];
|
|
@@ -83,12 +142,29 @@ export declare class OfficialClient implements OfficialOperations {
|
|
|
83
142
|
lastUsage?: import("@getpaseo/protocol/agent-types").AgentUsage | undefined;
|
|
84
143
|
lastError?: string | undefined;
|
|
85
144
|
requiresAttention?: boolean | undefined;
|
|
86
|
-
attentionReason?: "permission" | "
|
|
145
|
+
attentionReason?: "permission" | "error" | "finished" | null | undefined;
|
|
87
146
|
attentionTimestamp?: string | null | undefined;
|
|
88
147
|
archivedAt?: string | null | undefined;
|
|
89
148
|
providerUnavailable?: boolean | undefined;
|
|
90
149
|
internal?: boolean | undefined;
|
|
91
150
|
} | null>;
|
|
151
|
+
activityTask(agentId: string, signal?: AbortSignal): Promise<{
|
|
152
|
+
agentId: string;
|
|
153
|
+
provider: string;
|
|
154
|
+
title: string | null;
|
|
155
|
+
status: "error" | "running" | "idle" | "closed" | "initializing";
|
|
156
|
+
createdAt: string;
|
|
157
|
+
updatedAt: string;
|
|
158
|
+
lastUserMessageAt: string | null;
|
|
159
|
+
activeTurnStartedAt: string | null;
|
|
160
|
+
cwd: string | null;
|
|
161
|
+
requiresAttention: boolean;
|
|
162
|
+
attentionReason: "permission" | "error" | "finished" | null;
|
|
163
|
+
pendingRequests: {
|
|
164
|
+
requestId: string;
|
|
165
|
+
request: import("@getpaseo/protocol/agent-types").AgentPermissionRequest;
|
|
166
|
+
}[];
|
|
167
|
+
} | null>;
|
|
92
168
|
send(command: Extract<Command, {
|
|
93
169
|
type: 'send';
|
|
94
170
|
}>): Promise<void>;
|
|
@@ -104,11 +180,16 @@ export declare class OfficialClient implements OfficialOperations {
|
|
|
104
180
|
measuredAt: number;
|
|
105
181
|
tasks: {
|
|
106
182
|
agentId: string;
|
|
183
|
+
provider: string;
|
|
107
184
|
title: string | null;
|
|
108
|
-
status: "error" | "
|
|
185
|
+
status: "error" | "running" | "idle" | "closed" | "initializing";
|
|
186
|
+
createdAt: string;
|
|
109
187
|
updatedAt: string;
|
|
188
|
+
lastUserMessageAt: string | null;
|
|
189
|
+
activeTurnStartedAt: string | null;
|
|
190
|
+
cwd: string | null;
|
|
110
191
|
requiresAttention: boolean;
|
|
111
|
-
attentionReason: "permission" | "
|
|
192
|
+
attentionReason: "permission" | "error" | "finished" | null;
|
|
112
193
|
pendingRequests: {
|
|
113
194
|
requestId: string;
|
|
114
195
|
request: import("@getpaseo/protocol/agent-types").AgentPermissionRequest;
|
package/dist/official-client.js
CHANGED
|
@@ -45,6 +45,8 @@ export function readLocalCredentialForTarget(home, target) { try {
|
|
|
45
45
|
catch {
|
|
46
46
|
return undefined;
|
|
47
47
|
} }
|
|
48
|
+
export function projectTask(a) { return { agentId: a.id, provider: a.provider, title: a.title?.slice(0, 160) || null, status: a.status, createdAt: a.createdAt, updatedAt: a.updatedAt, lastUserMessageAt: a.lastUserMessageAt, activeTurnStartedAt: a.activeTurn?.startedAt ?? null, cwd: a.cwd?.slice(0, 1024) || null, requiresAttention: a.requiresAttention || false, attentionReason: a.attentionReason || null, pendingRequests: a.pendingPermissions.slice(0, 10).map(request => ({ requestId: request.id, request })) }; }
|
|
49
|
+
export function projectUsage(u) { return { fetchedAt: u.fetchedAt, providers: u.providers.slice(0, 16).map(p => ({ providerId: p.providerId.slice(0, 128), displayName: p.displayName.slice(0, 128), status: p.status, fetchedAt: p.fetchedAt || u.fetchedAt, windows: p.windows.slice(0, 8).map(w => ({ id: w.id.slice(0, 128), label: w.label.slice(0, 128), usedPct: w.usedPct ?? null, remainingPct: w.remainingPct ?? null, resetsAt: w.resetsAt ?? null })), balances: p.balances?.slice(0, 8).map(b => ({ id: b.id.slice(0, 128), label: b.label.slice(0, 128), used: b.used ?? null, remaining: b.remaining ?? null, limit: b.limit ?? null, unit: b.unit, resetsAt: b.resetsAt ?? null })) })) }; }
|
|
48
50
|
export class OfficialClient {
|
|
49
51
|
config;
|
|
50
52
|
journal;
|
|
@@ -54,6 +56,9 @@ export class OfficialClient {
|
|
|
54
56
|
serverId = '';
|
|
55
57
|
callbacks = new Set();
|
|
56
58
|
unlisten;
|
|
59
|
+
terminalReads = new Map();
|
|
60
|
+
requestReads = new Set();
|
|
61
|
+
observationOrder = 0;
|
|
57
62
|
constructor(config, journal) {
|
|
58
63
|
this.config = config;
|
|
59
64
|
this.journal = journal;
|
|
@@ -77,17 +82,30 @@ export class OfficialClient {
|
|
|
77
82
|
this.unlisten = this.sdk.subscribeRawMessages(message => {
|
|
78
83
|
if (message.type === 'agent_attention_required') {
|
|
79
84
|
const p = message.payload;
|
|
80
|
-
if (p.reason !== 'permission')
|
|
81
|
-
|
|
85
|
+
if (p.reason !== 'permission') {
|
|
86
|
+
const event = { agentId: p.agentId, kind: p.reason, timestamp: Date.parse(p.timestamp), observedOrder: ++this.observationOrder };
|
|
87
|
+
if (!Number.isSafeInteger(event.timestamp) || event.timestamp < 0)
|
|
88
|
+
return;
|
|
89
|
+
const pending = this.terminalReads.get(p.agentId);
|
|
90
|
+
if (pending) {
|
|
91
|
+
const latest = pending.next || pending.event;
|
|
92
|
+
if (event.timestamp < latest.timestamp || event.timestamp === latest.timestamp && event.kind === latest.kind)
|
|
93
|
+
return;
|
|
94
|
+
pending.next = event;
|
|
95
|
+
}
|
|
96
|
+
else
|
|
97
|
+
this.readTerminal(event);
|
|
98
|
+
}
|
|
82
99
|
}
|
|
83
100
|
if (message.type === 'agent_permission_request') {
|
|
84
101
|
const p = message.payload;
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
this.
|
|
102
|
+
this.fenceRequestReads(p.agentId, ++this.observationOrder);
|
|
103
|
+
void this.readCurrent(p.agentId, agent => { const r = agent?.pendingPermissions?.find(r => r.id === p.request.id); if (r)
|
|
104
|
+
this.emitRequest(p.agentId, r); }).catch(() => { });
|
|
88
105
|
}
|
|
89
106
|
if (message.type === 'agent_permission_resolved') {
|
|
90
107
|
const p = message.payload;
|
|
108
|
+
this.fenceRequestReads(p.agentId, ++this.observationOrder);
|
|
91
109
|
this.journal?.resolution(this.serverId, p.agentId, p.requestId, this.generation, p.resolution);
|
|
92
110
|
}
|
|
93
111
|
});
|
|
@@ -98,9 +116,93 @@ export class OfficialClient {
|
|
|
98
116
|
emit(event) { if (Number.isSafeInteger(event.timestamp) && event.timestamp >= 0)
|
|
99
117
|
for (const cb of this.callbacks)
|
|
100
118
|
cb(event); }
|
|
119
|
+
emitRequest(agentId, request) {
|
|
120
|
+
const occurrence = this.journal?.currentOccurrence(this.serverId, agentId, request.id);
|
|
121
|
+
if (this.journal && !occurrence)
|
|
122
|
+
return;
|
|
123
|
+
// Pending requests have independent lifetimes. The global attention clock can
|
|
124
|
+
// still describe an older finished turn; never use it to expire a new request.
|
|
125
|
+
// Runtime journals retain one observation clock per exact current occurrence.
|
|
126
|
+
this.emit({ agentId, requestId: request.id, occurrence, kind: request.kind === 'question' ? 'question' : 'permission', timestamp: occurrence?.createdAt ?? Date.now() });
|
|
127
|
+
}
|
|
128
|
+
readTerminal(event) {
|
|
129
|
+
const read = { event, valid: true, next: null };
|
|
130
|
+
this.terminalReads.set(event.agentId, read);
|
|
131
|
+
const complete = (agent) => {
|
|
132
|
+
if (this.terminalReads.get(event.agentId) !== read)
|
|
133
|
+
return;
|
|
134
|
+
this.terminalReads.delete(event.agentId);
|
|
135
|
+
if (read.next) {
|
|
136
|
+
this.readTerminal(read.next);
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
if (!read.valid)
|
|
140
|
+
return;
|
|
141
|
+
const timestamp = this.terminalTimestamp(agent, event);
|
|
142
|
+
if (timestamp !== null)
|
|
143
|
+
this.emit({ agentId: event.agentId, kind: event.kind, timestamp });
|
|
144
|
+
};
|
|
145
|
+
// At most one read and one latest event per agent; no retry without a new event.
|
|
146
|
+
// Terminal hydration is read-only; stale replies must not resync requests.
|
|
147
|
+
void this.sdk.fetchAgent({ agentId: event.agentId, timeout: 15000 }).then(value => complete(value?.agent || null)).catch(() => complete(null));
|
|
148
|
+
}
|
|
149
|
+
terminalTimestamp(agent, event) {
|
|
150
|
+
if (!agent || agent.id !== event.agentId || !agent.requiresAttention || agent.attentionReason !== event.kind || agent.activeTurn)
|
|
151
|
+
return null;
|
|
152
|
+
if (event.kind === 'finished' ? agent.status !== 'idle' && agent.status !== 'closed' : agent.status !== 'error')
|
|
153
|
+
return null;
|
|
154
|
+
const timestamp = Date.parse(agent.attentionTimestamp || '');
|
|
155
|
+
// Paseo sets attention before broadcasting; the raw clock is delivery time,
|
|
156
|
+
// not identity. A later attention or user turn cannot belong to this event.
|
|
157
|
+
if (!Number.isSafeInteger(timestamp) || timestamp < 0 || timestamp > event.timestamp || agent.lastUserMessageAt && Date.parse(agent.lastUserMessageAt) > event.timestamp)
|
|
158
|
+
return null;
|
|
159
|
+
return timestamp;
|
|
160
|
+
}
|
|
161
|
+
fenceTerminalRead(agentId, agent, observationOrder) {
|
|
162
|
+
const pending = this.terminalReads.get(agentId);
|
|
163
|
+
if (!pending)
|
|
164
|
+
return;
|
|
165
|
+
// A request begun before an event cannot retire that newer event, even if
|
|
166
|
+
// its older server snapshot arrives later. Keep the slot until it settles.
|
|
167
|
+
if (observationOrder >= pending.event.observedOrder && this.terminalTimestamp(agent, pending.event) === null)
|
|
168
|
+
pending.valid = false;
|
|
169
|
+
if (pending.next && observationOrder >= pending.next.observedOrder && this.terminalTimestamp(agent, pending.next) === null)
|
|
170
|
+
pending.next = null;
|
|
171
|
+
}
|
|
101
172
|
onAttention(callback) { this.callbacks.add(callback); return () => { this.callbacks.delete(callback); }; }
|
|
102
|
-
requestContext() { return { serverId: this.serverId, generation: this.generation }; }
|
|
103
|
-
|
|
173
|
+
requestContext() { return { serverId: this.serverId, generation: this.generation, journal: this.journal }; }
|
|
174
|
+
beginRequestRead(agentId) { const read = { agentId, observedOrder: ++this.observationOrder, stale: new Set() }; this.requestReads.add(read); return read; }
|
|
175
|
+
fenceRequestReads(agentId, observedOrder) {
|
|
176
|
+
// Track only in-flight reads, not an unbounded history of observed agents.
|
|
177
|
+
for (const read of this.requestReads)
|
|
178
|
+
if (read.observedOrder < observedOrder && (read.agentId === undefined || read.agentId === agentId))
|
|
179
|
+
read.stale.add(agentId);
|
|
180
|
+
}
|
|
181
|
+
acceptRequestRead(read, agentId) {
|
|
182
|
+
if (!this.requestReads.has(read) || read.stale.has(agentId))
|
|
183
|
+
return false;
|
|
184
|
+
this.fenceRequestReads(agentId, read.observedOrder);
|
|
185
|
+
return true;
|
|
186
|
+
}
|
|
187
|
+
async readCurrent(agentId, observe) {
|
|
188
|
+
const read = this.beginRequestRead(agentId);
|
|
189
|
+
try {
|
|
190
|
+
const value = await this.sdk.fetchAgent({ agentId, timeout: 15000 });
|
|
191
|
+
if (!this.acceptRequestRead(read, agentId))
|
|
192
|
+
return null;
|
|
193
|
+
const agent = value?.agent || null;
|
|
194
|
+
this.fenceTerminalRead(agentId, agent, read.observedOrder);
|
|
195
|
+
this.journal?.syncRequests(this.serverId, agentId, this.generation, agent?.pendingPermissions || []);
|
|
196
|
+
// Observation, journal synchronization and notification share one fence.
|
|
197
|
+
observe?.(agent);
|
|
198
|
+
return agent;
|
|
199
|
+
}
|
|
200
|
+
finally {
|
|
201
|
+
this.requestReads.delete(read);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
async current(agentId) { return this.readCurrent(agentId); }
|
|
205
|
+
async activityTask(agentId, signal) { signal?.throwIfAborted(); const observationOrder = ++this.observationOrder; const value = await this.sdk.fetchAgent({ agentId, timeout: 250 }); signal?.throwIfAborted(); this.fenceTerminalRead(agentId, value?.agent || null, observationOrder); return value?.agent ? projectTask(value.agent) : null; }
|
|
104
206
|
async send(command) { if (!this.sdk.isConnected)
|
|
105
207
|
throw Error('OFFICIAL_DISCONNECTED'); await this.sdk.sendAgentMessage(command.agentId, command.text, { messageId: command.messageId }); }
|
|
106
208
|
async permission(command) { if (!this.sdk.isConnected)
|
|
@@ -129,34 +231,35 @@ export class OfficialClient {
|
|
|
129
231
|
const info = this.info();
|
|
130
232
|
if (!info)
|
|
131
233
|
throw Error('OFFICIAL_IDENTITY_UNAVAILABLE');
|
|
132
|
-
const
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
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 });
|
|
234
|
+
const read = this.beginRequestRead();
|
|
235
|
+
try {
|
|
236
|
+
const result = await this.sdk.fetchAgents({ page: { limit: LIMITS.tasks }, filter: { includeArchived: false, includeInternal: false }, sort: [{ key: 'updated_at', direction: 'desc' }], timeout: 15000 });
|
|
237
|
+
const agents = result.entries.slice(0, LIMITS.tasks).map(entry => entry.agent).filter(agent => this.acceptRequestRead(read, agent.id));
|
|
238
|
+
for (const a of agents) {
|
|
239
|
+
this.fenceTerminalRead(a.id, a, read.observedOrder);
|
|
240
|
+
this.journal?.syncRequests(this.serverId, a.id, this.generation, a.pendingPermissions);
|
|
241
|
+
this.journal?.syncAttention(a.id, a.requiresAttention === true, a.attentionTimestamp ? Date.parse(a.attentionTimestamp) : null);
|
|
147
242
|
}
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
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 })) })) };
|
|
243
|
+
for (const a of agents) {
|
|
244
|
+
for (const request of a.pendingPermissions)
|
|
245
|
+
this.emitRequest(a.id, request);
|
|
246
|
+
if (a.requiresAttention && a.attentionReason && a.attentionReason !== 'permission' && a.attentionTimestamp)
|
|
247
|
+
this.emit({ agentId: a.id, kind: a.attentionReason, timestamp: Date.parse(a.attentionTimestamp) });
|
|
154
248
|
}
|
|
155
|
-
|
|
156
|
-
|
|
249
|
+
let usage = null;
|
|
250
|
+
if (info.features?.providerUsageList) {
|
|
251
|
+
try {
|
|
252
|
+
usage = projectUsage(await this.sdk.listProviderUsage());
|
|
253
|
+
}
|
|
254
|
+
catch {
|
|
255
|
+
usage = null;
|
|
256
|
+
}
|
|
157
257
|
}
|
|
258
|
+
return { version: 1, daemonServerId: info.serverId, hostName: (info.hostname || hostname()).slice(0, 256), measuredAt: Date.now(), tasks: agents.map(projectTask), usage };
|
|
259
|
+
}
|
|
260
|
+
finally {
|
|
261
|
+
this.requestReads.delete(read);
|
|
158
262
|
}
|
|
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
263
|
}
|
|
161
|
-
async close() { this.unlisten?.(); await this.subscription?.release().catch(() => { }); await this.sdk.close(); }
|
|
264
|
+
async close() { this.terminalReads.clear(); this.requestReads.clear(); this.unlisten?.(); await this.subscription?.release().catch(() => { }); await this.sdk.close(); }
|
|
162
265
|
}
|
package/dist/operations.d.ts
CHANGED
package/dist/operations.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { exact, object, text, LIMITS } from './limits.js';
|
|
2
2
|
import { decode, openEnvelope, sealEnvelope, validateEnvelope } from './crypto.js';
|
|
3
|
+
import { canonical, digest } from './journal.js';
|
|
3
4
|
import { occurrenceBinding } from './bindings.js';
|
|
4
5
|
import { validatePermissionInput } from './permission.js';
|
|
5
6
|
import { evidenceForCommand } from './evidence.js';
|
|
@@ -57,10 +58,29 @@ export function validateCommand(value, id, current) {
|
|
|
57
58
|
}
|
|
58
59
|
return c;
|
|
59
60
|
}
|
|
60
|
-
export async function boundCurrent(ctx, agentId) {
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
return
|
|
61
|
+
export async function boundCurrent(ctx, agentId) {
|
|
62
|
+
const current = await ctx.official.current(agentId);
|
|
63
|
+
if (!current)
|
|
64
|
+
return null;
|
|
65
|
+
const source = ctx.official.requestContext?.();
|
|
66
|
+
if (!source)
|
|
67
|
+
return current;
|
|
68
|
+
if (source.journal && source.journal !== ctx.journal)
|
|
69
|
+
throw Error('REQUEST_JOURNAL_MISMATCH');
|
|
70
|
+
const requests = current.pendingPermissions || [];
|
|
71
|
+
// A journal-owning adapter synchronizes before resolving current(). Repeating
|
|
72
|
+
// that write here could restore an older response after a newer observation.
|
|
73
|
+
if (!source.journal)
|
|
74
|
+
ctx.journal.syncRequests(source.serverId, agentId, source.generation, requests);
|
|
75
|
+
return { ...current, pendingPermissions: await Promise.all(requests.map(async (request) => {
|
|
76
|
+
const unbound = { ...request, occurrence: undefined, requestBinding: undefined };
|
|
77
|
+
const occurrence = ctx.journal.currentOccurrence(source.serverId, agentId, request.id);
|
|
78
|
+
if (!occurrence || occurrence.generation !== source.generation || occurrence.fingerprint !== digest(canonical(request)))
|
|
79
|
+
return unbound;
|
|
80
|
+
const requestBinding = await occurrenceBinding(ctx.pair, occurrence);
|
|
81
|
+
return ctx.journal.isCurrent(occurrence) ? { ...request, occurrence, requestBinding } : unbound;
|
|
82
|
+
})) };
|
|
83
|
+
}
|
|
64
84
|
async function outcome(ctx, e, state, now, code) {
|
|
65
85
|
const old = ctx.journal.get(e.pairId, e.id);
|
|
66
86
|
if (old.state === 'accepted' && state === 'unknown')
|
package/dist/projection.d.ts
CHANGED
|
@@ -9,11 +9,16 @@ export declare function projectSnapshot(source: Awaited<ReturnType<OfficialClien
|
|
|
9
9
|
request: import("@getpaseo/protocol/agent-types").AgentPermissionRequest;
|
|
10
10
|
}[];
|
|
11
11
|
agentId: string;
|
|
12
|
+
provider: string;
|
|
12
13
|
title: string | null;
|
|
13
|
-
status: "error" | "
|
|
14
|
+
status: "error" | "running" | "idle" | "closed" | "initializing";
|
|
15
|
+
createdAt: string;
|
|
14
16
|
updatedAt: string;
|
|
17
|
+
lastUserMessageAt: string | null;
|
|
18
|
+
activeTurnStartedAt: string | null;
|
|
19
|
+
cwd: string | null;
|
|
15
20
|
requiresAttention: boolean;
|
|
16
|
-
attentionReason: "permission" | "
|
|
21
|
+
attentionReason: "permission" | "error" | "finished" | null;
|
|
17
22
|
}[];
|
|
18
23
|
tasksTruncated: boolean;
|
|
19
24
|
version: number;
|