@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
package/README.md
CHANGED
|
@@ -3,6 +3,8 @@
|
|
|
3
3
|
**Run a fleet of persistent, securely isolated, identity-bound AI agents — across different agent
|
|
4
4
|
harnesses — from one declarative file.**
|
|
5
5
|
|
|
6
|
+
For the experiment that enrolls a human-operated terminal in Fleet, see [Native terminal participation](docs/native-session-participation.md).
|
|
7
|
+
|
|
6
8
|
## What is this?
|
|
7
9
|
|
|
8
10
|
An AI coding agent in a terminal dies when you close the laptop. `ours-fleet`
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"name":"ours-fleet-experiment","owner":{"name":"Ours Fleet local experiment"},"plugins":[{"name":"ours-fleet-native","source":"./claude-native","description":"Shared native Human conversation with local Fleet"}]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"name":"ours-fleet-native","version":"0.1.0","description":"Shared native Human conversation with the authorized local Ours Fleet"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"modules":["./register.js"]}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
let polling = false;
|
|
2
|
+
// Set by the first failed bridge operation: this session's pulse stops and is never retried.
|
|
3
|
+
let stopped = null;
|
|
4
|
+
let submitting = null;
|
|
5
|
+
let active = null;
|
|
6
|
+
let activeTurn = null;
|
|
7
|
+
const correlations = {};
|
|
8
|
+
const finished = [];
|
|
9
|
+
|
|
10
|
+
// The Ours plugin's server, or a directly configured "ours" server.
|
|
11
|
+
const OURS_SERVERS = ['plugin:ours.network:ours', 'ours'];
|
|
12
|
+
|
|
13
|
+
let oursServer = null;
|
|
14
|
+
|
|
15
|
+
async function oursCall($, tool, args) {
|
|
16
|
+
let error = 'no connected Ours MCP server in this session';
|
|
17
|
+
for (const server of oursServer ? [oursServer] : OURS_SERVERS) {
|
|
18
|
+
try {
|
|
19
|
+
const result = await $.mcp.call(server, tool, args);
|
|
20
|
+
oursServer = server;
|
|
21
|
+
return result;
|
|
22
|
+
} catch (failure) {
|
|
23
|
+
error = String(failure?.message ?? failure);
|
|
24
|
+
if (!/no connected MCP/.test(error)) break;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return { isError: true, content: [{ type: 'text', text: error }] };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* One read-only Ours tool the Fleet App asked for, run on this session's own MCP only while current_identity
|
|
32
|
+
* still shows the participant's identity, and read again afterwards.
|
|
33
|
+
*/
|
|
34
|
+
async function answer($, request) {
|
|
35
|
+
const identity = async () => (await oursCall($, 'current_identity', {}))?.content?.find(item => item.type === 'text')?.text;
|
|
36
|
+
const before = await identity();
|
|
37
|
+
const expected = request.expect;
|
|
38
|
+
if (typeof expected?.name !== 'string' || typeof expected?.cid !== 'string' || !before?.startsWith(`Bound to "${expected.name}" (${expected.cid})`))
|
|
39
|
+
return { id: request.id, value: { before, result: { isError: true, content: [] } } };
|
|
40
|
+
const result = await oursCall($, request.tool, request.arguments ?? {});
|
|
41
|
+
const after = await identity();
|
|
42
|
+
return { id: request.id, value: { before, result: { isError: !!result?.isError, content: result?.content }, after } };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// One App read at a time, off the pulse, so normal input and state keep flowing. A failed read only
|
|
46
|
+
// fails that request (the App reports it); it never stops this session's participation.
|
|
47
|
+
const ANSWER_LIMIT = 900 * 1024; // under the bridge's 1 MiB input cap
|
|
48
|
+
let reading = false;
|
|
49
|
+
// A failure produced here, not by the Ours tool; Fleet shows it only while consent still holds.
|
|
50
|
+
function failed(request, before, text) {
|
|
51
|
+
return { id: request.id, value: { before, local: true, result: { isError: true, content: [{ type: 'text', text }] } } };
|
|
52
|
+
}
|
|
53
|
+
function serve($, bridge, request) {
|
|
54
|
+
if (reading || !['list_contacts', 'list_history'].includes(request?.tool)) return;
|
|
55
|
+
reading = true;
|
|
56
|
+
(async () => {
|
|
57
|
+
let reply;
|
|
58
|
+
try { reply = await answer($, request); }
|
|
59
|
+
catch (error) { reply = failed(request, undefined, `the read could not run in this session (${error?.message ?? error})`); }
|
|
60
|
+
if (JSON.stringify(reply).length > ANSWER_LIMIT)
|
|
61
|
+
reply = failed(request, reply.value.before, 'the result is too large to hand to Fleet; request a smaller history page');
|
|
62
|
+
// Exactly one answer; a failed handoff is reported by the App's own deadline, never resent.
|
|
63
|
+
try { await bridge({ reads: [reply] }); } catch {}
|
|
64
|
+
})().finally(() => { reading = false; });
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function currentIdentity($) {
|
|
68
|
+
let error = 'no connected Ours MCP server in this session';
|
|
69
|
+
for (const server of OURS_SERVERS) {
|
|
70
|
+
try {
|
|
71
|
+
const result = await $.mcp.call(server, 'current_identity', {});
|
|
72
|
+
oursServer = server;
|
|
73
|
+
const text = result?.content?.find(item => item.type === 'text')?.text;
|
|
74
|
+
return result?.isError ? { error: text ?? 'current_identity failed' } : { text };
|
|
75
|
+
} catch (failure) {
|
|
76
|
+
if (!/no connected MCP/.test(String(failure?.message ?? failure))) return { error: String(failure?.message ?? failure) };
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return { error };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function stop($, reason) {
|
|
83
|
+
stopped = `Ours Fleet participation stopped for this session: ${reason}. Fleet will not retry; fix the cause, then restart or resume this Claude session.`;
|
|
84
|
+
try { $.ui.log(stopped); } catch {}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async function bridged($, run) {
|
|
88
|
+
let response;
|
|
89
|
+
try { response = await run(); } catch (error) { stop($, `the Fleet bridge could not run (${error?.message ?? error})`); return undefined; }
|
|
90
|
+
if (response.exitCode !== 0) {
|
|
91
|
+
const detail = String(response.stderr ?? '').trim().split('\n').at(-1) || `exit code ${response.exitCode}`;
|
|
92
|
+
stop($, `the Fleet bridge failed (${detail})`);
|
|
93
|
+
return undefined;
|
|
94
|
+
}
|
|
95
|
+
try { return JSON.parse(response.stdout); } catch { stop($, 'the Fleet bridge returned an unreadable reply'); return undefined; }
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async function pulse($) {
|
|
99
|
+
if (polling || stopped) return;
|
|
100
|
+
polling = true;
|
|
101
|
+
try {
|
|
102
|
+
const id = await $.session.id();
|
|
103
|
+
const info = await $.session.info();
|
|
104
|
+
const tail = await $.session.messages({ last: 1 });
|
|
105
|
+
if (!Array.isArray(tail)) return;
|
|
106
|
+
const state = { transcriptPath: info.transcriptPath, lastMessageId: tail.at(-1)?.uuid ?? null, status: info.state?.status ?? 'busy', correlations, finished, ready: info.state?.status === 'idle' && submitting === null && active === null, canRead: !reading };
|
|
107
|
+
const bridge = extra => $.process.run(['ours-fleet', 'participation', 'claude-bridge', id], {
|
|
108
|
+
stdin: JSON.stringify({ ...state, ...extra }), timeoutMs: 10000,
|
|
109
|
+
});
|
|
110
|
+
let reply = await bridged($, () => bridge({}));
|
|
111
|
+
if (!reply) return;
|
|
112
|
+
if (reply.identity === 'required') {
|
|
113
|
+
// Fleet joins only the identity this session already uses: read it through the session's own
|
|
114
|
+
// Ours MCP connection with the read-only current_identity tool. Fleet decides once; no retry.
|
|
115
|
+
reply = await bridged($, async () => bridge({ identity: await currentIdentity($) }));
|
|
116
|
+
if (!reply) return;
|
|
117
|
+
}
|
|
118
|
+
if (reply.read) serve($, bridge, reply.read);
|
|
119
|
+
const command = reply.command;
|
|
120
|
+
if (!command || submitting !== null || active !== null) return;
|
|
121
|
+
submitting = command.clientId;
|
|
122
|
+
// Never claim terminal-local consent. The authenticated PWA Human supplies
|
|
123
|
+
// these words; Claude keeps the plugin origin and its own native controls.
|
|
124
|
+
$.prompt.submit({ text: command.text, asUser: true }).then(result => {
|
|
125
|
+
if (result?.drop) finished.push({ clientId: command.clientId, outcome: 'cancelled' });
|
|
126
|
+
submitting = null;
|
|
127
|
+
}, () => {
|
|
128
|
+
finished.push({ clientId: command.clientId, outcome: 'failed' });
|
|
129
|
+
submitting = null;
|
|
130
|
+
});
|
|
131
|
+
} catch (error) {
|
|
132
|
+
stop($, `the session state could not be read (${error?.message ?? error})`);
|
|
133
|
+
} finally { polling = false; }
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function register(on) {
|
|
137
|
+
on('session.start', ($, e, next) => {
|
|
138
|
+
if (e.isInteractive) $.clock.every(1000, () => pulse($));
|
|
139
|
+
return next(e);
|
|
140
|
+
});
|
|
141
|
+
on('session.append', ($, e, next) => {
|
|
142
|
+
if (submitting && e.agentId === undefined && e.message.type === 'user' && e.origin.kind === 'plugin' && e.origin.name === 'ours-fleet-native') {
|
|
143
|
+
correlations[e.uuid] = submitting;
|
|
144
|
+
active = submitting;
|
|
145
|
+
}
|
|
146
|
+
return next(e);
|
|
147
|
+
});
|
|
148
|
+
on('turn.start', ($, e, next) => {
|
|
149
|
+
if (e.agentId === undefined && active && activeTurn === null) activeTurn = e.turnId;
|
|
150
|
+
return next(e);
|
|
151
|
+
});
|
|
152
|
+
on('turn.complete', ($, e, next) => {
|
|
153
|
+
if (e.agentId === undefined && active && activeTurn === e.turnId) {
|
|
154
|
+
finished.push({ clientId: active, outcome: e.isAborted ? 'cancelled' : e.reason === 'answer' ? 'completed' : 'failed' });
|
|
155
|
+
active = null;
|
|
156
|
+
activeTurn = null;
|
|
157
|
+
}
|
|
158
|
+
return next(e);
|
|
159
|
+
});
|
|
160
|
+
}
|
|
@@ -4,6 +4,14 @@ import { type CapabilityContext } from './capabilities.js';
|
|
|
4
4
|
import { RoleRepository } from './role-repository.js';
|
|
5
5
|
import type { RoleCapabilities, RoleRecord, RoleStatus } from './types.js';
|
|
6
6
|
export interface FleetQueryOptions {
|
|
7
|
+
nativeParticipants?: () => Promise<Array<{
|
|
8
|
+
harness: 'claude' | 'codex';
|
|
9
|
+
cid: string;
|
|
10
|
+
name: string;
|
|
11
|
+
lastSeen: number;
|
|
12
|
+
title?: string;
|
|
13
|
+
cwd?: string;
|
|
14
|
+
}>>;
|
|
7
15
|
repository: RoleRepository;
|
|
8
16
|
supervisor: SupervisorBackend;
|
|
9
17
|
control?: typeof controlRequest;
|
|
@@ -29,6 +37,7 @@ export declare class FleetQueryService {
|
|
|
29
37
|
status: RoleStatus;
|
|
30
38
|
capabilities: RoleCapabilities;
|
|
31
39
|
}>>;
|
|
40
|
+
private nativeRows;
|
|
32
41
|
detail(id: string): Promise<{
|
|
33
42
|
role: RoleRecord;
|
|
34
43
|
status: RoleStatus;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { lstatSync, readFileSync } from 'node:fs';
|
|
2
|
-
import { join } from 'node:path';
|
|
2
|
+
import { basename, join } from 'node:path';
|
|
3
3
|
import { classifyActivity } from '../session/activity.js';
|
|
4
4
|
import { controlRequest } from '../session/control.js';
|
|
5
5
|
import { SessionControlError } from '../session/types.js';
|
|
@@ -78,13 +78,25 @@ export class FleetQueryService {
|
|
|
78
78
|
async list(includeTemporary = false, strict = false) {
|
|
79
79
|
const roles = (await this.options.repository.list(strict))
|
|
80
80
|
.filter(role => (role.configured && role.lifetime === 'permanent') || (includeTemporary && role.lifetime === 'temporary'));
|
|
81
|
-
|
|
81
|
+
const managed = await Promise.all(roles.map(async (role) => {
|
|
82
82
|
const status = await this.status(role);
|
|
83
83
|
return { role, status, capabilities: roleCapabilities(role, status, this.options.capabilityContext) };
|
|
84
84
|
}));
|
|
85
|
+
const native = includeTemporary ? await this.nativeRows() : [];
|
|
86
|
+
return [...managed, ...native.filter(row => !roles.some(role => role.id === row.role.id))];
|
|
87
|
+
}
|
|
88
|
+
async nativeRows() {
|
|
89
|
+
const rows = await this.options.nativeParticipants?.() ?? [];
|
|
90
|
+
const labels = rows.map(nativeParticipantLabel);
|
|
91
|
+
return rows.map((row, index) => nativeParticipantView(row, labels.filter(label => label === labels[index]).length > 1 ? `${labels[index]} · ${row.name.slice(-6)}` : labels[index]));
|
|
85
92
|
}
|
|
86
93
|
async detail(id) {
|
|
87
94
|
const role = await this.options.repository.get(id);
|
|
95
|
+
if (!role) {
|
|
96
|
+
const native = (await this.nativeRows()).find(row => row.role.id === id);
|
|
97
|
+
if (native)
|
|
98
|
+
return native;
|
|
99
|
+
}
|
|
88
100
|
if (!role)
|
|
89
101
|
throw new FleetError('role_not_found', `no such role '${id}'`, { provesOffline: false });
|
|
90
102
|
const status = await this.status(role);
|
|
@@ -195,3 +207,25 @@ export class FleetQueryService {
|
|
|
195
207
|
};
|
|
196
208
|
}
|
|
197
209
|
}
|
|
210
|
+
function nativeParticipantLabel(row) {
|
|
211
|
+
const harness = row.harness === 'codex' ? 'Codex' : 'Claude';
|
|
212
|
+
return row.title?.trim() ? `${clean(row.title, 160)} · ${harness}` : `${harness} · ${row.cwd ? clean(basename(row.cwd), 160) : 'Session'}`;
|
|
213
|
+
}
|
|
214
|
+
function nativeParticipantView(row, label) {
|
|
215
|
+
return {
|
|
216
|
+
role: { id: row.name, lifetime: 'temporary', configured: false, stateHealth: 'present',
|
|
217
|
+
config: { name: label, harness: row.harness === 'codex' ? 'codex' : 'claude-code', session: row.harness === 'codex' ? 'codex-app-server' : 'acp', identity: row.name, cwd: row.cwd, mission: 'Independent terminal session; Ours correspondence' },
|
|
218
|
+
detectedBackend: 'none', compatibility: { compatible: true }, problems: [],
|
|
219
|
+
nativeParticipation: { harness: row.harness, cid: row.cid } },
|
|
220
|
+
status: { roleId: row.name, observedAt: new Date(row.lastSeen).toISOString(), overall: 'unknown',
|
|
221
|
+
supervisor: { backend: 'none', liveness: 'unknown', detail: 'Independently launched native session' },
|
|
222
|
+
session: { backend: 'unknown', reachability: 'online', readiness: 'unknown', evidence: 'authoritative', activity: { state: 'unobservable' } },
|
|
223
|
+
restart: { circuit: 'closed', consecutiveImmediateFailures: 0, nextDelayMs: 0 },
|
|
224
|
+
monitor: { mode: 'native', health: 'armed', stale: false }, isolation: { degraded: false }, problems: [] },
|
|
225
|
+
capabilities: { protocolVersion: 1, inventory: true, status: true,
|
|
226
|
+
output: { recent: true, stream: true, structured: true, replayCursor: true },
|
|
227
|
+
input: { text: true, interrupt: false, steering: false }, permissions: { observe: false, respond: false },
|
|
228
|
+
lifecycle: { start: false, stop: false, restartResume: false, restartFresh: false, remove: false },
|
|
229
|
+
logs: { tail: false, follow: false, cursor: false } },
|
|
230
|
+
};
|
|
231
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { NativeConversationTransport, NativeTranscript } from './native-conversation.js';
|
|
2
|
+
export type ClaudePulse = {
|
|
3
|
+
transcriptPath: string;
|
|
4
|
+
lastMessageId: string | null;
|
|
5
|
+
status: 'idle' | 'busy' | 'waiting';
|
|
6
|
+
correlations: Record<string, string>;
|
|
7
|
+
finished: NonNullable<NativeTranscript['finished']>;
|
|
8
|
+
ready: boolean;
|
|
9
|
+
at: number;
|
|
10
|
+
};
|
|
11
|
+
type Queued = {
|
|
12
|
+
text: string;
|
|
13
|
+
clientId: string;
|
|
14
|
+
sequence: number;
|
|
15
|
+
claimed?: boolean;
|
|
16
|
+
};
|
|
17
|
+
export declare class NativeClaudeConversation implements NativeConversationTransport {
|
|
18
|
+
private directory;
|
|
19
|
+
private nativeId;
|
|
20
|
+
private guard;
|
|
21
|
+
private projects;
|
|
22
|
+
constructor(directory: string, nativeId: string, guard: () => void, projects?: string);
|
|
23
|
+
private snapshot;
|
|
24
|
+
private existingTranscript;
|
|
25
|
+
read(): Promise<NativeTranscript>;
|
|
26
|
+
private commands;
|
|
27
|
+
submit(text: string, clientId: string): Promise<void>;
|
|
28
|
+
pulse(state: ClaudePulse): Promise<{
|
|
29
|
+
command?: undefined;
|
|
30
|
+
} | {
|
|
31
|
+
command: Queued;
|
|
32
|
+
}>;
|
|
33
|
+
}
|
|
34
|
+
export {};
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { existsSync, readFileSync, readdirSync, mkdirSync, constants } from 'node:fs';
|
|
3
|
+
import { open } from 'node:fs/promises';
|
|
4
|
+
import { join, basename } from 'node:path';
|
|
5
|
+
import { homedir } from 'node:os';
|
|
6
|
+
import { createInterface } from 'node:readline';
|
|
7
|
+
import { atomicPrivateWrite } from '../agent-ours/state.js';
|
|
8
|
+
import { withFileLock } from '../atomic-file.js';
|
|
9
|
+
import { FleetError } from './errors.js';
|
|
10
|
+
export class NativeClaudeConversation {
|
|
11
|
+
directory;
|
|
12
|
+
nativeId;
|
|
13
|
+
guard;
|
|
14
|
+
projects;
|
|
15
|
+
constructor(directory, nativeId, guard, projects = join(process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), '.claude'), 'projects')) {
|
|
16
|
+
this.directory = directory;
|
|
17
|
+
this.nativeId = nativeId;
|
|
18
|
+
this.guard = guard;
|
|
19
|
+
this.projects = projects;
|
|
20
|
+
}
|
|
21
|
+
snapshot() { this.guard(); const path = join(this.directory, 'state.json'); if (!existsSync(path))
|
|
22
|
+
throw new FleetError('capability_unavailable', 'Enable the Ours native Claude plugin and restart this Claude session'); return JSON.parse(readFileSync(path, 'utf8')); }
|
|
23
|
+
existingTranscript() {
|
|
24
|
+
if (!/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(this.nativeId))
|
|
25
|
+
throw new FleetError('capability_unavailable', 'Invalid native session identity');
|
|
26
|
+
const paths = existsSync(this.projects) ? readdirSync(this.projects, { withFileTypes: true }).filter(entry => entry.isDirectory()).map(entry => join(this.projects, entry.name, this.nativeId + '.jsonl')).filter(existsSync) : [];
|
|
27
|
+
if (paths.length !== 1)
|
|
28
|
+
throw new FleetError('capability_unavailable', 'A unique saved transcript for this Claude session is unavailable');
|
|
29
|
+
return paths[0];
|
|
30
|
+
}
|
|
31
|
+
async read() {
|
|
32
|
+
this.guard();
|
|
33
|
+
const bridged = existsSync(join(this.directory, 'state.json'));
|
|
34
|
+
const state = bridged ? this.snapshot() : { transcriptPath: this.existingTranscript(), lastMessageId: null, status: 'idle', correlations: {}, finished: [], ready: false, at: 0 };
|
|
35
|
+
const messages = [];
|
|
36
|
+
if (basename(state.transcriptPath) !== this.nativeId + '.jsonl')
|
|
37
|
+
throw Error('Claude transcript identity mismatch');
|
|
38
|
+
if ((!bridged || state.lastMessageId) && existsSync(state.transcriptPath)) {
|
|
39
|
+
const file = await open(state.transcriptPath, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
40
|
+
try {
|
|
41
|
+
const stat = await file.stat();
|
|
42
|
+
if (!stat.isFile() || stat.uid !== process.getuid?.())
|
|
43
|
+
throw Error('Claude transcript must be an owned regular file');
|
|
44
|
+
const lines = createInterface({ input: file.createReadStream(), crlfDelay: Infinity });
|
|
45
|
+
for await (const line of lines) {
|
|
46
|
+
let row;
|
|
47
|
+
try {
|
|
48
|
+
row = JSON.parse(line);
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
const boundary = row.uuid === state.lastMessageId;
|
|
54
|
+
if (boundary && !(row.sessionId === this.nativeId && !row.isSidechain && !row.isMeta && ['user', 'assistant'].includes(row.type)))
|
|
55
|
+
break;
|
|
56
|
+
if (row.sessionId !== this.nativeId || row.isSidechain || row.isMeta || !row.uuid || !['user', 'assistant'].includes(row.type))
|
|
57
|
+
continue;
|
|
58
|
+
const content = row.message?.content;
|
|
59
|
+
const text = typeof content === 'string' ? content : Array.isArray(content) ? content.filter((b) => b.type === 'text').map((b) => b.text).join('\n') : '';
|
|
60
|
+
if (text)
|
|
61
|
+
messages.push({ id: row.uuid, role: row.type, text, clientId: state.correlations[row.uuid], at: row.timestamp });
|
|
62
|
+
if (boundary)
|
|
63
|
+
break;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
finally {
|
|
67
|
+
await file.close().catch(() => { });
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
this.guard();
|
|
71
|
+
// If the plugin appeared while reading, use its correlation watermark before
|
|
72
|
+
// publishing anything that could be a newly accepted PWA input echo.
|
|
73
|
+
if (!bridged && existsSync(join(this.directory, 'state.json')))
|
|
74
|
+
return this.read();
|
|
75
|
+
const queued = this.commands().filter(c => !state.finished.some(f => f.clientId === c.clientId) && !Object.values(state.correlations).includes(c.clientId)).map(c => c.clientId);
|
|
76
|
+
return { messages, queued, finished: state.finished, status: bridged ? state.status : 'unavailable' };
|
|
77
|
+
}
|
|
78
|
+
commands() { if (!existsSync(this.directory))
|
|
79
|
+
return []; return readdirSync(this.directory).filter(n => /^input-[a-f0-9]+\.json$/.test(n)).map(n => JSON.parse(readFileSync(join(this.directory, n), 'utf8'))).sort((a, b) => a.sequence - b.sequence); }
|
|
80
|
+
async submit(text, clientId) { const state = this.snapshot(); if (Date.now() - state.at > 10000)
|
|
81
|
+
throw new FleetError('capability_unavailable', 'Native Claude bridge is not responding'); this.guard(); await withFileLock(join(this.directory, 'input.lock'), () => { this.guard(); const sequence = Math.max(0, ...this.commands().map(row => row.sequence)) + 1; atomicPrivateWrite(join(this.directory, 'input-' + createHash('sha256').update(clientId).digest('hex') + '.json'), { text, clientId, sequence }); }); }
|
|
82
|
+
async pulse(state) {
|
|
83
|
+
this.guard();
|
|
84
|
+
mkdirSync(this.directory, { recursive: true, mode: 0o700 });
|
|
85
|
+
return withFileLock(join(this.directory, 'pulse.lock'), () => {
|
|
86
|
+
this.guard();
|
|
87
|
+
const path = join(this.directory, 'state.json');
|
|
88
|
+
const previous = existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : undefined;
|
|
89
|
+
state = { ...state, correlations: { ...previous?.correlations, ...state.correlations }, finished: [...new Map([...(previous?.finished ?? []), ...state.finished].map(row => [row.clientId, row])).values()] };
|
|
90
|
+
atomicPrivateWrite(path, { ...state, at: Date.now() });
|
|
91
|
+
if (!state.ready)
|
|
92
|
+
return {};
|
|
93
|
+
const command = this.commands().find(c => !c.claimed);
|
|
94
|
+
if (!command)
|
|
95
|
+
return {};
|
|
96
|
+
const inputPath = join(this.directory, 'input-' + createHash('sha256').update(command.clientId).digest('hex') + '.json');
|
|
97
|
+
// Claim before handing off: a lost local process reply must not duplicate a turn.
|
|
98
|
+
atomicPrivateWrite(inputPath, { ...command, claimed: true });
|
|
99
|
+
return { command };
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { NativeConversationTransport, NativeMessage } from './native-conversation.js';
|
|
2
|
+
/** Uses only read/queue RPCs: the native terminal remains the controlling client. */
|
|
3
|
+
export declare class NativeCodexConversation implements NativeConversationTransport {
|
|
4
|
+
private socket;
|
|
5
|
+
private threadId;
|
|
6
|
+
private cid;
|
|
7
|
+
private name;
|
|
8
|
+
private guard;
|
|
9
|
+
constructor(socket: string, threadId: string, cid: string, name: string, guard: () => void);
|
|
10
|
+
read(): Promise<{
|
|
11
|
+
messages: NativeMessage[];
|
|
12
|
+
queued: string[];
|
|
13
|
+
finished: {
|
|
14
|
+
clientId: string;
|
|
15
|
+
outcome: "failed" | "cancelled" | "completed";
|
|
16
|
+
}[];
|
|
17
|
+
status: "idle" | "busy";
|
|
18
|
+
}>;
|
|
19
|
+
submit(text: string, clientId: string): Promise<void>;
|
|
20
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { withCodex, verifyCodexBinding } from '../native-codex-wake.js';
|
|
2
|
+
import { FleetError } from './errors.js';
|
|
3
|
+
/** Uses only read/queue RPCs: the native terminal remains the controlling client. */
|
|
4
|
+
export class NativeCodexConversation {
|
|
5
|
+
socket;
|
|
6
|
+
threadId;
|
|
7
|
+
cid;
|
|
8
|
+
name;
|
|
9
|
+
guard;
|
|
10
|
+
constructor(socket, threadId, cid, name, guard) {
|
|
11
|
+
this.socket = socket;
|
|
12
|
+
this.threadId = threadId;
|
|
13
|
+
this.cid = cid;
|
|
14
|
+
this.name = name;
|
|
15
|
+
this.guard = guard;
|
|
16
|
+
}
|
|
17
|
+
async read() {
|
|
18
|
+
this.guard();
|
|
19
|
+
return withCodex(this.socket, async (request) => {
|
|
20
|
+
let loaded;
|
|
21
|
+
try {
|
|
22
|
+
loaded = await request('thread/read', { threadId: this.threadId, includeTurns: true });
|
|
23
|
+
}
|
|
24
|
+
catch (error) {
|
|
25
|
+
// No substitute history source: the native refusal is surfaced as is.
|
|
26
|
+
if (/list_turns is not supported/.test(String(error)))
|
|
27
|
+
throw new FleetError('capability_unavailable', `This Codex App Server cannot list the thread's turns (${error.message}); Fleet does not read history another way. Update Codex to a version whose thread/read supports includeTurns, then reopen the conversation.`);
|
|
28
|
+
throw error;
|
|
29
|
+
}
|
|
30
|
+
const messages = [];
|
|
31
|
+
let cursor = null;
|
|
32
|
+
for (const turn of loaded.thread.turns)
|
|
33
|
+
for (const item of turn.items) {
|
|
34
|
+
if (item.type !== 'userMessage' && item.type !== 'agentMessage')
|
|
35
|
+
continue;
|
|
36
|
+
if (item.moderation || item.display?.mode === 'hide' || item.display?.mode === 'block')
|
|
37
|
+
continue;
|
|
38
|
+
const text = item.type === 'agentMessage' ? item.text ?? '' : (item.content ?? []).filter(c => c.type === 'text').map(c => c.text ?? '').join('\n');
|
|
39
|
+
if (!text)
|
|
40
|
+
continue;
|
|
41
|
+
messages.push({ id: item.id, role: item.type === 'userMessage' ? 'user' : 'assistant', text, clientId: item.clientId, ...(turn.startedAt ? { at: new Date(turn.startedAt * 1000).toISOString() } : {}) });
|
|
42
|
+
}
|
|
43
|
+
const queued = [];
|
|
44
|
+
cursor = null;
|
|
45
|
+
do {
|
|
46
|
+
const page = await request('thread/queue/list', { threadId: this.threadId, cursor, limit: 100 });
|
|
47
|
+
for (const item of page.data)
|
|
48
|
+
if (item.clientUserMessageId)
|
|
49
|
+
queued.push(item.clientUserMessageId);
|
|
50
|
+
cursor = page.nextCursor;
|
|
51
|
+
} while (cursor);
|
|
52
|
+
const finished = loaded.thread.turns.flatMap(turn => turn.status === 'completed' || turn.status === 'failed' || turn.status === 'interrupted' ? turn.items.filter(item => item.type === 'userMessage' && item.clientId).map(item => ({ clientId: item.clientId, outcome: turn.status === 'completed' ? 'completed' : turn.status === 'interrupted' ? 'cancelled' : 'failed' })) : []);
|
|
53
|
+
this.guard();
|
|
54
|
+
if (loaded.thread.status.type === 'notLoaded')
|
|
55
|
+
throw new FleetError('role_not_found', 'Native runtime is unloaded');
|
|
56
|
+
return { messages, queued, finished, status: loaded.thread.status.type === 'idle' ? 'idle' : 'busy' };
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
async submit(text, clientId) {
|
|
60
|
+
this.guard();
|
|
61
|
+
if (!await verifyCodexBinding(this.socket, this.threadId, this.cid, this.name))
|
|
62
|
+
throw new FleetError('conflict', 'Native Ours identity changed');
|
|
63
|
+
await withCodex(this.socket, async (request) => {
|
|
64
|
+
this.guard();
|
|
65
|
+
await request('thread/queue/add', { threadId: this.threadId, clientUserMessageId: clientId, input: [{ type: 'text', text, text_elements: [] }] });
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
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 NativeMessage {
|
|
6
|
+
id: string;
|
|
7
|
+
role: 'user' | 'assistant';
|
|
8
|
+
text: string;
|
|
9
|
+
clientId?: string;
|
|
10
|
+
at?: string;
|
|
11
|
+
}
|
|
12
|
+
export interface NativeTranscript {
|
|
13
|
+
status: 'idle' | 'busy' | 'waiting' | 'unavailable';
|
|
14
|
+
messages: NativeMessage[];
|
|
15
|
+
queued: string[];
|
|
16
|
+
finished?: Array<{
|
|
17
|
+
clientId: string;
|
|
18
|
+
outcome: 'completed' | 'cancelled' | 'failed';
|
|
19
|
+
}>;
|
|
20
|
+
}
|
|
21
|
+
export interface NativeConversationTransport {
|
|
22
|
+
read(): Promise<NativeTranscript>;
|
|
23
|
+
submit(text: string, clientId: string): Promise<void>;
|
|
24
|
+
}
|
|
25
|
+
interface Options {
|
|
26
|
+
id: string;
|
|
27
|
+
cid: string;
|
|
28
|
+
harness: 'claude' | 'codex';
|
|
29
|
+
directory: string;
|
|
30
|
+
connected(): boolean;
|
|
31
|
+
native: NativeConversationTransport;
|
|
32
|
+
correspondence?: (request?: {
|
|
33
|
+
peer_cid: string;
|
|
34
|
+
limit?: number;
|
|
35
|
+
before_seq?: number;
|
|
36
|
+
}) => Promise<unknown>;
|
|
37
|
+
}
|
|
38
|
+
/** Native Human conversation implementation of Fleet's existing conversation contract. It never controls the native terminal. */
|
|
39
|
+
export declare class NativeConversation implements RoleSessionControl {
|
|
40
|
+
private options;
|
|
41
|
+
private store;
|
|
42
|
+
private generation;
|
|
43
|
+
private seen;
|
|
44
|
+
private commands;
|
|
45
|
+
private completed;
|
|
46
|
+
private nativeState;
|
|
47
|
+
private listeners;
|
|
48
|
+
private revision;
|
|
49
|
+
private syncing?;
|
|
50
|
+
private sending;
|
|
51
|
+
private timer?;
|
|
52
|
+
private follows;
|
|
53
|
+
private failed;
|
|
54
|
+
private disposed;
|
|
55
|
+
constructor(options: Options);
|
|
56
|
+
private commandPath;
|
|
57
|
+
private assertConnected;
|
|
58
|
+
private state;
|
|
59
|
+
private changed;
|
|
60
|
+
describe(): Promise<{
|
|
61
|
+
backend: "acp" | "codex-app-server";
|
|
62
|
+
protocolVersion: number;
|
|
63
|
+
features: string[];
|
|
64
|
+
snapshot: SessionSnapshot;
|
|
65
|
+
}>;
|
|
66
|
+
snapshot(): Promise<SessionSnapshot>;
|
|
67
|
+
agentContacts(): Promise<unknown>;
|
|
68
|
+
agentHistory(request: {
|
|
69
|
+
peer_cid: string;
|
|
70
|
+
limit?: number;
|
|
71
|
+
before_seq?: number;
|
|
72
|
+
}): Promise<unknown>;
|
|
73
|
+
recentOutput(): Promise<{
|
|
74
|
+
events: never[];
|
|
75
|
+
truncated: boolean;
|
|
76
|
+
}>;
|
|
77
|
+
sendText(text: string): Promise<{
|
|
78
|
+
accepted: boolean;
|
|
79
|
+
promptId: string;
|
|
80
|
+
queuedBehind: number;
|
|
81
|
+
terminalOutcomeKnown: boolean;
|
|
82
|
+
detail: string;
|
|
83
|
+
}>;
|
|
84
|
+
sync(): Promise<void>;
|
|
85
|
+
conversationPage(request?: {
|
|
86
|
+
after?: string;
|
|
87
|
+
limit?: number;
|
|
88
|
+
}): Promise<{
|
|
89
|
+
snapshot: ConversationObservationState;
|
|
90
|
+
events: ConversationEventV1[];
|
|
91
|
+
firstAvailableCursor?: string;
|
|
92
|
+
nextCursor?: string;
|
|
93
|
+
hasMore: boolean;
|
|
94
|
+
}>;
|
|
95
|
+
conversationTail(request?: {
|
|
96
|
+
before?: string;
|
|
97
|
+
limit?: number;
|
|
98
|
+
signal?: AbortSignal;
|
|
99
|
+
}): Promise<import("./conversation-history.js").ConversationTailPage>;
|
|
100
|
+
submitPromptV2(request: {
|
|
101
|
+
commandId: string;
|
|
102
|
+
text: string;
|
|
103
|
+
actorBrowserSession: string;
|
|
104
|
+
source: 'owner_admin_console';
|
|
105
|
+
expectedSessionGeneration?: string;
|
|
106
|
+
requireIdle?: boolean;
|
|
107
|
+
}): Promise<PromptReceipt>;
|
|
108
|
+
observeConversation(listener: (state: ConversationObservationState) => void): {
|
|
109
|
+
snapshot: ConversationObservationState;
|
|
110
|
+
unsubscribe: () => void;
|
|
111
|
+
};
|
|
112
|
+
subscribeConversation(listener: (event: ConversationEventV1) => void): () => void;
|
|
113
|
+
subscribeConversationFailure(listener: (generation: string) => void): () => void;
|
|
114
|
+
replayConversation(request: ConversationReplayRequest): AsyncGenerator<import("../session/conversation-replay.js").ConversationReplayPage, any, any>;
|
|
115
|
+
followConversation(request: LegacyConversationFollowRequest | PassiveConversationFollow): Promise<{
|
|
116
|
+
close: () => void;
|
|
117
|
+
}>;
|
|
118
|
+
close(): void;
|
|
119
|
+
}
|
|
120
|
+
export {};
|