@ours.network/fleet 2.4.1 → 2.4.3
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 +60 -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 +72 -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 +11 -0
- package/dist/native-codex-wake.js +207 -0
- package/dist/native-participation-cli.d.ts +62 -0
- package/dist/native-participation-cli.js +213 -0
- package/dist/native-participation.d.ts +68 -0
- package/dist/native-participation.js +326 -0
- package/dist/web/runtime.js +49 -3
- package/docs/native-session-participation.md +169 -0
- package/package.json +4 -3
|
@@ -11,7 +11,8 @@ export interface ResolvedRoleView {
|
|
|
11
11
|
coordinator?: string;
|
|
12
12
|
model?: string;
|
|
13
13
|
cwd?: string;
|
|
14
|
-
permissions
|
|
14
|
+
/** Absent when native terminal permissions are not controlled or observed by Fleet. */
|
|
15
|
+
permissions?: CommonPermissions;
|
|
15
16
|
nativeRuntime?: {
|
|
16
17
|
approval?: string;
|
|
17
18
|
permissionMode?: string;
|
|
@@ -23,6 +24,11 @@ export interface ResolvedRoleView {
|
|
|
23
24
|
}>;
|
|
24
25
|
}
|
|
25
26
|
export interface RoleRecord {
|
|
27
|
+
/** Independent native runtime; mail is addressed by CID, never a managed supervisor. */
|
|
28
|
+
nativeParticipation?: {
|
|
29
|
+
harness: 'claude' | 'codex';
|
|
30
|
+
cid: string;
|
|
31
|
+
};
|
|
26
32
|
id: string;
|
|
27
33
|
lifetime: RoleLifetime;
|
|
28
34
|
configured: boolean;
|
package/dist/build-info.json
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
|
-
"version": "2.4.
|
|
3
|
-
"buildId": "
|
|
4
|
-
"commit": "
|
|
2
|
+
"version": "2.4.3",
|
|
3
|
+
"buildId": "7a2716a3e63c",
|
|
4
|
+
"commit": "6f2d339f5b3cf7689704002b80fb3f970d787e83",
|
|
5
5
|
"dirty": false,
|
|
6
|
-
"builtAt": "2026-12-
|
|
6
|
+
"builtAt": "2026-12-03T09:26:41.738Z",
|
|
7
7
|
"capabilities": [
|
|
8
8
|
"service.refresh-v1",
|
|
9
9
|
"managed-cli.codex-reasoning-effort-v1",
|
package/dist/cli.js
CHANGED
|
@@ -58,6 +58,7 @@ import { beginFleetAuditCollection, consumeFleetAuditCollection, FleetCliExit, s
|
|
|
58
58
|
import './harness/claude-code.js'; // registers the claude-code adapter
|
|
59
59
|
import './harness/codex.js'; // registers the codex adapter
|
|
60
60
|
import './harness/hermes.js';
|
|
61
|
+
import { registerNativeParticipationCommands } from './native-participation-cli.js';
|
|
61
62
|
import { registerLayoutCommands } from './rooms-tasks/layout-cli.js';
|
|
62
63
|
import { MANAGED_CONFIGURATION_FLAG, assertPinnedConfiguration, enableManagedCli, managedCliReport, parseManagedEntry, } from './managed-cli.js';
|
|
63
64
|
import { MANAGED_CLI_WORKFLOW_IDS } from './config.js';
|
|
@@ -1884,6 +1885,7 @@ function configureWebAccess(opts) {
|
|
|
1884
1885
|
return undefined;
|
|
1885
1886
|
}
|
|
1886
1887
|
// ── rooms & tasks ──────────────────────────────────────────────────────────
|
|
1888
|
+
registerNativeParticipationCommands(program);
|
|
1887
1889
|
registerLayoutCommands(program, cOpt);
|
|
1888
1890
|
registerTemplateCommands(program, cOpt);
|
|
1889
1891
|
registerTaskCommands(program, cOpt);
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { NativeMessage } from './application/native-conversation.js';
|
|
2
|
+
/** Read only the file named by thread/read, and verify its embedded thread ID. */
|
|
3
|
+
export declare function readCodexHistory(path: string, threadId: string): Promise<{
|
|
4
|
+
messages: NativeMessage[];
|
|
5
|
+
finished: {
|
|
6
|
+
clientId: string;
|
|
7
|
+
outcome: "completed" | "cancelled" | "failed";
|
|
8
|
+
}[];
|
|
9
|
+
}>;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { open } from 'node:fs/promises';
|
|
2
|
+
import { constants } from 'node:fs';
|
|
3
|
+
import { createInterface } from 'node:readline';
|
|
4
|
+
/** Read only the file named by thread/read, and verify its embedded thread ID. */
|
|
5
|
+
export async function readCodexHistory(path, threadId) {
|
|
6
|
+
const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
7
|
+
const messages = new Map();
|
|
8
|
+
const clients = new Map();
|
|
9
|
+
const outcomes = new Map();
|
|
10
|
+
try {
|
|
11
|
+
const stat = await file.stat();
|
|
12
|
+
if (!stat.isFile() || stat.uid !== process.getuid?.())
|
|
13
|
+
throw Error('Native history must be a regular file owned by this user');
|
|
14
|
+
const lines = createInterface({ input: file.createReadStream(), crlfDelay: Infinity });
|
|
15
|
+
let first = true;
|
|
16
|
+
for await (const line of lines) {
|
|
17
|
+
if (!line)
|
|
18
|
+
continue;
|
|
19
|
+
let row;
|
|
20
|
+
try {
|
|
21
|
+
row = JSON.parse(line);
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
continue;
|
|
25
|
+
} // native writer may leave an incomplete final line
|
|
26
|
+
const p = row.payload;
|
|
27
|
+
if (first) {
|
|
28
|
+
first = false;
|
|
29
|
+
if (row.type !== 'session_meta' || p?.id !== threadId)
|
|
30
|
+
throw Error('Native history thread identity mismatch');
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
if (row.type !== 'event_msg')
|
|
34
|
+
continue;
|
|
35
|
+
if (p.type === 'task_complete')
|
|
36
|
+
outcomes.set(p.turn_id, 'completed');
|
|
37
|
+
if (p.type === 'turn_aborted')
|
|
38
|
+
outcomes.set(p.turn_id, 'cancelled');
|
|
39
|
+
if (p.type !== 'item_completed')
|
|
40
|
+
continue;
|
|
41
|
+
const item = p.item;
|
|
42
|
+
if (p.thread_id !== threadId || !item?.id || !['UserMessage', 'AgentMessage'].includes(item.type))
|
|
43
|
+
continue;
|
|
44
|
+
const text = (item.content ?? []).filter((b) => b.type === 'text' || b.type === 'Text').map((b) => b.text ?? '').join('\n');
|
|
45
|
+
if (!text)
|
|
46
|
+
continue;
|
|
47
|
+
messages.set(item.id, { id: item.id, role: item.type === 'UserMessage' ? 'user' : 'assistant', text, clientId: item.client_id, at: row.timestamp });
|
|
48
|
+
if (item.type === 'UserMessage' && item.client_id)
|
|
49
|
+
clients.set(p.turn_id, [...(clients.get(p.turn_id) ?? []), item.client_id]);
|
|
50
|
+
}
|
|
51
|
+
if (first)
|
|
52
|
+
throw Error('Native history has no session metadata');
|
|
53
|
+
const finished = [];
|
|
54
|
+
for (const [turn, outcome] of outcomes)
|
|
55
|
+
for (const clientId of clients.get(turn) ?? [])
|
|
56
|
+
finished.push({ clientId, outcome });
|
|
57
|
+
return { messages: [...messages.values()], finished };
|
|
58
|
+
}
|
|
59
|
+
finally {
|
|
60
|
+
await file.close().catch(() => { });
|
|
61
|
+
}
|
|
62
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export declare function validateCodexSocket(path: string): void;
|
|
2
|
+
export declare function withCodex<T>(path: string, run: (request: (method: string, params: object) => Promise<unknown>) => Promise<T>): Promise<T>;
|
|
3
|
+
export declare function listLoadedCodexThreads(path: string, metadata?: (id: string, value: {
|
|
4
|
+
title?: string;
|
|
5
|
+
cwd?: string;
|
|
6
|
+
}) => void): Promise<string[]>;
|
|
7
|
+
export declare function inspectCodexThread(path: string, threadId: string): Promise<'idle' | 'busy' | 'absent'>;
|
|
8
|
+
/** Read-only verification through the target runtime's actual MCP connection. */
|
|
9
|
+
export declare function verifyCodexBinding(path: string, threadId: string, cid: string, name: string): Promise<boolean>;
|
|
10
|
+
export declare function cancelCodexWakes(path: string, threadId: string, grant: string, cid?: string): Promise<void>;
|
|
11
|
+
export declare function wakeCodexThread(path: string, threadId: string, wakeId: string): Promise<boolean>;
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync } from 'node:fs';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { dirname, isAbsolute, join, normalize } from 'node:path';
|
|
4
|
+
import WebSocket from 'ws';
|
|
5
|
+
import { nativeParticipationRoot, wakePrompt } from './native-participation.js';
|
|
6
|
+
import { atomicPrivateWrite } from './agent-ours/state.js';
|
|
7
|
+
export function validateCodexSocket(path) {
|
|
8
|
+
if (!isAbsolute(path) || normalize(path) !== path || path.includes(':')) {
|
|
9
|
+
throw new Error('Provide a normalized absolute Codex Unix socket path.');
|
|
10
|
+
}
|
|
11
|
+
const uid = process.getuid?.();
|
|
12
|
+
const entry = lstatSync(path);
|
|
13
|
+
const target = realpathSync(path);
|
|
14
|
+
const socket = lstatSync(target);
|
|
15
|
+
// Current Codex uses a private short-path socket and a symlink at --listen.
|
|
16
|
+
// Both entry and endpoint must be protected by their enclosing directories.
|
|
17
|
+
const privateParent = (endpoint) => {
|
|
18
|
+
const parent = lstatSync(dirname(endpoint));
|
|
19
|
+
return parent.isDirectory() && parent.uid === uid && !(parent.mode & 0o077);
|
|
20
|
+
};
|
|
21
|
+
if (uid === undefined || !socket.isSocket() || entry.uid !== uid || socket.uid !== uid
|
|
22
|
+
|| !privateParent(path) || !privateParent(target)) {
|
|
23
|
+
throw new Error('The Codex Unix socket must be owned by this user in a private directory.');
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
// Requests are sequential and use a separate connection. The native TUI keeps
|
|
27
|
+
// handling input, interrupts, approvals and all server-initiated requests.
|
|
28
|
+
export async function withCodex(path, run) {
|
|
29
|
+
validateCodexSocket(path);
|
|
30
|
+
const socket = new WebSocket(`ws+unix://${path}:/`, { handshakeTimeout: 2500, maxPayload: 32 * 1024 * 1024 });
|
|
31
|
+
try {
|
|
32
|
+
await new Promise((resolve, reject) => {
|
|
33
|
+
socket.once('open', resolve);
|
|
34
|
+
socket.on('error', reject);
|
|
35
|
+
});
|
|
36
|
+
let nextId = 0;
|
|
37
|
+
async function request(method, params) {
|
|
38
|
+
const id = ++nextId;
|
|
39
|
+
return new Promise((resolve, reject) => {
|
|
40
|
+
function cleanup() {
|
|
41
|
+
clearTimeout(timeout);
|
|
42
|
+
socket.off('message', receive);
|
|
43
|
+
socket.off('close', closed);
|
|
44
|
+
}
|
|
45
|
+
function closed() {
|
|
46
|
+
cleanup();
|
|
47
|
+
reject(new Error('Codex App Server disconnected.'));
|
|
48
|
+
}
|
|
49
|
+
function receive(raw) {
|
|
50
|
+
let reply;
|
|
51
|
+
try {
|
|
52
|
+
reply = JSON.parse(String(raw));
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
if (reply?.id !== id || reply.method)
|
|
58
|
+
return;
|
|
59
|
+
cleanup();
|
|
60
|
+
if (reply.error)
|
|
61
|
+
reject(new Error(reply.error.message ?? 'Codex App Server rejected the request.'));
|
|
62
|
+
else
|
|
63
|
+
resolve(reply.result);
|
|
64
|
+
}
|
|
65
|
+
const timeout = setTimeout(() => {
|
|
66
|
+
cleanup();
|
|
67
|
+
reject(new Error(`Codex App Server did not acknowledge ${method}.`));
|
|
68
|
+
}, 3500);
|
|
69
|
+
socket.on('message', receive);
|
|
70
|
+
socket.once('close', closed);
|
|
71
|
+
socket.send(JSON.stringify({ id, method, params }), (error) => {
|
|
72
|
+
if (error) {
|
|
73
|
+
cleanup();
|
|
74
|
+
reject(error);
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
await request('initialize', { clientInfo: { name: 'ours_fleet', version: '0.1.0' },
|
|
80
|
+
capabilities: { experimentalApi: true } });
|
|
81
|
+
socket.send(JSON.stringify({ method: 'initialized', params: {} }));
|
|
82
|
+
return await run(request);
|
|
83
|
+
}
|
|
84
|
+
finally {
|
|
85
|
+
socket.terminate();
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
async function loadedThreads(request) {
|
|
89
|
+
const ids = [];
|
|
90
|
+
let cursor = null;
|
|
91
|
+
do {
|
|
92
|
+
const page = await request('thread/loaded/list', { limit: 100, cursor });
|
|
93
|
+
ids.push(...page.data);
|
|
94
|
+
cursor = page.nextCursor;
|
|
95
|
+
} while (cursor);
|
|
96
|
+
return ids;
|
|
97
|
+
}
|
|
98
|
+
async function readThread(request, threadId) {
|
|
99
|
+
const { thread } = await request('thread/read', { threadId, includeTurns: false });
|
|
100
|
+
return thread;
|
|
101
|
+
}
|
|
102
|
+
function interactive(thread, threadId) {
|
|
103
|
+
// The stock TUI on the default daemon is classified as vscode by Codex 0.172.
|
|
104
|
+
// Skip exec/internal threads; separately verify this runtime's Ours integration.
|
|
105
|
+
return thread?.id === threadId && !thread.ephemeral
|
|
106
|
+
&& (thread.source === 'cli' || thread.source === 'vscode');
|
|
107
|
+
}
|
|
108
|
+
async function hasOursIntegration(request, threadId) {
|
|
109
|
+
const result = await request('mcpServerStatus/list', {
|
|
110
|
+
threadId, serverName: 'ours', detail: 'toolsAndAuthOnly',
|
|
111
|
+
});
|
|
112
|
+
return result.data.some(server => server.name === 'ours' && server.runtimeStatus === 'connected'
|
|
113
|
+
&& Object.hasOwn(server.tools, 'get_messages') && Object.hasOwn(server.tools, 'send_message'));
|
|
114
|
+
}
|
|
115
|
+
export async function listLoadedCodexThreads(path, metadata) {
|
|
116
|
+
return withCodex(path, async (request) => {
|
|
117
|
+
const ids = await loadedThreads(request);
|
|
118
|
+
const eligible = [];
|
|
119
|
+
for (const id of ids) {
|
|
120
|
+
try {
|
|
121
|
+
const thread = await readThread(request, id);
|
|
122
|
+
if (interactive(thread, id) && await hasOursIntegration(request, id)) {
|
|
123
|
+
await queued(request, id);
|
|
124
|
+
eligible.push(id);
|
|
125
|
+
metadata?.(id, { title: thread?.name ?? '', cwd: thread?.cwd });
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
catch (error) {
|
|
129
|
+
// Ignore a confirmed unload race, not a missing capability or bad reply.
|
|
130
|
+
if ((await loadedThreads(request)).includes(id))
|
|
131
|
+
throw error;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return eligible;
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
export async function inspectCodexThread(path, threadId) {
|
|
138
|
+
return withCodex(path, request => inspectThread(request, threadId));
|
|
139
|
+
}
|
|
140
|
+
/** Read-only verification through the target runtime's actual MCP connection. */
|
|
141
|
+
export async function verifyCodexBinding(path, threadId, cid, name) {
|
|
142
|
+
return withCodex(path, async (request) => {
|
|
143
|
+
const result = await request('mcpServer/tool/call', {
|
|
144
|
+
threadId, server: 'ours', tool: 'current_identity', arguments: {},
|
|
145
|
+
});
|
|
146
|
+
return !result.isError && !!result.content?.some(item => item.type === 'text'
|
|
147
|
+
&& item.text?.startsWith(`Bound to "${name}" (${cid})`));
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
async function inspectThread(request, threadId) {
|
|
151
|
+
if (!(await loadedThreads(request)).includes(threadId))
|
|
152
|
+
return 'absent';
|
|
153
|
+
const thread = await readThread(request, threadId);
|
|
154
|
+
if (!interactive(thread, threadId) || thread?.status?.type === 'notLoaded')
|
|
155
|
+
return 'absent';
|
|
156
|
+
return thread?.status?.type === 'idle' ? 'idle' : 'busy';
|
|
157
|
+
}
|
|
158
|
+
async function queued(request, threadId) {
|
|
159
|
+
const result = [];
|
|
160
|
+
let cursor = null;
|
|
161
|
+
do {
|
|
162
|
+
const page = await request('thread/queue/list', { threadId, cursor, limit: 100 });
|
|
163
|
+
result.push(...page.data);
|
|
164
|
+
cursor = page.nextCursor;
|
|
165
|
+
} while (cursor);
|
|
166
|
+
return result;
|
|
167
|
+
}
|
|
168
|
+
export async function cancelCodexWakes(path, threadId, grant, cid) {
|
|
169
|
+
await withCodex(path, async (request) => {
|
|
170
|
+
for (const item of await queued(request, threadId)) {
|
|
171
|
+
if (item.clientUserMessageId?.startsWith(`ours-fleet:${grant}:${threadId}:`) || (cid && item.clientUserMessageId?.startsWith(`ours-fleet-human:${cid}:`)))
|
|
172
|
+
await request('thread/queue/delete', { threadId, queuedSubmissionId: item.id });
|
|
173
|
+
}
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
export async function wakeCodexThread(path, threadId, wakeId) {
|
|
177
|
+
return withCodex(path, async (request) => {
|
|
178
|
+
if (await inspectThread(request, threadId) === 'absent')
|
|
179
|
+
return false;
|
|
180
|
+
const digest = createHash('sha256').update(JSON.stringify([path, threadId, wakeId])).digest('hex');
|
|
181
|
+
const receipt = join(nativeParticipationRoot(), 'codex-wakes', digest + '.json');
|
|
182
|
+
if (existsSync(receipt)) {
|
|
183
|
+
if (JSON.parse(readFileSync(receipt, 'utf8')).accepted)
|
|
184
|
+
return true;
|
|
185
|
+
if ((await queued(request, threadId)).some(item => item.clientUserMessageId === wakeId))
|
|
186
|
+
return true;
|
|
187
|
+
let cursor = null;
|
|
188
|
+
do {
|
|
189
|
+
const page = await request('thread/items/list', { threadId, cursor, limit: 100, sortDirection: 'desc' });
|
|
190
|
+
if (page.data.some(({ item }) => item.type === 'userMessage' && item.clientId === wakeId))
|
|
191
|
+
return true;
|
|
192
|
+
cursor = page.nextCursor;
|
|
193
|
+
} while (cursor);
|
|
194
|
+
// Queue correlation IDs are not idempotency keys. An uncertain submission
|
|
195
|
+
// must not be blindly repeated, which could start a duplicate agent turn.
|
|
196
|
+
throw new Error('Codex wake acknowledgment is uncertain; waiting for queue/history reconciliation.');
|
|
197
|
+
}
|
|
198
|
+
// Verify support before persisting a submission intent.
|
|
199
|
+
await queued(request, threadId);
|
|
200
|
+
mkdirSync(dirname(receipt), { recursive: true, mode: 0o700 });
|
|
201
|
+
atomicPrivateWrite(receipt, { accepted: false });
|
|
202
|
+
await request('thread/queue/add', { threadId, clientUserMessageId: wakeId,
|
|
203
|
+
input: [{ type: 'text', text: wakePrompt, text_elements: [] }] });
|
|
204
|
+
atomicPrivateWrite(receipt, { accepted: true });
|
|
205
|
+
return true;
|
|
206
|
+
});
|
|
207
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { Command } from 'commander';
|
|
2
|
+
export declare function claudeNativeHooks(executable: string, entry: string): {
|
|
3
|
+
hooks: {
|
|
4
|
+
SessionStart: {
|
|
5
|
+
hooks: ({
|
|
6
|
+
asyncRewake: true;
|
|
7
|
+
timeout: number;
|
|
8
|
+
type: string;
|
|
9
|
+
command: string;
|
|
10
|
+
args: string[];
|
|
11
|
+
} | {
|
|
12
|
+
timeout: number;
|
|
13
|
+
type: string;
|
|
14
|
+
command: string;
|
|
15
|
+
args: string[];
|
|
16
|
+
})[];
|
|
17
|
+
}[];
|
|
18
|
+
Stop: {
|
|
19
|
+
hooks: ({
|
|
20
|
+
asyncRewake: true;
|
|
21
|
+
timeout: number;
|
|
22
|
+
type: string;
|
|
23
|
+
command: string;
|
|
24
|
+
args: string[];
|
|
25
|
+
} | {
|
|
26
|
+
timeout: number;
|
|
27
|
+
type: string;
|
|
28
|
+
command: string;
|
|
29
|
+
args: string[];
|
|
30
|
+
})[];
|
|
31
|
+
}[];
|
|
32
|
+
SessionEnd: {
|
|
33
|
+
hooks: ({
|
|
34
|
+
asyncRewake: true;
|
|
35
|
+
timeout: number;
|
|
36
|
+
type: string;
|
|
37
|
+
command: string;
|
|
38
|
+
args: string[];
|
|
39
|
+
} | {
|
|
40
|
+
timeout: number;
|
|
41
|
+
type: string;
|
|
42
|
+
command: string;
|
|
43
|
+
args: string[];
|
|
44
|
+
})[];
|
|
45
|
+
}[];
|
|
46
|
+
UserPromptSubmit: {
|
|
47
|
+
hooks: ({
|
|
48
|
+
asyncRewake: true;
|
|
49
|
+
timeout: number;
|
|
50
|
+
type: string;
|
|
51
|
+
command: string;
|
|
52
|
+
args: string[];
|
|
53
|
+
} | {
|
|
54
|
+
timeout: number;
|
|
55
|
+
type: string;
|
|
56
|
+
command: string;
|
|
57
|
+
args: string[];
|
|
58
|
+
})[];
|
|
59
|
+
}[];
|
|
60
|
+
};
|
|
61
|
+
};
|
|
62
|
+
export declare function registerNativeParticipationCommands(program: Command): void;
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { NativeClaudeConversation } from './application/native-claude-conversation.js';
|
|
3
|
+
import { realpathSync } from 'node:fs';
|
|
4
|
+
import { join, resolve } from 'node:path';
|
|
5
|
+
import { homedir } from 'node:os';
|
|
6
|
+
import { setTimeout as sleep } from 'node:timers/promises';
|
|
7
|
+
import { InvalidArgumentError } from 'commander';
|
|
8
|
+
import { inspectCodexThread, listLoadedCodexThreads, validateCodexSocket, verifyCodexBinding, wakeCodexThread } from './native-codex-wake.js';
|
|
9
|
+
import { NativeParticipation, nativeHostProfile, nativeParticipationRoot, wakePrompt } from './native-participation.js';
|
|
10
|
+
function harness(value) {
|
|
11
|
+
if (value === 'claude' || value === 'codex')
|
|
12
|
+
return value;
|
|
13
|
+
throw new InvalidArgumentError('Choose claude or codex.');
|
|
14
|
+
}
|
|
15
|
+
function nativeId(value) {
|
|
16
|
+
if (typeof value !== 'string' || !/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(value)) {
|
|
17
|
+
throw new InvalidArgumentError('Expected a native session UUID.');
|
|
18
|
+
}
|
|
19
|
+
return value;
|
|
20
|
+
}
|
|
21
|
+
async function hookInput() {
|
|
22
|
+
let input = '';
|
|
23
|
+
process.stdin.setEncoding('utf8');
|
|
24
|
+
for await (const chunk of process.stdin) {
|
|
25
|
+
input += chunk;
|
|
26
|
+
if (input.length > 128 * 1024)
|
|
27
|
+
throw new Error('Native hook payload exceeded 128 KiB.');
|
|
28
|
+
}
|
|
29
|
+
const value = JSON.parse(input);
|
|
30
|
+
if (typeof value.hook_event_name !== 'string')
|
|
31
|
+
throw new Error('Expected a native hook event.');
|
|
32
|
+
return { session: nativeId(value.session_id), event: value.hook_event_name, ...(typeof value.session_title === 'string' ? { title: value.session_title } : {}), ...(typeof value.cwd === 'string' ? { cwd: value.cwd } : {}) };
|
|
33
|
+
}
|
|
34
|
+
export function claudeNativeHooks(executable, entry) {
|
|
35
|
+
function hook(asyncRewake = false) {
|
|
36
|
+
return { type: 'command', command: executable, args: [entry, 'participation', 'hook'],
|
|
37
|
+
...(asyncRewake ? { asyncRewake, timeout: 86_400 } : { timeout: 30 }) };
|
|
38
|
+
}
|
|
39
|
+
return { hooks: {
|
|
40
|
+
SessionStart: [{ hooks: [hook(true)] }],
|
|
41
|
+
Stop: [{ hooks: [hook(true)] }],
|
|
42
|
+
SessionEnd: [{ hooks: [hook()] }],
|
|
43
|
+
UserPromptSubmit: [{ hooks: [hook()] }],
|
|
44
|
+
} };
|
|
45
|
+
}
|
|
46
|
+
async function serveCodex(store) {
|
|
47
|
+
const grant = store.authorization();
|
|
48
|
+
if (!grant?.codexSocket)
|
|
49
|
+
throw new Error('Enable participation with --codex first.');
|
|
50
|
+
const workers = new Map();
|
|
51
|
+
const retryAfter = new Map();
|
|
52
|
+
while (store.authorization()?.grant === grant.grant) {
|
|
53
|
+
let ids;
|
|
54
|
+
try {
|
|
55
|
+
ids = await listLoadedCodexThreads(grant.codexSocket, (id, metadata) => store.setMetadata('codex', id, metadata));
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
console.error('Waiting for the Codex App Server:', error.message);
|
|
59
|
+
await sleep(2500);
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
for (const [id, worker] of workers)
|
|
63
|
+
if (!ids.includes(id))
|
|
64
|
+
worker.controller.abort();
|
|
65
|
+
for (const id of retryAfter.keys())
|
|
66
|
+
if (!ids.includes(id))
|
|
67
|
+
retryAfter.delete(id);
|
|
68
|
+
for (const id of ids) {
|
|
69
|
+
if (workers.has(id) || (retryAfter.get(id) ?? 0) > Date.now())
|
|
70
|
+
continue;
|
|
71
|
+
const controller = new AbortController();
|
|
72
|
+
const task = watch(store, 'codex', nativeId(id), controller.signal).then(() => { retryAfter.set(id, Date.now() + 30_000); })
|
|
73
|
+
.catch((error) => { retryAfter.set(id, Date.now() + 30_000); console.error('Codex participant:', error.message); })
|
|
74
|
+
.finally(() => workers.delete(id));
|
|
75
|
+
workers.set(id, { task, controller });
|
|
76
|
+
}
|
|
77
|
+
await sleep(1000);
|
|
78
|
+
}
|
|
79
|
+
for (const worker of workers.values())
|
|
80
|
+
worker.controller.abort();
|
|
81
|
+
await Promise.all([...workers.values()].map(worker => worker.task));
|
|
82
|
+
}
|
|
83
|
+
async function watch(store, host, session, signal) {
|
|
84
|
+
const grant = store.authorization();
|
|
85
|
+
if (!grant)
|
|
86
|
+
return;
|
|
87
|
+
await store.watch(host, session, async () => {
|
|
88
|
+
const socket = grant.codexSocket;
|
|
89
|
+
if (host === 'codex' && (!socket || await inspectCodexThread(socket, session) === 'absent'))
|
|
90
|
+
return;
|
|
91
|
+
let binding;
|
|
92
|
+
if (!await store.start(host, session, host === 'codex' && socket ? async (cid, name) => {
|
|
93
|
+
binding = { cid, name };
|
|
94
|
+
return verifyCodexBinding(socket, session, cid, name);
|
|
95
|
+
} : undefined))
|
|
96
|
+
return;
|
|
97
|
+
let unreachable = 0;
|
|
98
|
+
while (!signal?.aborted && store.authorization()?.grant === grant.grant) {
|
|
99
|
+
try {
|
|
100
|
+
if (host === 'codex' && socket && await inspectCodexThread(socket, session) === 'absent') {
|
|
101
|
+
if (++unreachable >= 3)
|
|
102
|
+
break;
|
|
103
|
+
await sleep(1000);
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
const result = await store.poll(host, session, host === 'codex' && socket ? async (wakeId) => {
|
|
107
|
+
if (!binding || !await verifyCodexBinding(socket, session, binding.cid, binding.name))
|
|
108
|
+
throw new Error('The target Codex runtime no longer has the authorized Ours identity.');
|
|
109
|
+
return wakeCodexThread(socket, session, wakeId);
|
|
110
|
+
} : async () => true, signal);
|
|
111
|
+
unreachable = 0;
|
|
112
|
+
if (result === 'end')
|
|
113
|
+
return;
|
|
114
|
+
if (result === 'wake' && host === 'claude') {
|
|
115
|
+
console.error(wakePrompt);
|
|
116
|
+
process.exitCode = 2;
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
if (signal?.aborted)
|
|
122
|
+
break;
|
|
123
|
+
if (++unreachable >= 3) {
|
|
124
|
+
console.error('Native participation watcher stopped:', error.message);
|
|
125
|
+
break;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
await sleep(1000);
|
|
129
|
+
}
|
|
130
|
+
await store.leave(host, session, false);
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
export function registerNativeParticipationCommands(program) {
|
|
134
|
+
const participation = program.command('participation')
|
|
135
|
+
.description('Experiment for ordinary terminal sessions that join Fleet voluntarily');
|
|
136
|
+
const store = async () => new NativeParticipation(await nativeHostProfile());
|
|
137
|
+
participation.command('enable')
|
|
138
|
+
.description('Authorize automatic registration and peer-triggered wake under one Human')
|
|
139
|
+
.requiredOption('--human-cid <cid>', 'Human root CID from this Ours MCP profile')
|
|
140
|
+
.requiredOption('--authorize-registration-and-wake', 'explicitly grant both capabilities')
|
|
141
|
+
.option('--codex', 'discover sessions on the standard local Codex App Server')
|
|
142
|
+
.option('--codex-socket <absolute-path>', 'private socket of the App Server serving the Codex terminal')
|
|
143
|
+
.action(async ({ humanCid, codex, codexSocket }) => {
|
|
144
|
+
if (codex && codexSocket)
|
|
145
|
+
throw new Error('Choose --codex or --codex-socket, not both.');
|
|
146
|
+
if (codex)
|
|
147
|
+
codexSocket = join(process.env.CODEX_HOME ?? join(homedir(), '.codex'), 'app-server-control', 'app-server-control.sock');
|
|
148
|
+
if (codexSocket)
|
|
149
|
+
validateCodexSocket(codexSocket);
|
|
150
|
+
await (await store()).authorize(humanCid, codexSocket);
|
|
151
|
+
});
|
|
152
|
+
participation.command('disable').description('Revoke the local grant and withdraw its sessions')
|
|
153
|
+
.action(async () => (await store()).disable());
|
|
154
|
+
participation.command('ls').description('List currently connected native participants')
|
|
155
|
+
.option('--json', 'output JSON')
|
|
156
|
+
.action(async ({ json }) => {
|
|
157
|
+
const rows = (await store()).list();
|
|
158
|
+
if (json)
|
|
159
|
+
console.log(JSON.stringify(rows));
|
|
160
|
+
else if (rows.length === 0)
|
|
161
|
+
console.log('No connected native participants.');
|
|
162
|
+
else
|
|
163
|
+
for (const row of rows)
|
|
164
|
+
console.log(`${row.name}\t${row.harness}\t${row.cid}`);
|
|
165
|
+
});
|
|
166
|
+
participation.command('leave').description('Withdraw one session while keeping its native conversation open')
|
|
167
|
+
.argument('<harness>', 'claude or codex', harness)
|
|
168
|
+
.argument('<session-id>', 'native session UUID', nativeId)
|
|
169
|
+
.action(async (host, session) => (await store()).leave(host, session));
|
|
170
|
+
participation.command('hooks').description('Print Claude Code user-scope hook configuration')
|
|
171
|
+
.argument('<harness>', 'claude', harness)
|
|
172
|
+
.action((host) => {
|
|
173
|
+
if (host !== 'claude')
|
|
174
|
+
throw new Error('Codex discovery uses participation serve-codex.');
|
|
175
|
+
console.log(JSON.stringify(claudeNativeHooks(process.execPath, realpathSync(resolve(process.argv[1]))), null, 2));
|
|
176
|
+
});
|
|
177
|
+
participation.command('hook', { hidden: true })
|
|
178
|
+
.action(async () => {
|
|
179
|
+
const { event, session, title, cwd } = await hookInput();
|
|
180
|
+
const registry = await store();
|
|
181
|
+
if (event !== 'SessionEnd')
|
|
182
|
+
registry.setMetadata('claude', session, { title, cwd });
|
|
183
|
+
if (event === 'SessionEnd')
|
|
184
|
+
await registry.leave('claude', session, false);
|
|
185
|
+
else if (event === 'SessionStart' || event === 'Stop')
|
|
186
|
+
await watch(registry, 'claude', session);
|
|
187
|
+
});
|
|
188
|
+
participation.command('claude-bridge', { hidden: true }).argument('<session-id>', 'native session UUID', nativeId).action(async (session) => {
|
|
189
|
+
let input = '';
|
|
190
|
+
for await (const chunk of process.stdin) {
|
|
191
|
+
input += chunk;
|
|
192
|
+
if (input.length > 1024 * 1024)
|
|
193
|
+
throw Error('Claude bridge payload too large');
|
|
194
|
+
}
|
|
195
|
+
const registry = await store(), grant = registry.authorization();
|
|
196
|
+
const row = registry.list().find(r => r.harness === 'claude' && registry.participant(r.name)?.nativeId === session);
|
|
197
|
+
if (!row || !grant) {
|
|
198
|
+
console.log('{}');
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
const state = JSON.parse(input);
|
|
202
|
+
if (typeof state.transcriptPath !== 'string' || !['idle', 'busy', 'waiting'].includes(state.status) || typeof state.correlations !== 'object' || !Array.isArray(state.finished))
|
|
203
|
+
throw Error('Invalid Claude bridge state');
|
|
204
|
+
const key = `${grant.rootCid}:${row.cid}:${grant.grant}`;
|
|
205
|
+
const guard = () => { if (registry.authorization()?.grant !== grant.grant || !registry.list().some(r => r.cid === row.cid))
|
|
206
|
+
throw Error('Native participation withdrawn'); };
|
|
207
|
+
const bridge = new NativeClaudeConversation(join(nativeParticipationRoot(), 'native-conversations', createHash('sha256').update(key).digest('hex'), 'bridge'), session, guard);
|
|
208
|
+
console.log(JSON.stringify(await bridge.pulse(state)));
|
|
209
|
+
});
|
|
210
|
+
participation.command('serve-codex')
|
|
211
|
+
.description('Discover native conversations on the authorized local Codex App Server and wake them on mail')
|
|
212
|
+
.action(async () => serveCodex(await store()));
|
|
213
|
+
}
|