@ours.network/fleet 2.4.1 → 2.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/contrib/.claude-plugin/marketplace.json +1 -0
- package/contrib/claude-native/.claude-plugin/plugin.json +1 -0
- package/contrib/claude-native/hooks/hooks.json +1 -0
- package/contrib/claude-native/hooks/register.js +160 -0
- package/dist/application/fleet-query-service.d.ts +9 -0
- package/dist/application/fleet-query-service.js +36 -2
- package/dist/application/native-claude-conversation.d.ts +34 -0
- package/dist/application/native-claude-conversation.js +102 -0
- package/dist/application/native-codex-conversation.d.ts +20 -0
- package/dist/application/native-codex-conversation.js +68 -0
- package/dist/application/native-conversation.d.ts +120 -0
- package/dist/application/native-conversation.js +193 -0
- package/dist/application/native-conversations.d.ts +19 -0
- package/dist/application/native-conversations.js +74 -0
- package/dist/application/native-correspondence.d.ts +98 -0
- package/dist/application/native-correspondence.js +161 -0
- package/dist/application/native-mailbox.d.ts +14 -0
- package/dist/application/native-mailbox.js +77 -0
- package/dist/application/types.d.ts +7 -1
- package/dist/build-info.json +4 -4
- package/dist/cli.js +2 -0
- package/dist/native-codex-history.d.ts +9 -0
- package/dist/native-codex-history.js +62 -0
- package/dist/native-codex-wake.d.ts +25 -0
- package/dist/native-codex-wake.js +237 -0
- package/dist/native-participation-cli.d.ts +62 -0
- package/dist/native-participation-cli.js +279 -0
- package/dist/native-participation.d.ts +125 -0
- package/dist/native-participation.js +446 -0
- package/dist/web/runtime.js +49 -3
- package/docs/native-session-participation.md +193 -0
- package/package.json +4 -3
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { existsSync, readFileSync, readdirSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { atomicPrivateWrite } from '../agent-ours/state.js';
|
|
5
|
+
import { ConversationEventStore } from '../session/conversation-store.js';
|
|
6
|
+
import { startConversationReplay } from '../session/conversation-replay.js';
|
|
7
|
+
import { conversationTailPage } from './conversation-history.js';
|
|
8
|
+
import { FleetError } from './errors.js';
|
|
9
|
+
const textBlock = (text) => ({ type: 'text', text, bytes: Buffer.byteLength(text) });
|
|
10
|
+
/** Native Human conversation implementation of Fleet's existing conversation contract. It never controls the native terminal. */
|
|
11
|
+
export class NativeConversation {
|
|
12
|
+
options;
|
|
13
|
+
store;
|
|
14
|
+
generation;
|
|
15
|
+
seen = new Map();
|
|
16
|
+
commands = new Map();
|
|
17
|
+
completed = new Set();
|
|
18
|
+
nativeState = { status: 'idle', messages: [], queued: [] };
|
|
19
|
+
listeners = new Set();
|
|
20
|
+
revision = 0;
|
|
21
|
+
syncing;
|
|
22
|
+
sending = Promise.resolve();
|
|
23
|
+
timer;
|
|
24
|
+
follows = 0;
|
|
25
|
+
failed = false;
|
|
26
|
+
disposed = false;
|
|
27
|
+
constructor(options) {
|
|
28
|
+
this.options = options;
|
|
29
|
+
this.generation = `native-conversation:${options.cid}`;
|
|
30
|
+
this.store = new ConversationEventStore(join(options.directory, '.conversation'), { roleId: options.id });
|
|
31
|
+
for (let after;;) {
|
|
32
|
+
const page = this.store.page({ after, limit: 1000 });
|
|
33
|
+
for (const event of page.events) {
|
|
34
|
+
if (event.messageId?.startsWith('native:'))
|
|
35
|
+
this.seen.set(event.messageId, JSON.stringify(event.payload));
|
|
36
|
+
if (event.kind === 'turn.completed' && event.promptId)
|
|
37
|
+
this.completed.add(event.promptId);
|
|
38
|
+
}
|
|
39
|
+
if (!page.hasMore)
|
|
40
|
+
break;
|
|
41
|
+
after = page.nextCursor;
|
|
42
|
+
}
|
|
43
|
+
for (const file of readdirSync(options.directory).filter(n => /^command-[a-f0-9]+\.json$/.test(n))) {
|
|
44
|
+
const row = JSON.parse(readFileSync(join(options.directory, file), 'utf8'));
|
|
45
|
+
this.commands.set(row.clientId, row);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
commandPath(id) { return join(this.options.directory, `command-${createHash('sha256').update(id).digest('hex')}.json`); }
|
|
49
|
+
assertConnected() { if (this.disposed || !this.options.connected())
|
|
50
|
+
throw new FleetError('role_not_found', 'Native participant is disconnected'); }
|
|
51
|
+
state() {
|
|
52
|
+
const pending = [...this.commands.values()].filter(c => !this.completed.has(c.receipt.promptId));
|
|
53
|
+
const active = pending.filter(c => this.nativeState.messages.some(m => m.clientId === c.clientId));
|
|
54
|
+
return { sessionGeneration: this.generation, stateRevision: this.revision, ledgerBarrier: Number(this.store.lastCursor() ?? 0),
|
|
55
|
+
alive: !this.disposed && this.options.connected(), readiness: !this.options.connected() ? 'offline' : this.nativeState.status === 'unavailable' ? 'failed' : this.nativeState.status === 'waiting' ? 'awaiting_permission' : this.nativeState.status === 'busy' ? 'running' : 'idle',
|
|
56
|
+
queueDepth: pending.length - active.length, pendingPermissionIds: [], pendingPermissions: [], commands: [], historyDegraded: this.store.degraded,
|
|
57
|
+
pendingPrompts: pending.map(c => ({ promptId: c.receipt.promptId, source: 'owner_admin_console', admittedAt: c.receipt.acceptedAt, bytes: 0 })),
|
|
58
|
+
pendingPromptCount: pending.length, activePromptIds: active.map(c => c.receipt.promptId), ...(this.failed ? { observationFailure: 'capture_failed' } : {}) };
|
|
59
|
+
}
|
|
60
|
+
changed() { this.revision++; for (const listener of this.listeners)
|
|
61
|
+
listener(this.state()); }
|
|
62
|
+
async describe() { return { backend: this.options.harness === 'codex' ? 'codex-app-server' : 'acp', protocolVersion: 3, features: ['conversation_v3', 'conversation_live_complete', ...(this.options.correspondence ? ['agent_correspondence'] : [])], snapshot: await this.snapshot() }; }
|
|
63
|
+
async snapshot() { return { backend: this.options.harness === 'codex' ? 'codex-app-server' : 'acp', alive: this.options.connected(), readiness: !this.options.connected() || this.nativeState.status === 'unavailable' ? 'failed' : this.nativeState.status === 'idle' ? 'idle' : 'running', sessionId: this.generation }; }
|
|
64
|
+
async agentContacts() { this.assertConnected(); if (!this.options.correspondence)
|
|
65
|
+
throw new FleetError('capability_unavailable', 'Native correspondence unavailable'); return this.options.correspondence(); }
|
|
66
|
+
async agentHistory(request) { this.assertConnected(); if (!/^[a-f0-9]{64}$/i.test(request.peer_cid) || !Number.isInteger(request.limit ?? 100) || (request.limit ?? 100) < 1 || (request.limit ?? 100) > 1000 || !Number.isInteger(request.before_seq ?? 0) || (request.before_seq ?? 0) < 0)
|
|
67
|
+
throw new FleetError('invalid_request', 'Invalid history query'); if (!this.options.correspondence)
|
|
68
|
+
throw new FleetError('capability_unavailable', 'Native correspondence unavailable'); return this.options.correspondence(request); }
|
|
69
|
+
async recentOutput() { return { events: [], truncated: false }; }
|
|
70
|
+
async sendText(text) { const receipt = await this.submitPromptV2({ commandId: randomUUID(), text, actorBrowserSession: 'legacy', source: 'owner_admin_console' }); return { accepted: true, promptId: receipt.promptId, queuedBehind: 0, terminalOutcomeKnown: false, detail: 'Native input queued; terminal remains independently controlled' }; }
|
|
71
|
+
async sync() {
|
|
72
|
+
if (this.syncing)
|
|
73
|
+
return this.syncing;
|
|
74
|
+
this.syncing = this.sending.then(async () => {
|
|
75
|
+
this.assertConnected();
|
|
76
|
+
const snapshot = await this.options.native.read();
|
|
77
|
+
this.assertConnected();
|
|
78
|
+
this.nativeState = snapshot;
|
|
79
|
+
for (const message of snapshot.messages) {
|
|
80
|
+
if (message.clientId && this.commands.has(message.clientId))
|
|
81
|
+
continue;
|
|
82
|
+
const messageId = `native:${message.id}`;
|
|
83
|
+
const payload = { role: message.role, content: textBlock(message.text) };
|
|
84
|
+
const digest = JSON.stringify(payload);
|
|
85
|
+
if (this.seen.get(messageId) === digest)
|
|
86
|
+
continue;
|
|
87
|
+
this.store.append({ sessionGeneration: this.generation, kind: 'message.replace', messageId,
|
|
88
|
+
source: message.role === 'user' ? 'local_console' : 'agent', ...(message.at ? { at: message.at } : {}), payload });
|
|
89
|
+
this.seen.set(messageId, digest);
|
|
90
|
+
}
|
|
91
|
+
for (const command of this.commands.values()) {
|
|
92
|
+
if (this.completed.has(command.receipt.promptId))
|
|
93
|
+
continue;
|
|
94
|
+
// A queue acknowledgement is not a completed native turn. Observing the
|
|
95
|
+
// correlated native input and an idle runtime proves it left execution.
|
|
96
|
+
const finished = snapshot.finished?.find(item => item.clientId === command.clientId);
|
|
97
|
+
if (command.status === 'intent' && (snapshot.messages.some(m => m.clientId === command.clientId) || snapshot.queued.includes(command.clientId))) {
|
|
98
|
+
command.status = 'sent';
|
|
99
|
+
atomicPrivateWrite(this.commandPath(command.receipt.commandId), command);
|
|
100
|
+
}
|
|
101
|
+
if (finished) {
|
|
102
|
+
this.store.append({ sessionGeneration: this.generation, kind: 'turn.completed', promptId: command.receipt.promptId, payload: { outcome: finished.outcome } });
|
|
103
|
+
this.completed.add(command.receipt.promptId);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
this.failed = false;
|
|
107
|
+
this.changed();
|
|
108
|
+
}).catch(error => { this.failed = true; this.changed(); throw error; }).finally(() => { this.syncing = undefined; });
|
|
109
|
+
this.sending = this.syncing.then(() => { }, () => { });
|
|
110
|
+
return this.syncing;
|
|
111
|
+
}
|
|
112
|
+
async conversationPage(request = {}) { await this.sync(); return { ...this.store.page(request), snapshot: this.state() }; }
|
|
113
|
+
async conversationTail(request = {}) { await this.sync(); return conversationTailPage(this.options.directory, request, this.state(), undefined, request.signal); }
|
|
114
|
+
async submitPromptV2(request) {
|
|
115
|
+
await this.sync();
|
|
116
|
+
const run = async () => {
|
|
117
|
+
this.assertConnected();
|
|
118
|
+
if (request.requireIdle)
|
|
119
|
+
throw new FleetError('capability_unavailable', 'Atomic idle-only admission is unavailable for native sessions');
|
|
120
|
+
if (request.expectedSessionGeneration && request.expectedSessionGeneration !== this.generation)
|
|
121
|
+
throw new FleetError('stale_state', 'Participant generation changed');
|
|
122
|
+
if (!request.commandId || !request.text.trim())
|
|
123
|
+
throw new FleetError('invalid_request', 'A command ID and nonempty message are required');
|
|
124
|
+
const digest = ConversationEventStore.bodyDigest(request.text);
|
|
125
|
+
const path = this.commandPath(request.commandId);
|
|
126
|
+
if (existsSync(path)) {
|
|
127
|
+
const previous = JSON.parse(readFileSync(path, 'utf8'));
|
|
128
|
+
if (previous.digest !== digest)
|
|
129
|
+
throw new FleetError('idempotency_conflict', 'Command ID was already used for different text');
|
|
130
|
+
if (previous.status !== 'sent')
|
|
131
|
+
throw new FleetError('conflict', 'Native input outcome is unknown. Check the terminal before sending a new command.');
|
|
132
|
+
return previous.receipt;
|
|
133
|
+
}
|
|
134
|
+
if (this.nativeState.status === 'unavailable')
|
|
135
|
+
throw new FleetError('capability_unavailable', 'History is available; load the Ours native Claude plugin to send input to this session');
|
|
136
|
+
// Finish any concurrent history capture before admitting a send, so its outgoing row cannot race the receipt.
|
|
137
|
+
const promptId = randomUUID();
|
|
138
|
+
const event = this.store.append({ sessionGeneration: this.generation, kind: 'prompt.admitted', promptId, commandId: request.commandId, source: 'owner_admin_console', actor: { browserSession: request.actorBrowserSession }, payload: { text: textBlock(request.text), queuedBehind: 0 } });
|
|
139
|
+
const receipt = { commandId: request.commandId, promptId, state: 'queued', queuedBehind: 0, acceptedAt: event.at, eventCursor: String(event.seq), sessionGeneration: this.generation };
|
|
140
|
+
const clientId = `ours-fleet-human:${this.options.cid}:${request.commandId}`;
|
|
141
|
+
const command = { digest, receipt, status: 'intent', clientId };
|
|
142
|
+
atomicPrivateWrite(path, command);
|
|
143
|
+
this.commands.set(clientId, command);
|
|
144
|
+
try {
|
|
145
|
+
this.assertConnected();
|
|
146
|
+
await this.options.native.submit(request.text, clientId);
|
|
147
|
+
command.status = 'sent';
|
|
148
|
+
atomicPrivateWrite(path, command);
|
|
149
|
+
this.changed();
|
|
150
|
+
return receipt;
|
|
151
|
+
}
|
|
152
|
+
catch (error) {
|
|
153
|
+
this.failed = true;
|
|
154
|
+
this.changed();
|
|
155
|
+
throw error;
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
const result = this.sending.then(run);
|
|
159
|
+
this.sending = result.then(() => { }, () => { });
|
|
160
|
+
return result;
|
|
161
|
+
}
|
|
162
|
+
observeConversation(listener) { this.listeners.add(listener); return { snapshot: this.state(), unsubscribe: () => { this.listeners.delete(listener); } }; }
|
|
163
|
+
subscribeConversation(listener) { return this.store.subscribe(listener); }
|
|
164
|
+
subscribeConversationFailure(listener) { return this.store.subscribeFailure(listener); }
|
|
165
|
+
replayConversation(request) { return this.store.replay(request); }
|
|
166
|
+
async followConversation(request) {
|
|
167
|
+
await this.sync();
|
|
168
|
+
this.follows++;
|
|
169
|
+
if (!this.timer) {
|
|
170
|
+
this.timer = setInterval(() => { if (!this.options.connected())
|
|
171
|
+
this.changed();
|
|
172
|
+
else
|
|
173
|
+
void this.sending.then(() => this.sync()).catch(() => { }); }, 1000);
|
|
174
|
+
this.timer.unref();
|
|
175
|
+
}
|
|
176
|
+
let release;
|
|
177
|
+
if ('controller' in request) {
|
|
178
|
+
const follow = startConversationReplay(this, request, { replay: request.onReplay, ready: request.onReady, event: request.onEvent, state: request.onState, close: request.onClose });
|
|
179
|
+
release = follow.close;
|
|
180
|
+
}
|
|
181
|
+
else {
|
|
182
|
+
request.onPage({ ...this.store.page({ after: request.after }), snapshot: this.state() });
|
|
183
|
+
release = this.store.subscribe(request.onEvent);
|
|
184
|
+
}
|
|
185
|
+
let closed = false;
|
|
186
|
+
return { close: () => { if (closed)
|
|
187
|
+
return; closed = true; release(); if (!--this.follows) {
|
|
188
|
+
clearInterval(this.timer);
|
|
189
|
+
this.timer = undefined;
|
|
190
|
+
} } };
|
|
191
|
+
}
|
|
192
|
+
close() { this.disposed = true; clearInterval(this.timer); this.changed(); this.store.close(); this.listeners.clear(); }
|
|
193
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { NativeConversation } from './native-conversation.js';
|
|
2
|
+
import type { ConversationRoleObservation, ConversationRoleState } from './conversation-role-observer.js';
|
|
3
|
+
/** The web process owns projections, while native participation remains the authority for membership. */
|
|
4
|
+
export declare class NativeConversations {
|
|
5
|
+
private sessions;
|
|
6
|
+
private registry?;
|
|
7
|
+
initialize(): Promise<void>;
|
|
8
|
+
list(): {
|
|
9
|
+
harness: import("../native-participation.js").NativeHarness;
|
|
10
|
+
cid: string;
|
|
11
|
+
name: string;
|
|
12
|
+
lastSeen: number;
|
|
13
|
+
title?: string;
|
|
14
|
+
cwd?: string;
|
|
15
|
+
}[];
|
|
16
|
+
session(id: string): Promise<NativeConversation | undefined>;
|
|
17
|
+
observe(id: string, listener: (state: ConversationRoleState) => void): ConversationRoleObservation;
|
|
18
|
+
close(): void;
|
|
19
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { NativeParticipation, nativeHostProfile, nativeParticipationRoot } from '../native-participation.js';
|
|
4
|
+
import { FleetError } from './errors.js';
|
|
5
|
+
import { NativeConversation } from './native-conversation.js';
|
|
6
|
+
import { NativeClaudeConversation } from './native-claude-conversation.js';
|
|
7
|
+
import { NativeCodexConversation } from './native-codex-conversation.js';
|
|
8
|
+
/** The web process owns projections, while native participation remains the authority for membership. */
|
|
9
|
+
export class NativeConversations {
|
|
10
|
+
sessions = new Map();
|
|
11
|
+
registry;
|
|
12
|
+
async initialize() { if (!this.registry)
|
|
13
|
+
this.registry = new NativeParticipation(await nativeHostProfile()); }
|
|
14
|
+
list() { return this.registry?.list() ?? []; }
|
|
15
|
+
async session(id) {
|
|
16
|
+
const row = this.list().find(row => row.name === id), grant = this.registry?.authorization();
|
|
17
|
+
if (!row || !grant)
|
|
18
|
+
return undefined;
|
|
19
|
+
const key = `${grant.rootCid}:${row.cid}:${grant.grant}`;
|
|
20
|
+
let session = this.sessions.get(key);
|
|
21
|
+
if (!session) {
|
|
22
|
+
const guard = () => { if (!this.list().some(item => item.name === id && item.cid === row.cid) || this.registry?.authorization()?.grant !== grant.grant)
|
|
23
|
+
throw new FleetError('role_not_found', 'Native participant is disconnected'); };
|
|
24
|
+
const locator = this.registry?.participant(id);
|
|
25
|
+
if (row.harness === 'codex' && locator && grant.codexSocket) {
|
|
26
|
+
session = new NativeConversation({ id, cid: row.cid, harness: row.harness, correspondence: (request) => this.registry.correspondence(id, request),
|
|
27
|
+
directory: join(nativeParticipationRoot(), 'native-conversations', createHash('sha256').update(key).digest('hex')),
|
|
28
|
+
connected: () => { try {
|
|
29
|
+
guard();
|
|
30
|
+
return true;
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return false;
|
|
34
|
+
} },
|
|
35
|
+
native: new NativeCodexConversation(grant.codexSocket, locator.nativeId, row.cid, id, guard) });
|
|
36
|
+
}
|
|
37
|
+
else if (locator) {
|
|
38
|
+
session = new NativeConversation({ id, cid: row.cid, harness: row.harness, correspondence: (request) => this.registry.correspondence(id, request),
|
|
39
|
+
directory: join(nativeParticipationRoot(), 'native-conversations', createHash('sha256').update(key).digest('hex')),
|
|
40
|
+
connected: () => { try {
|
|
41
|
+
guard();
|
|
42
|
+
return true;
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return false;
|
|
46
|
+
} },
|
|
47
|
+
native: new NativeClaudeConversation(join(nativeParticipationRoot(), 'native-conversations', createHash('sha256').update(key).digest('hex'), 'bridge'), locator.nativeId, guard) });
|
|
48
|
+
}
|
|
49
|
+
else
|
|
50
|
+
return undefined;
|
|
51
|
+
this.sessions.set(key, session);
|
|
52
|
+
}
|
|
53
|
+
return session;
|
|
54
|
+
}
|
|
55
|
+
observe(id, listener) {
|
|
56
|
+
const initial = this.list().find(row => row.name === id);
|
|
57
|
+
let state = { roleId: id, roleRevision: 0, roleLifetime: initial?.cid ?? id, availability: initial ? 'available' : 'missing', health: 'healthy', fallbackHarness: initial?.harness === 'codex' ? 'codex' : 'claude-code' };
|
|
58
|
+
const listeners = new Set();
|
|
59
|
+
const timer = setInterval(() => {
|
|
60
|
+
const row = this.list().find(row => row.name === id);
|
|
61
|
+
const availability = row ? 'available' : 'missing', lifetime = row?.cid ?? state.roleLifetime;
|
|
62
|
+
if (availability === state.availability && lifetime === state.roleLifetime)
|
|
63
|
+
return;
|
|
64
|
+
state = { ...state, availability, roleLifetime: lifetime, roleRevision: state.roleRevision + 1 };
|
|
65
|
+
listener({ ...state });
|
|
66
|
+
for (const fn of listeners)
|
|
67
|
+
fn({ ...state });
|
|
68
|
+
}, 1000);
|
|
69
|
+
timer.unref();
|
|
70
|
+
return { snapshot: () => ({ ...state }), subscribe(fn) { listeners.add(fn); return { snapshot: { ...state }, unsubscribe: () => { listeners.delete(fn); } }; }, dispose() { clearInterval(timer); listeners.clear(); } };
|
|
71
|
+
}
|
|
72
|
+
close() { for (const session of this.sessions.values())
|
|
73
|
+
session.close(); this.sessions.clear(); }
|
|
74
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { type ConversationReplayRequest } from '../session/conversation-replay.js';
|
|
2
|
+
import type { ConversationEventV1, ConversationObservationState, PromptReceipt } from '../session/conversation-types.js';
|
|
3
|
+
import type { SessionSnapshot } from '../session/types.js';
|
|
4
|
+
import type { RoleSessionControl, LegacyConversationFollowRequest, PassiveConversationFollow } from './session-control.js';
|
|
5
|
+
export interface NativeMail {
|
|
6
|
+
wire_id: string;
|
|
7
|
+
dir: 'in' | 'out';
|
|
8
|
+
text: string;
|
|
9
|
+
date?: string;
|
|
10
|
+
}
|
|
11
|
+
export interface NativeMailbox {
|
|
12
|
+
history(): Promise<NativeMail[]>;
|
|
13
|
+
send(text: string): Promise<{
|
|
14
|
+
wire_id: string | null;
|
|
15
|
+
}>;
|
|
16
|
+
}
|
|
17
|
+
interface Options {
|
|
18
|
+
id: string;
|
|
19
|
+
cid: string;
|
|
20
|
+
harness: 'claude' | 'codex';
|
|
21
|
+
directory: string;
|
|
22
|
+
connected(): boolean;
|
|
23
|
+
mailbox: NativeMailbox;
|
|
24
|
+
}
|
|
25
|
+
/** Mail-only implementation of Fleet's existing conversation contract. It never controls the native terminal. */
|
|
26
|
+
export declare class NativeCorrespondence implements RoleSessionControl {
|
|
27
|
+
private options;
|
|
28
|
+
private store;
|
|
29
|
+
private generation;
|
|
30
|
+
private seen;
|
|
31
|
+
private outgoing;
|
|
32
|
+
private listeners;
|
|
33
|
+
private revision;
|
|
34
|
+
private syncing?;
|
|
35
|
+
private sending;
|
|
36
|
+
private timer?;
|
|
37
|
+
private follows;
|
|
38
|
+
private failed;
|
|
39
|
+
private disposed;
|
|
40
|
+
constructor(options: Options);
|
|
41
|
+
private assertConnected;
|
|
42
|
+
private state;
|
|
43
|
+
private changed;
|
|
44
|
+
describe(): Promise<{
|
|
45
|
+
backend: "acp" | "codex-app-server";
|
|
46
|
+
protocolVersion: number;
|
|
47
|
+
features: string[];
|
|
48
|
+
snapshot: SessionSnapshot;
|
|
49
|
+
}>;
|
|
50
|
+
snapshot(): Promise<SessionSnapshot>;
|
|
51
|
+
recentOutput(): Promise<{
|
|
52
|
+
events: never[];
|
|
53
|
+
truncated: boolean;
|
|
54
|
+
}>;
|
|
55
|
+
sendText(text: string): Promise<{
|
|
56
|
+
accepted: boolean;
|
|
57
|
+
promptId: string;
|
|
58
|
+
queuedBehind: number;
|
|
59
|
+
terminalOutcomeKnown: boolean;
|
|
60
|
+
detail: string;
|
|
61
|
+
}>;
|
|
62
|
+
sync(): Promise<void>;
|
|
63
|
+
conversationPage(request?: {
|
|
64
|
+
after?: string;
|
|
65
|
+
limit?: number;
|
|
66
|
+
}): Promise<{
|
|
67
|
+
snapshot: ConversationObservationState;
|
|
68
|
+
events: ConversationEventV1[];
|
|
69
|
+
firstAvailableCursor?: string;
|
|
70
|
+
nextCursor?: string;
|
|
71
|
+
hasMore: boolean;
|
|
72
|
+
}>;
|
|
73
|
+
conversationTail(request?: {
|
|
74
|
+
before?: string;
|
|
75
|
+
limit?: number;
|
|
76
|
+
signal?: AbortSignal;
|
|
77
|
+
}): Promise<import("./conversation-history.js").ConversationTailPage>;
|
|
78
|
+
submitPromptV2(request: {
|
|
79
|
+
commandId: string;
|
|
80
|
+
text: string;
|
|
81
|
+
actorBrowserSession: string;
|
|
82
|
+
source: 'owner_admin_console';
|
|
83
|
+
expectedSessionGeneration?: string;
|
|
84
|
+
requireIdle?: boolean;
|
|
85
|
+
}): Promise<PromptReceipt>;
|
|
86
|
+
observeConversation(listener: (state: ConversationObservationState) => void): {
|
|
87
|
+
snapshot: ConversationObservationState;
|
|
88
|
+
unsubscribe: () => void;
|
|
89
|
+
};
|
|
90
|
+
subscribeConversation(listener: (event: ConversationEventV1) => void): () => void;
|
|
91
|
+
subscribeConversationFailure(listener: (generation: string) => void): () => void;
|
|
92
|
+
replayConversation(request: ConversationReplayRequest): AsyncGenerator<import("../session/conversation-replay.js").ConversationReplayPage, any, any>;
|
|
93
|
+
followConversation(request: LegacyConversationFollowRequest | PassiveConversationFollow): Promise<{
|
|
94
|
+
close: () => void;
|
|
95
|
+
}>;
|
|
96
|
+
close(): void;
|
|
97
|
+
}
|
|
98
|
+
export {};
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { existsSync, readFileSync, readdirSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { atomicPrivateWrite } from '../agent-ours/state.js';
|
|
5
|
+
import { ConversationEventStore } from '../session/conversation-store.js';
|
|
6
|
+
import { startConversationReplay } from '../session/conversation-replay.js';
|
|
7
|
+
import { conversationTailPage } from './conversation-history.js';
|
|
8
|
+
import { FleetError } from './errors.js';
|
|
9
|
+
const textBlock = (text) => ({ type: 'text', text, bytes: Buffer.byteLength(text) });
|
|
10
|
+
/** Mail-only implementation of Fleet's existing conversation contract. It never controls the native terminal. */
|
|
11
|
+
export class NativeCorrespondence {
|
|
12
|
+
options;
|
|
13
|
+
store;
|
|
14
|
+
generation;
|
|
15
|
+
seen = new Set();
|
|
16
|
+
outgoing = new Set();
|
|
17
|
+
listeners = new Set();
|
|
18
|
+
revision = 0;
|
|
19
|
+
syncing;
|
|
20
|
+
sending = Promise.resolve();
|
|
21
|
+
timer;
|
|
22
|
+
follows = 0;
|
|
23
|
+
failed = false;
|
|
24
|
+
disposed = false;
|
|
25
|
+
constructor(options) {
|
|
26
|
+
this.options = options;
|
|
27
|
+
this.generation = `native-mail:${options.cid}`;
|
|
28
|
+
this.store = new ConversationEventStore(join(options.directory, '.conversation'), { roleId: options.id });
|
|
29
|
+
for (let after;;) {
|
|
30
|
+
const page = this.store.page({ after, limit: 1000 });
|
|
31
|
+
for (const event of page.events)
|
|
32
|
+
if (event.messageId?.startsWith('mail:'))
|
|
33
|
+
this.seen.add(event.messageId.slice(5));
|
|
34
|
+
if (!page.hasMore)
|
|
35
|
+
break;
|
|
36
|
+
after = page.nextCursor;
|
|
37
|
+
}
|
|
38
|
+
for (const file of readdirSync(options.directory).filter(n => /^command-[a-f0-9]+\.json$/.test(n))) {
|
|
39
|
+
const row = JSON.parse(readFileSync(join(options.directory, file), 'utf8'));
|
|
40
|
+
if (row.wireId)
|
|
41
|
+
this.outgoing.add(row.wireId);
|
|
42
|
+
}
|
|
43
|
+
// Receipt generations survive web restarts; unknown in-flight sends are not replayed.
|
|
44
|
+
for (const prompt of this.store.openPrompts())
|
|
45
|
+
this.store.append({ sessionGeneration: this.generation, kind: 'turn.completed', promptId: prompt.promptId, payload: { outcome: 'unknown_after_restart' } });
|
|
46
|
+
}
|
|
47
|
+
assertConnected() { if (this.disposed || !this.options.connected())
|
|
48
|
+
throw new FleetError('role_not_found', 'Native participant is disconnected'); }
|
|
49
|
+
state() {
|
|
50
|
+
return {
|
|
51
|
+
sessionGeneration: this.generation, stateRevision: this.revision, ledgerBarrier: Number(this.store.lastCursor() ?? 0),
|
|
52
|
+
alive: !this.disposed && this.options.connected(), readiness: this.options.connected() ? 'idle' : 'offline', queueDepth: 0, pendingPermissionIds: [],
|
|
53
|
+
pendingPrompts: [], pendingPromptCount: 0, activePromptIds: [], pendingPermissions: [], commands: [], historyDegraded: this.store.degraded,
|
|
54
|
+
...(this.failed ? { observationFailure: 'capture_failed' } : {}),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
changed() { this.revision++; for (const listener of this.listeners)
|
|
58
|
+
listener(this.state()); }
|
|
59
|
+
async describe() { return { backend: this.options.harness === 'codex' ? 'codex-app-server' : 'acp', protocolVersion: 3, features: ['conversation_v3', 'conversation_live_complete'], snapshot: await this.snapshot() }; }
|
|
60
|
+
async snapshot() { return { backend: this.options.harness === 'codex' ? 'codex-app-server' : 'acp', alive: this.options.connected(), readiness: this.options.connected() ? 'idle' : 'failed', sessionId: this.generation }; }
|
|
61
|
+
async recentOutput() { return { events: [], truncated: false }; }
|
|
62
|
+
async sendText(text) { const receipt = await this.submitPromptV2({ commandId: randomUUID(), text, actorBrowserSession: 'legacy', source: 'owner_admin_console' }); return { accepted: true, promptId: receipt.promptId, queuedBehind: 0, terminalOutcomeKnown: false, detail: 'Ours mail accepted; terminal remains independently controlled' }; }
|
|
63
|
+
async sync() {
|
|
64
|
+
if (this.syncing)
|
|
65
|
+
return this.syncing;
|
|
66
|
+
this.syncing = this.sending.then(async () => {
|
|
67
|
+
this.assertConnected();
|
|
68
|
+
const messages = await this.options.mailbox.history();
|
|
69
|
+
this.assertConnected();
|
|
70
|
+
for (const mail of messages) {
|
|
71
|
+
if (this.seen.has(mail.wire_id) || this.outgoing.has(mail.wire_id))
|
|
72
|
+
continue;
|
|
73
|
+
this.store.append({ sessionGeneration: this.generation, kind: 'message.replace', messageId: `mail:${mail.wire_id}`,
|
|
74
|
+
source: mail.dir === 'in' ? 'agent' : 'owner_admin_console', ...(mail.date ? { at: mail.date } : {}),
|
|
75
|
+
payload: { role: mail.dir === 'in' ? 'assistant' : 'user', content: textBlock(mail.text) } });
|
|
76
|
+
this.seen.add(mail.wire_id);
|
|
77
|
+
}
|
|
78
|
+
this.failed = false;
|
|
79
|
+
this.changed();
|
|
80
|
+
}).catch(error => { this.failed = true; this.changed(); throw error; }).finally(() => { this.syncing = undefined; });
|
|
81
|
+
this.sending = this.syncing.then(() => { }, () => { });
|
|
82
|
+
return this.syncing;
|
|
83
|
+
}
|
|
84
|
+
async conversationPage(request = {}) { await this.sync(); return { ...this.store.page(request), snapshot: this.state() }; }
|
|
85
|
+
async conversationTail(request = {}) { await this.sync(); return conversationTailPage(this.options.directory, request, this.state(), undefined, request.signal); }
|
|
86
|
+
async submitPromptV2(request) {
|
|
87
|
+
const run = async () => {
|
|
88
|
+
this.assertConnected();
|
|
89
|
+
if (request.requireIdle)
|
|
90
|
+
throw new FleetError('capability_unavailable', 'Native terminal idle state is controlled by its operator');
|
|
91
|
+
if (request.expectedSessionGeneration && request.expectedSessionGeneration !== this.generation)
|
|
92
|
+
throw new FleetError('stale_state', 'Participant generation changed');
|
|
93
|
+
if (!request.commandId || !request.text.trim())
|
|
94
|
+
throw new FleetError('invalid_request', 'A command ID and nonempty message are required');
|
|
95
|
+
const digest = ConversationEventStore.bodyDigest(request.text);
|
|
96
|
+
const path = join(this.options.directory, `command-${createHash('sha256').update(request.commandId).digest('hex')}.json`);
|
|
97
|
+
if (existsSync(path)) {
|
|
98
|
+
const previous = JSON.parse(readFileSync(path, 'utf8'));
|
|
99
|
+
if (previous.digest !== digest)
|
|
100
|
+
throw new FleetError('idempotency_conflict', 'Command ID was already used for different text');
|
|
101
|
+
if (previous.status !== 'sent')
|
|
102
|
+
throw new FleetError('conflict', 'Mail delivery outcome is unknown. Check correspondence before sending a new message.');
|
|
103
|
+
return previous.receipt;
|
|
104
|
+
}
|
|
105
|
+
// Finish any concurrent history capture before admitting a send, so its outgoing row cannot race the receipt.
|
|
106
|
+
const promptId = randomUUID();
|
|
107
|
+
const event = this.store.append({ sessionGeneration: this.generation, kind: 'prompt.admitted', promptId, commandId: request.commandId, source: 'owner_admin_console', actor: { browserSession: request.actorBrowserSession }, payload: { text: textBlock(request.text), queuedBehind: 0 } });
|
|
108
|
+
const receipt = { commandId: request.commandId, promptId, state: 'queued', queuedBehind: 0, acceptedAt: event.at, eventCursor: String(event.seq), sessionGeneration: this.generation };
|
|
109
|
+
atomicPrivateWrite(path, { digest, receipt, status: 'intent' });
|
|
110
|
+
try {
|
|
111
|
+
this.assertConnected();
|
|
112
|
+
const sent = await this.options.mailbox.send(request.text);
|
|
113
|
+
if (sent.wire_id)
|
|
114
|
+
this.outgoing.add(sent.wire_id);
|
|
115
|
+
atomicPrivateWrite(path, { digest, receipt, status: 'sent', wireId: sent.wire_id });
|
|
116
|
+
this.store.append({ sessionGeneration: this.generation, kind: 'turn.completed', promptId, source: 'owner_admin_console', payload: { outcome: 'completed', stopReason: 'Ours mail accepted; this does not assert completion of a native model turn' } });
|
|
117
|
+
this.changed();
|
|
118
|
+
return receipt;
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
this.store.append({ sessionGeneration: this.generation, kind: 'turn.completed', promptId, payload: { outcome: 'inconclusive', stopReason: 'Mail acceptance could not be confirmed; automatic resend is disabled' } });
|
|
122
|
+
this.changed();
|
|
123
|
+
throw error;
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
const result = this.sending.then(run);
|
|
127
|
+
this.sending = result.then(() => { }, () => { });
|
|
128
|
+
return result;
|
|
129
|
+
}
|
|
130
|
+
observeConversation(listener) { this.listeners.add(listener); return { snapshot: this.state(), unsubscribe: () => { this.listeners.delete(listener); } }; }
|
|
131
|
+
subscribeConversation(listener) { return this.store.subscribe(listener); }
|
|
132
|
+
subscribeConversationFailure(listener) { return this.store.subscribeFailure(listener); }
|
|
133
|
+
replayConversation(request) { return this.store.replay(request); }
|
|
134
|
+
async followConversation(request) {
|
|
135
|
+
await this.sync();
|
|
136
|
+
this.follows++;
|
|
137
|
+
if (!this.timer) {
|
|
138
|
+
this.timer = setInterval(() => { if (!this.options.connected())
|
|
139
|
+
this.changed();
|
|
140
|
+
else
|
|
141
|
+
void this.sending.then(() => this.sync()).catch(() => { }); }, 1000);
|
|
142
|
+
this.timer.unref();
|
|
143
|
+
}
|
|
144
|
+
let release;
|
|
145
|
+
if ('controller' in request) {
|
|
146
|
+
const follow = startConversationReplay(this, request, { replay: request.onReplay, ready: request.onReady, event: request.onEvent, state: request.onState, close: request.onClose });
|
|
147
|
+
release = follow.close;
|
|
148
|
+
}
|
|
149
|
+
else {
|
|
150
|
+
request.onPage({ ...this.store.page({ after: request.after }), snapshot: this.state() });
|
|
151
|
+
release = this.store.subscribe(request.onEvent);
|
|
152
|
+
}
|
|
153
|
+
let closed = false;
|
|
154
|
+
return { close: () => { if (closed)
|
|
155
|
+
return; closed = true; release(); if (!--this.follows) {
|
|
156
|
+
clearInterval(this.timer);
|
|
157
|
+
this.timer = undefined;
|
|
158
|
+
} } };
|
|
159
|
+
}
|
|
160
|
+
close() { this.disposed = true; clearInterval(this.timer); this.changed(); this.store.close(); this.listeners.clear(); }
|
|
161
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { NativeMailbox, NativeMail } from './native-correspondence.js';
|
|
2
|
+
/** Uses the already configured Messenger Human. Does not bind or impersonate the native agent. */
|
|
3
|
+
export declare class NativeHumanMailbox implements NativeMailbox {
|
|
4
|
+
private cid;
|
|
5
|
+
private rootCid;
|
|
6
|
+
private assertConnected;
|
|
7
|
+
constructor(cid: string, rootCid: string, assertConnected?: () => void);
|
|
8
|
+
private transport;
|
|
9
|
+
private verify;
|
|
10
|
+
history(): Promise<NativeMail[]>;
|
|
11
|
+
send(text: string): Promise<{
|
|
12
|
+
wire_id: string | null;
|
|
13
|
+
}>;
|
|
14
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { readPrivateFile } from '@ours.network/sdk/connector';
|
|
2
|
+
import { readClientProfile } from '../client-profile.js';
|
|
3
|
+
import { FleetError } from './errors.js';
|
|
4
|
+
/** Uses the already configured Messenger Human. Does not bind or impersonate the native agent. */
|
|
5
|
+
export class NativeHumanMailbox {
|
|
6
|
+
cid;
|
|
7
|
+
rootCid;
|
|
8
|
+
assertConnected;
|
|
9
|
+
constructor(cid, rootCid, assertConnected = () => { }) {
|
|
10
|
+
this.cid = cid;
|
|
11
|
+
this.rootCid = rootCid;
|
|
12
|
+
this.assertConnected = assertConnected;
|
|
13
|
+
}
|
|
14
|
+
transport() {
|
|
15
|
+
const profile = readClientProfile();
|
|
16
|
+
const base = profile.serverUrl.replace(/\/$/, '');
|
|
17
|
+
const credential = readPrivateFile(profile.credentialPath, 4096).toString('utf8').trim();
|
|
18
|
+
return async (path, body) => {
|
|
19
|
+
const response = await fetch(`${base}/messenger/api${path}`, {
|
|
20
|
+
method: body === undefined ? 'GET' : 'POST', signal: AbortSignal.timeout(15_000), redirect: 'error',
|
|
21
|
+
headers: { 'X-Ours-Api-Token': credential, Origin: new URL(base).origin, 'X-Ours-Messenger-CSRF': '1', ...(body === undefined ? {} : { 'Content-Type': 'application/json' }) },
|
|
22
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
23
|
+
});
|
|
24
|
+
if (!response.ok)
|
|
25
|
+
throw new FleetError('backend_failure', `Local Messenger returned HTTP ${response.status}`);
|
|
26
|
+
return response.json();
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
async verify(request) {
|
|
30
|
+
const identity = await request('/identity');
|
|
31
|
+
if (identity.cid?.toUpperCase() !== this.rootCid.toUpperCase())
|
|
32
|
+
throw new FleetError('forbidden', 'Messenger Human differs from native participation authorization');
|
|
33
|
+
const directory = await request('/contacts');
|
|
34
|
+
// Older Messenger versions resolve name-or-CID. Reject ambiguous addresses instead of reading another peer.
|
|
35
|
+
if (!Array.isArray(directory.contacts) || directory.contacts.some((row) => row.name === this.cid && row.container_id?.toUpperCase() !== this.cid.toUpperCase()))
|
|
36
|
+
throw new FleetError('conflict', 'Messenger cannot resolve this participant CID unambiguously');
|
|
37
|
+
}
|
|
38
|
+
async history() {
|
|
39
|
+
const request = this.transport();
|
|
40
|
+
this.assertConnected();
|
|
41
|
+
await this.verify(request);
|
|
42
|
+
const pages = [];
|
|
43
|
+
let before;
|
|
44
|
+
for (let pageNo = 0; pageNo < 100; pageNo++) {
|
|
45
|
+
const page = await request(`/conversations/${encodeURIComponent(this.cid)}/page?limit=200${before ? '&before=' + encodeURIComponent(before) : ''}`);
|
|
46
|
+
if (page.contact?.toUpperCase() !== this.cid.toUpperCase() || !Array.isArray(page.messages))
|
|
47
|
+
throw new FleetError('backend_failure', 'Invalid Messenger correspondence response');
|
|
48
|
+
const rows = [];
|
|
49
|
+
for (const row of page.messages) {
|
|
50
|
+
if (row.peer_cid && row.peer_cid.toUpperCase() !== this.cid.toUpperCase())
|
|
51
|
+
throw new FleetError('conflict', 'Messenger history belongs to another peer');
|
|
52
|
+
if (typeof row.wire_id === 'string' && row.wire_id && ['in', 'out'].includes(row.dir))
|
|
53
|
+
rows.push({ wire_id: row.wire_id, dir: row.dir, text: typeof row.text === 'string' ? row.text : '[Non-text Ours message]', date: row.date });
|
|
54
|
+
}
|
|
55
|
+
pages.unshift(rows);
|
|
56
|
+
if (!page.hasMore) {
|
|
57
|
+
await this.verify(request);
|
|
58
|
+
this.assertConnected();
|
|
59
|
+
return pages.flat();
|
|
60
|
+
}
|
|
61
|
+
if (!page.nextBefore || page.nextBefore === before)
|
|
62
|
+
throw new FleetError('backend_failure', 'Messenger history did not advance');
|
|
63
|
+
before = page.nextBefore;
|
|
64
|
+
}
|
|
65
|
+
throw new FleetError('capability_unavailable', 'Native correspondence exceeds the bounded history import');
|
|
66
|
+
}
|
|
67
|
+
async send(text) {
|
|
68
|
+
const request = this.transport();
|
|
69
|
+
this.assertConnected();
|
|
70
|
+
await this.verify(request);
|
|
71
|
+
this.assertConnected();
|
|
72
|
+
const result = await request('/messages/send', { contact: this.cid, text });
|
|
73
|
+
if (typeof result.wire_id !== 'string' && !(result.wire_id === null && result.delivery === 'introduced'))
|
|
74
|
+
throw new FleetError('backend_failure', 'Messenger did not confirm mail acceptance');
|
|
75
|
+
return { wire_id: result.wire_id };
|
|
76
|
+
}
|
|
77
|
+
}
|