helixbox-stellar-cli 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/LICENSE +7 -0
- package/README.md +118 -3
- package/dist/ai/cli.d.ts +59 -0
- package/dist/ai/cli.js +193 -0
- package/dist/ai/codex.d.ts +149 -0
- package/dist/ai/codex.js +2133 -0
- package/dist/ai/index.d.ts +59 -0
- package/dist/ai/index.js +131 -0
- package/dist/ai/interface.d.ts +93 -0
- package/dist/ai/interface.js +3 -0
- package/dist/ai/model-mcp.d.ts +1 -0
- package/dist/ai/model-mcp.js +66 -0
- package/dist/ai/model-tools.d.ts +30 -0
- package/dist/ai/model-tools.js +101 -0
- package/dist/ai/opencode.d.ts +72 -0
- package/dist/ai/opencode.js +883 -0
- package/dist/backend-config.d.ts +4 -0
- package/dist/backend-config.js +6 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +3364 -0
- package/dist/transport/protocol.d.ts +77 -0
- package/dist/transport/protocol.js +79 -0
- package/dist/transport/v2.d.ts +47 -0
- package/dist/transport/v2.js +347 -0
- package/package.json +54 -6
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { AiEvent, ModelSelector, FileAttachment, CodexPromptOptions } from "./interface.js";
|
|
2
|
+
export type AiBackend = "opencode" | "codex" | "claude" | "hermes";
|
|
3
|
+
export declare const AI_BACKENDS: readonly AiBackend[];
|
|
4
|
+
export declare function isAiBackend(value: unknown): value is AiBackend;
|
|
5
|
+
export declare class AiManager {
|
|
6
|
+
private _providers;
|
|
7
|
+
private _available;
|
|
8
|
+
init(): Promise<void>;
|
|
9
|
+
private tryInit;
|
|
10
|
+
availableBackends(): AiBackend[];
|
|
11
|
+
private get;
|
|
12
|
+
subscribe(emitter: (backend: AiBackend, event: AiEvent) => void): () => void;
|
|
13
|
+
destroy(): Promise<void>;
|
|
14
|
+
listAllSessions(): Promise<{
|
|
15
|
+
sessions: Array<Record<string, unknown> & {
|
|
16
|
+
backend: AiBackend;
|
|
17
|
+
}>;
|
|
18
|
+
}>;
|
|
19
|
+
createSession(backend: AiBackend, title?: string): Promise<{
|
|
20
|
+
session: import("./interface.js").SessionInfo;
|
|
21
|
+
}>;
|
|
22
|
+
getSession(backend: AiBackend, id: string): Promise<{
|
|
23
|
+
session: import("./interface.js").SessionInfo;
|
|
24
|
+
}>;
|
|
25
|
+
deleteSession(backend: AiBackend, id: string): Promise<{
|
|
26
|
+
deleted: boolean;
|
|
27
|
+
}>;
|
|
28
|
+
renameSession(backend: AiBackend, id: string, title: string): Promise<{
|
|
29
|
+
session: import("./interface.js").SessionInfo;
|
|
30
|
+
}>;
|
|
31
|
+
getMessages(backend: AiBackend, sessionId: string): Promise<{
|
|
32
|
+
messages: import("./interface.js").MessageInfo[];
|
|
33
|
+
}>;
|
|
34
|
+
statuses(backend: AiBackend): Promise<{
|
|
35
|
+
statuses: Record<string, unknown>;
|
|
36
|
+
}>;
|
|
37
|
+
prompt(backend: AiBackend, sessionId: string, text: string, model?: ModelSelector, agent?: string, files?: FileAttachment[], codexOptions?: CodexPromptOptions): Promise<{
|
|
38
|
+
ack: true;
|
|
39
|
+
}>;
|
|
40
|
+
abort(backend: AiBackend, sessionId: string): Promise<Record<string, never>>;
|
|
41
|
+
agents(backend?: AiBackend): Promise<{
|
|
42
|
+
agents: unknown;
|
|
43
|
+
}>;
|
|
44
|
+
providers(backend?: AiBackend): Promise<import("./interface.js").ProviderInfo>;
|
|
45
|
+
setAuth(backend: AiBackend, providerId: string, key: string): Promise<Record<string, never>>;
|
|
46
|
+
command(backend: AiBackend, sessionId: string, command: string, args: string): Promise<{
|
|
47
|
+
result: unknown;
|
|
48
|
+
}>;
|
|
49
|
+
revert(backend: AiBackend, sessionId: string, messageId: string): Promise<Record<string, never>>;
|
|
50
|
+
unrevert(backend: AiBackend, sessionId: string): Promise<Record<string, never>>;
|
|
51
|
+
share(backend: AiBackend, sessionId: string): Promise<{
|
|
52
|
+
share: import("./interface.js").ShareInfo;
|
|
53
|
+
}>;
|
|
54
|
+
permissionReply(backend: AiBackend, sessionId: string, permissionId: string, response: "once" | "always" | "reject"): Promise<Record<string, never>>;
|
|
55
|
+
questionReply(backend: AiBackend, sessionId: string, questionId: string, answers: string[][]): Promise<Record<string, never>>;
|
|
56
|
+
questionReject(backend: AiBackend, sessionId: string, questionId: string): Promise<Record<string, never>>;
|
|
57
|
+
}
|
|
58
|
+
export declare function createAiManager(): Promise<AiManager>;
|
|
59
|
+
export type { AIProvider, AiEventEmitter, AiEvent, ModelSelector } from "./interface.js";
|
package/dist/ai/index.js
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// AI manager — runs every installed provider simultaneously and routes calls
|
|
2
|
+
// by the `backend` field in each request. Backends that fail to init are
|
|
3
|
+
// skipped gracefully; the available list is exposed to the app.
|
|
4
|
+
export const AI_BACKENDS = ["opencode", "codex", "claude", "hermes"];
|
|
5
|
+
export function isAiBackend(value) {
|
|
6
|
+
return typeof value === "string" && AI_BACKENDS.includes(value);
|
|
7
|
+
}
|
|
8
|
+
const DEBUG_MODE = process.env.HELIXBOX_DEBUG === "1" || process.env.HELIXBOX_DEBUG_AI === "1";
|
|
9
|
+
export class AiManager {
|
|
10
|
+
_providers = {};
|
|
11
|
+
_available = [];
|
|
12
|
+
async init() {
|
|
13
|
+
await Promise.allSettled([
|
|
14
|
+
this.tryInit("opencode"),
|
|
15
|
+
this.tryInit("codex"),
|
|
16
|
+
this.tryInit("claude"),
|
|
17
|
+
this.tryInit("hermes"),
|
|
18
|
+
]);
|
|
19
|
+
if (this._available.length === 0) {
|
|
20
|
+
console.warn("[ai] No AI backends available. CLI will continue without AI features.");
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
if (DEBUG_MODE) {
|
|
24
|
+
console.log(`[ai] Available backends: ${this._available.join(", ")}`);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
async tryInit(backend) {
|
|
28
|
+
try {
|
|
29
|
+
if (backend === "opencode") {
|
|
30
|
+
const { OpenCodeProvider } = await import("./opencode.js");
|
|
31
|
+
const p = new OpenCodeProvider();
|
|
32
|
+
await p.init();
|
|
33
|
+
this._providers.opencode = p;
|
|
34
|
+
}
|
|
35
|
+
else if (backend === "codex") {
|
|
36
|
+
const { CodexProvider } = await import("./codex.js");
|
|
37
|
+
const p = new CodexProvider();
|
|
38
|
+
await p.init();
|
|
39
|
+
this._providers.codex = p;
|
|
40
|
+
}
|
|
41
|
+
else {
|
|
42
|
+
const { CliAgentProvider } = await import("./cli.js");
|
|
43
|
+
const p = new CliAgentProvider(backend);
|
|
44
|
+
await p.init();
|
|
45
|
+
this._providers[backend] = p;
|
|
46
|
+
}
|
|
47
|
+
this._available.push(backend);
|
|
48
|
+
}
|
|
49
|
+
catch (err) {
|
|
50
|
+
if (DEBUG_MODE) {
|
|
51
|
+
console.warn(`[ai] ${backend} backend unavailable: ${err.message}`);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
availableBackends() {
|
|
56
|
+
return [...this._available];
|
|
57
|
+
}
|
|
58
|
+
get(backend) {
|
|
59
|
+
const p = this._providers[backend];
|
|
60
|
+
if (!p) {
|
|
61
|
+
throw Object.assign(new Error(`Backend "${backend}" is not available`), { code: "EUNAVAILABLE" });
|
|
62
|
+
}
|
|
63
|
+
return p;
|
|
64
|
+
}
|
|
65
|
+
// Wire each provider's events to the emitter, tagged with backend name.
|
|
66
|
+
subscribe(emitter) {
|
|
67
|
+
const cleanups = this._available.map((backend) => this._providers[backend].subscribe((event) => emitter(backend, event)));
|
|
68
|
+
return () => cleanups.forEach((c) => c());
|
|
69
|
+
}
|
|
70
|
+
async destroy() {
|
|
71
|
+
await Promise.allSettled(this._available.map((b) => this._providers[b].destroy()));
|
|
72
|
+
}
|
|
73
|
+
// List sessions from all available backends, each tagged with its backend.
|
|
74
|
+
async listAllSessions() {
|
|
75
|
+
const results = await Promise.allSettled(this._available.map(async (backend) => {
|
|
76
|
+
const res = await this._providers[backend].listSessions();
|
|
77
|
+
const sessions = res.sessions ?? [];
|
|
78
|
+
return sessions.map((s) => ({ ...s, backend }));
|
|
79
|
+
}));
|
|
80
|
+
const sessions = results.flatMap((r) => (r.status === "fulfilled" ? r.value : []));
|
|
81
|
+
return { sessions };
|
|
82
|
+
}
|
|
83
|
+
// Session management — all require explicit backend
|
|
84
|
+
createSession(backend, title) { return this.get(backend).createSession(title); }
|
|
85
|
+
getSession(backend, id) { return this.get(backend).getSession(id); }
|
|
86
|
+
deleteSession(backend, id) { return this.get(backend).deleteSession(id); }
|
|
87
|
+
renameSession(backend, id, title) { return this.get(backend).renameSession(id, title); }
|
|
88
|
+
getMessages(backend, sessionId) { return this.get(backend).getMessages(sessionId); }
|
|
89
|
+
async statuses(backend) {
|
|
90
|
+
const provider = this.get(backend);
|
|
91
|
+
if (!provider.statuses)
|
|
92
|
+
return { statuses: {} };
|
|
93
|
+
return provider.statuses();
|
|
94
|
+
}
|
|
95
|
+
prompt(backend, sessionId, text, model, agent, files, codexOptions) {
|
|
96
|
+
this.get(backend).setActiveSession?.(sessionId);
|
|
97
|
+
return this.get(backend).prompt(sessionId, text, model, agent, files, codexOptions);
|
|
98
|
+
}
|
|
99
|
+
abort(backend, sessionId) { return this.get(backend).abort(sessionId); }
|
|
100
|
+
// Metadata — backend is optional, falls back to first available
|
|
101
|
+
agents(backend) { return this.get(backend ?? this._available[0]).agents(); }
|
|
102
|
+
providers(backend) { return this.get(backend ?? this._available[0]).providers(); }
|
|
103
|
+
setAuth(backend, providerId, key) { return this.get(backend).setAuth(providerId, key); }
|
|
104
|
+
// Session operations
|
|
105
|
+
command(backend, sessionId, command, args) { return this.get(backend).command(sessionId, command, args); }
|
|
106
|
+
revert(backend, sessionId, messageId) { return this.get(backend).revert(sessionId, messageId); }
|
|
107
|
+
unrevert(backend, sessionId) { return this.get(backend).unrevert(sessionId); }
|
|
108
|
+
share(backend, sessionId) { return this.get(backend).share(sessionId); }
|
|
109
|
+
permissionReply(backend, sessionId, permissionId, response) {
|
|
110
|
+
return this.get(backend).permissionReply(sessionId, permissionId, response);
|
|
111
|
+
}
|
|
112
|
+
questionReply(backend, sessionId, questionId, answers) {
|
|
113
|
+
const provider = this.get(backend);
|
|
114
|
+
if (!provider.questionReply) {
|
|
115
|
+
throw new Error(`Backend "${backend}" does not support question replies`);
|
|
116
|
+
}
|
|
117
|
+
return provider.questionReply(sessionId, questionId, answers);
|
|
118
|
+
}
|
|
119
|
+
questionReject(backend, sessionId, questionId) {
|
|
120
|
+
const provider = this.get(backend);
|
|
121
|
+
if (!provider.questionReject) {
|
|
122
|
+
throw new Error(`Backend "${backend}" does not support question rejection`);
|
|
123
|
+
}
|
|
124
|
+
return provider.questionReject(sessionId, questionId);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
export async function createAiManager() {
|
|
128
|
+
const manager = new AiManager();
|
|
129
|
+
await manager.init();
|
|
130
|
+
return manager;
|
|
131
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
export interface AiEvent {
|
|
2
|
+
type: string;
|
|
3
|
+
properties: Record<string, unknown>;
|
|
4
|
+
}
|
|
5
|
+
export type AiEventEmitter = (event: AiEvent) => void;
|
|
6
|
+
export interface ModelSelector {
|
|
7
|
+
providerID: string;
|
|
8
|
+
modelID: string;
|
|
9
|
+
}
|
|
10
|
+
export interface CodexPromptOptions {
|
|
11
|
+
reasoningEffort?: string;
|
|
12
|
+
speed?: string;
|
|
13
|
+
permissionMode?: "default" | "full-access";
|
|
14
|
+
}
|
|
15
|
+
export interface FileAttachment {
|
|
16
|
+
type: "file";
|
|
17
|
+
mime: string;
|
|
18
|
+
filename?: string;
|
|
19
|
+
url: string;
|
|
20
|
+
}
|
|
21
|
+
export interface MessageInfo {
|
|
22
|
+
id: string;
|
|
23
|
+
role: string;
|
|
24
|
+
parts: unknown[];
|
|
25
|
+
time: unknown;
|
|
26
|
+
}
|
|
27
|
+
export interface SessionInfo {
|
|
28
|
+
[key: string]: unknown;
|
|
29
|
+
}
|
|
30
|
+
export interface ShareInfo {
|
|
31
|
+
[key: string]: unknown;
|
|
32
|
+
}
|
|
33
|
+
export interface ProviderInfo {
|
|
34
|
+
providers: unknown[];
|
|
35
|
+
default: Record<string, string>;
|
|
36
|
+
[key: string]: unknown;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Every AI backend (OpenCode, Codex, …) implements this interface.
|
|
40
|
+
* Method names map 1-to-1 with the "ai" namespace actions in index.ts.
|
|
41
|
+
*/
|
|
42
|
+
export interface AIProvider {
|
|
43
|
+
init(): Promise<void>;
|
|
44
|
+
destroy(): Promise<void>;
|
|
45
|
+
/**
|
|
46
|
+
* Register an event emitter. The provider calls it for every async event
|
|
47
|
+
* (SSE events, streaming tokens, errors, etc.).
|
|
48
|
+
* Returns a cleanup/unsubscribe function.
|
|
49
|
+
*/
|
|
50
|
+
subscribe(emitter: AiEventEmitter): () => void;
|
|
51
|
+
setActiveSession?(sessionId: string): void;
|
|
52
|
+
createSession(title?: string): Promise<{
|
|
53
|
+
session: SessionInfo;
|
|
54
|
+
}>;
|
|
55
|
+
listSessions(): Promise<{
|
|
56
|
+
sessions: unknown;
|
|
57
|
+
}>;
|
|
58
|
+
getSession(id: string): Promise<{
|
|
59
|
+
session: SessionInfo;
|
|
60
|
+
}>;
|
|
61
|
+
deleteSession(id: string): Promise<{
|
|
62
|
+
deleted: boolean;
|
|
63
|
+
}>;
|
|
64
|
+
renameSession(id: string, title: string): Promise<{
|
|
65
|
+
session: SessionInfo;
|
|
66
|
+
}>;
|
|
67
|
+
getMessages(sessionId: string): Promise<{
|
|
68
|
+
messages: MessageInfo[];
|
|
69
|
+
}>;
|
|
70
|
+
statuses?(): Promise<{
|
|
71
|
+
statuses: Record<string, unknown>;
|
|
72
|
+
}>;
|
|
73
|
+
prompt(sessionId: string, text: string, model?: ModelSelector, agent?: string, files?: FileAttachment[], codexOptions?: CodexPromptOptions): Promise<{
|
|
74
|
+
ack: true;
|
|
75
|
+
}>;
|
|
76
|
+
abort(sessionId: string): Promise<Record<string, never>>;
|
|
77
|
+
agents(): Promise<{
|
|
78
|
+
agents: unknown;
|
|
79
|
+
}>;
|
|
80
|
+
providers(): Promise<ProviderInfo>;
|
|
81
|
+
setAuth(providerId: string, key: string): Promise<Record<string, never>>;
|
|
82
|
+
command(sessionId: string, command: string, args: string): Promise<{
|
|
83
|
+
result: unknown;
|
|
84
|
+
}>;
|
|
85
|
+
revert(sessionId: string, messageId: string): Promise<Record<string, never>>;
|
|
86
|
+
unrevert(sessionId: string): Promise<Record<string, never>>;
|
|
87
|
+
share(sessionId: string): Promise<{
|
|
88
|
+
share: ShareInfo;
|
|
89
|
+
}>;
|
|
90
|
+
permissionReply(sessionId: string, permissionId: string, response: "once" | "always" | "reject"): Promise<Record<string, never>>;
|
|
91
|
+
questionReply?(sessionId: string, questionId: string, answers: string[][]): Promise<Record<string, never>>;
|
|
92
|
+
questionReject?(sessionId: string, questionId: string): Promise<Record<string, never>>;
|
|
93
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { createModelToolClient, MODEL_TOOL_DEFINITIONS } from './model-tools.js';
|
|
2
|
+
const client = createModelToolClient(() => process.env.HELIXBOX_MODEL_PASSWORD && process.env.HELIXBOX_MODEL_MANAGER ? { managerUrl: process.env.HELIXBOX_MODEL_MANAGER, password: process.env.HELIXBOX_MODEL_PASSWORD } : null);
|
|
3
|
+
let pending = '', active = 0;
|
|
4
|
+
process.stdin.setEncoding('utf8');
|
|
5
|
+
const send = (value) => process.stdout.write(JSON.stringify(value) + '\n');
|
|
6
|
+
async function handle(raw) {
|
|
7
|
+
let message;
|
|
8
|
+
try {
|
|
9
|
+
message = JSON.parse(raw);
|
|
10
|
+
}
|
|
11
|
+
catch {
|
|
12
|
+
send({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Invalid JSON' } });
|
|
13
|
+
return;
|
|
14
|
+
}
|
|
15
|
+
if (!message || message.jsonrpc !== '2.0' || message.id === undefined)
|
|
16
|
+
return;
|
|
17
|
+
if (++active > 4) {
|
|
18
|
+
active--;
|
|
19
|
+
send({ jsonrpc: '2.0', id: message.id, error: { code: -32000, message: 'Model tool is busy' } });
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
try {
|
|
23
|
+
let result;
|
|
24
|
+
if (message.method === 'initialize')
|
|
25
|
+
result = { protocolVersion: ['2025-11-25', '2025-06-18', '2024-11-05'].includes(message.params?.protocolVersion) ? message.params.protocolVersion : '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: 'helixbox-model-tools', version: '1.0.0' } };
|
|
26
|
+
else if (message.method === 'ping')
|
|
27
|
+
result = {};
|
|
28
|
+
else if (message.method === 'tools/list')
|
|
29
|
+
result = { tools: MODEL_TOOL_DEFINITIONS };
|
|
30
|
+
else if (message.method === 'tools/call') {
|
|
31
|
+
try {
|
|
32
|
+
result = { content: [{ type: 'text', text: JSON.stringify(await client.call(message.params?.name, message.params?.arguments ?? {})) }] };
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
result = { isError: true, content: [{ type: 'text', text: error instanceof Error ? error.message : 'Model tool failed' }] };
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
else {
|
|
39
|
+
send({ jsonrpc: '2.0', id: message.id, error: { code: -32601, message: 'Method not found' } });
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
send({ jsonrpc: '2.0', id: message.id, result });
|
|
43
|
+
}
|
|
44
|
+
finally {
|
|
45
|
+
active--;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
process.stdin.on('data', (chunk) => {
|
|
49
|
+
pending += chunk;
|
|
50
|
+
let newline;
|
|
51
|
+
while ((newline = pending.indexOf('\n')) >= 0) {
|
|
52
|
+
const line = pending.slice(0, newline);
|
|
53
|
+
pending = pending.slice(newline + 1);
|
|
54
|
+
if (Buffer.byteLength(line) > 32768) {
|
|
55
|
+
process.exitCode = 1;
|
|
56
|
+
process.stdin.destroy();
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
if (line.trim())
|
|
60
|
+
void handle(line);
|
|
61
|
+
}
|
|
62
|
+
if (Buffer.byteLength(pending) > 32768) {
|
|
63
|
+
process.exitCode = 1;
|
|
64
|
+
process.stdin.destroy();
|
|
65
|
+
}
|
|
66
|
+
});
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export interface ModelToolConnection {
|
|
2
|
+
managerUrl: string;
|
|
3
|
+
password: string;
|
|
4
|
+
}
|
|
5
|
+
export declare function configureModelTools(resolve: () => ModelToolConnection | null): void;
|
|
6
|
+
export declare function modelToolConnection(): ModelToolConnection | null;
|
|
7
|
+
export declare function prepareClaudeModelTools(): Promise<{
|
|
8
|
+
filename: string;
|
|
9
|
+
env: {
|
|
10
|
+
HELIXBOX_MODEL_MANAGER: string;
|
|
11
|
+
HELIXBOX_MODEL_PASSWORD: string;
|
|
12
|
+
};
|
|
13
|
+
cleanup: () => Promise<void>;
|
|
14
|
+
} | null>;
|
|
15
|
+
export declare const MODEL_TOOL_DEFINITIONS: {
|
|
16
|
+
name: string;
|
|
17
|
+
description: string;
|
|
18
|
+
inputSchema: {
|
|
19
|
+
type: string;
|
|
20
|
+
properties: Record<string, unknown>;
|
|
21
|
+
required: string[];
|
|
22
|
+
additionalProperties: boolean;
|
|
23
|
+
};
|
|
24
|
+
}[];
|
|
25
|
+
export declare function createModelToolClient(resolve: () => ModelToolConnection | null, fetcher?: typeof fetch, workspace?: string): {
|
|
26
|
+
call(name: string, args: unknown): Promise<unknown>;
|
|
27
|
+
};
|
|
28
|
+
export declare const modelTools: {
|
|
29
|
+
call(name: string, args: unknown): Promise<unknown>;
|
|
30
|
+
};
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { mkdir, lstat, realpath, writeFile, readFile, unlink } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
let connection = () => null;
|
|
6
|
+
export function configureModelTools(resolve) { connection = resolve; }
|
|
7
|
+
export function modelToolConnection() { return connection(); }
|
|
8
|
+
export async function prepareClaudeModelTools() {
|
|
9
|
+
const current = connection();
|
|
10
|
+
if (!current)
|
|
11
|
+
return null;
|
|
12
|
+
const filename = `.helixbox-mcp-${randomUUID()}.json`, file = path.join(process.cwd(), filename);
|
|
13
|
+
// No credential is written to the project; Claude expands these inherited variables at launch.
|
|
14
|
+
await writeFile(file, JSON.stringify({ mcpServers: { helixbox: { type: 'stdio', command: process.execPath, args: [fileURLToPath(new URL('./model-mcp.js', import.meta.url))],
|
|
15
|
+
env: { HELIXBOX_MODEL_MANAGER: '${HELIXBOX_MODEL_MANAGER}', HELIXBOX_MODEL_PASSWORD: '${HELIXBOX_MODEL_PASSWORD}' } } } }), { flag: 'wx', mode: 0o600 });
|
|
16
|
+
return { filename, env: { HELIXBOX_MODEL_MANAGER: current.managerUrl, HELIXBOX_MODEL_PASSWORD: current.password }, cleanup: () => unlink(file).catch(() => { }) };
|
|
17
|
+
}
|
|
18
|
+
const id = (value) => { if (typeof value !== 'string' || !/^[a-f0-9-]{36}$/.test(value))
|
|
19
|
+
throw new Error('Invalid purchase or mandate ID'); return value; };
|
|
20
|
+
const string = (value, max) => { if (typeof value !== 'string' || !value || Buffer.byteLength(value) > max)
|
|
21
|
+
throw new Error('Invalid model tool input'); return value; };
|
|
22
|
+
const schema = (properties, required = []) => ({ type: 'object', properties, required, additionalProperties: false });
|
|
23
|
+
export const MODEL_TOOL_DEFINITIONS = [
|
|
24
|
+
{ name: 'helixbox_model_catalog', description: 'Discover live chat, image and speech models. Listing is free; use a quote to get a fixed USDC price.', inputSchema: schema({ search: { type: 'string', maxLength: 100 }, kind: { type: 'string', enum: ['chat', 'image', 'voice'] } }) },
|
|
25
|
+
];
|
|
26
|
+
async function artifact(job, workspace) {
|
|
27
|
+
const result = job.result;
|
|
28
|
+
if (!result?.base64)
|
|
29
|
+
return job;
|
|
30
|
+
const suffix = result.kind === 'image' && result.mediaType === 'image/png' ? '.png' : result.kind === 'voice' && result.mediaType === 'audio/mpeg' ? '.mp3' : null;
|
|
31
|
+
if (!suffix || typeof result.base64 !== 'string' || result.base64.length > 16777216 || !/^[A-Za-z0-9+/]*={0,2}$/.test(result.base64))
|
|
32
|
+
throw new Error('Invalid model artifact');
|
|
33
|
+
const root = await realpath(workspace), directory = path.join(root, '.helixbox-model-results');
|
|
34
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
35
|
+
if ((await lstat(directory)).isSymbolicLink() || await realpath(directory) !== directory)
|
|
36
|
+
throw new Error('Model artifact directory cannot be a symlink');
|
|
37
|
+
const file = path.join(directory, id(job.id) + suffix), bytes = Buffer.from(result.base64, 'base64');
|
|
38
|
+
try {
|
|
39
|
+
await writeFile(file, bytes, { flag: 'wx', mode: 0o600 });
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
if (error.code !== 'EEXIST')
|
|
43
|
+
throw error;
|
|
44
|
+
if ((await lstat(file)).isSymbolicLink() || createHash('sha256').update(await readFile(file)).digest('hex') !== createHash('sha256').update(bytes).digest('hex'))
|
|
45
|
+
throw new Error('Existing model artifact differs; refusing to overwrite');
|
|
46
|
+
}
|
|
47
|
+
const { base64, ...metadata } = result;
|
|
48
|
+
return { ...job, result: { ...metadata, artifactPath: file } };
|
|
49
|
+
}
|
|
50
|
+
export function createModelToolClient(resolve, fetcher = fetch, workspace = process.cwd()) {
|
|
51
|
+
async function request(route, body) {
|
|
52
|
+
const current = resolve();
|
|
53
|
+
if (!current)
|
|
54
|
+
throw new Error('Pair a HelixBox workspace first');
|
|
55
|
+
const url = new URL(current.managerUrl);
|
|
56
|
+
if (url.protocol !== 'https:')
|
|
57
|
+
throw new Error('Model tools require an HTTPS manager');
|
|
58
|
+
const response = await fetcher(url.origin + '/v2/models' + route, { method: body === undefined ? 'GET' : 'POST', headers: { Authorization: `Bearer ${current.password}`, 'Content-Type': 'application/json' },
|
|
59
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: AbortSignal.timeout(120000) });
|
|
60
|
+
if (resolve()?.password !== current.password)
|
|
61
|
+
throw new Error('Workspace pairing changed; discard the old result');
|
|
62
|
+
const value = await response.json().catch(() => null);
|
|
63
|
+
if (!response.ok)
|
|
64
|
+
throw new Error(value?.error || `Model operation failed (${response.status})`);
|
|
65
|
+
return value;
|
|
66
|
+
}
|
|
67
|
+
return { async call(name, args) {
|
|
68
|
+
if (!args || typeof args !== 'object' || Array.isArray(args))
|
|
69
|
+
throw new Error('Invalid model tool arguments');
|
|
70
|
+
const input = args;
|
|
71
|
+
if (!MODEL_TOOL_DEFINITIONS.some(tool => tool.name === name))
|
|
72
|
+
throw new Error('Unknown model tool');
|
|
73
|
+
if (name === 'helixbox_model_catalog') {
|
|
74
|
+
if (input.kind !== undefined && !['chat', 'image', 'voice'].includes(String(input.kind)))
|
|
75
|
+
throw new Error('Invalid model kind');
|
|
76
|
+
const search = input.search === undefined ? '' : string(input.search, 100).toLowerCase(), catalog = await request('');
|
|
77
|
+
return { paymentsEnabled: catalog.paymentsEnabled, models: catalog.models.filter((m) => (!input.kind || m.kind === input.kind) && `${m.id} ${m.name}`.toLowerCase().includes(search)).slice(0, 20) };
|
|
78
|
+
}
|
|
79
|
+
if (name === 'helixbox_model_mandates')
|
|
80
|
+
return request('/mandates');
|
|
81
|
+
if (name === 'helixbox_model_quote') {
|
|
82
|
+
const mandateId = id(input.mandateId), modelId = string(input.modelId, 256), prompt = string(input.prompt, 8000);
|
|
83
|
+
const { mandates } = await request('/mandates');
|
|
84
|
+
const mandate = mandates.find((m) => m.id === mandateId && m.state === 'active' && m.policy.expiresAt > Date.now());
|
|
85
|
+
if (!mandate?.policy.models.some((m) => m.id === modelId && m.kind === input.kind))
|
|
86
|
+
throw new Error('User has not approved this model in an active mandate');
|
|
87
|
+
const quoted = await request('/quotes', { modelId, kind: input.kind, prompt, consent: true, ...input.maxOutputTokens !== undefined ? { maxOutputTokens: input.maxOutputTokens } : {}, ...input.voice !== undefined ? { voice: input.voice } : {} });
|
|
88
|
+
if (BigInt(quoted.terms.amount) > BigInt(mandate.policy.perCallAmount))
|
|
89
|
+
throw new Error('Quoted price exceeds the user’s per-call cap');
|
|
90
|
+
return quoted;
|
|
91
|
+
}
|
|
92
|
+
const purchaseId = id(input.purchaseId);
|
|
93
|
+
if (name === 'helixbox_model_purchase')
|
|
94
|
+
return request(`/purchases/${purchaseId}/request`, { mandateId: id(input.mandateId) });
|
|
95
|
+
let job = await request(`/purchases/${purchaseId}`);
|
|
96
|
+
if (job.state === 'paid')
|
|
97
|
+
job = await request(`/purchases/${purchaseId}/resume`, {});
|
|
98
|
+
return artifact(job, workspace);
|
|
99
|
+
} };
|
|
100
|
+
}
|
|
101
|
+
export const modelTools = createModelToolClient(() => connection());
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import type { AIProvider, AiEventEmitter, CodexPromptOptions, FileAttachment, ModelSelector, MessageInfo, ProviderInfo, SessionInfo, ShareInfo } from "./interface.js";
|
|
2
|
+
export declare class OpenCodeProvider implements AIProvider {
|
|
3
|
+
private client;
|
|
4
|
+
private server;
|
|
5
|
+
private authHeader;
|
|
6
|
+
private lastActiveSessionId;
|
|
7
|
+
private shuttingDown;
|
|
8
|
+
private emitter;
|
|
9
|
+
private knownPendingPermissionIds;
|
|
10
|
+
private knownPendingQuestionIds;
|
|
11
|
+
private debugLog;
|
|
12
|
+
private debugWarn;
|
|
13
|
+
private debugError;
|
|
14
|
+
init(): Promise<void>;
|
|
15
|
+
destroy(): Promise<void>;
|
|
16
|
+
subscribe(emitter: AiEventEmitter): () => void;
|
|
17
|
+
setActiveSession(sessionId: string): void;
|
|
18
|
+
createSession(title?: string): Promise<{
|
|
19
|
+
session: SessionInfo;
|
|
20
|
+
}>;
|
|
21
|
+
listSessions(): Promise<{
|
|
22
|
+
sessions: unknown;
|
|
23
|
+
}>;
|
|
24
|
+
getSession(id: string): Promise<{
|
|
25
|
+
session: SessionInfo;
|
|
26
|
+
}>;
|
|
27
|
+
deleteSession(id: string): Promise<{
|
|
28
|
+
deleted: boolean;
|
|
29
|
+
}>;
|
|
30
|
+
renameSession(id: string, title: string): Promise<{
|
|
31
|
+
session: SessionInfo;
|
|
32
|
+
}>;
|
|
33
|
+
getMessages(sessionId: string): Promise<{
|
|
34
|
+
messages: MessageInfo[];
|
|
35
|
+
}>;
|
|
36
|
+
statuses(): Promise<{
|
|
37
|
+
statuses: Record<string, unknown>;
|
|
38
|
+
}>;
|
|
39
|
+
prompt(sessionId: string, text: string, model?: ModelSelector, agent?: string, files?: FileAttachment[], codexOptions?: CodexPromptOptions): Promise<{
|
|
40
|
+
ack: true;
|
|
41
|
+
}>;
|
|
42
|
+
abort(sessionId: string): Promise<Record<string, never>>;
|
|
43
|
+
agents(): Promise<{
|
|
44
|
+
agents: unknown;
|
|
45
|
+
}>;
|
|
46
|
+
providers(): Promise<ProviderInfo>;
|
|
47
|
+
setAuth(providerId: string, key: string): Promise<Record<string, never>>;
|
|
48
|
+
command(sessionId: string, command: string, args: string): Promise<{
|
|
49
|
+
result: unknown;
|
|
50
|
+
}>;
|
|
51
|
+
revert(sessionId: string, messageId: string): Promise<Record<string, never>>;
|
|
52
|
+
unrevert(sessionId: string): Promise<Record<string, never>>;
|
|
53
|
+
share(sessionId: string): Promise<{
|
|
54
|
+
share: ShareInfo;
|
|
55
|
+
}>;
|
|
56
|
+
permissionReply(sessionId: string, permissionId: string, response: "once" | "always" | "reject"): Promise<Record<string, never>>;
|
|
57
|
+
questionReply(sessionId: string, questionId: string, answers: string[][]): Promise<Record<string, never>>;
|
|
58
|
+
questionReject(sessionId: string, questionId: string): Promise<Record<string, never>>;
|
|
59
|
+
private runSseLoop;
|
|
60
|
+
private sendPromptAsync;
|
|
61
|
+
private reconcileOpenCodeState;
|
|
62
|
+
private refreshBusySessionMessages;
|
|
63
|
+
private refreshSessionsMetadata;
|
|
64
|
+
private refreshPendingPermissions;
|
|
65
|
+
private refreshPendingQuestions;
|
|
66
|
+
private fetchOpenCodeJson;
|
|
67
|
+
private refreshSessionStatuses;
|
|
68
|
+
private fetchSessionStatuses;
|
|
69
|
+
private trackPermissionEvent;
|
|
70
|
+
private readString;
|
|
71
|
+
private asRecord;
|
|
72
|
+
}
|