@chatpanel/bridge 0.11.24 โ 0.12.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/.env.example +12 -0
- package/README.md +7 -7
- package/package.json +1 -13
- package/scripts/sync-channels.mjs +8 -90
- package/scripts/sync-events.mjs +7 -78
- package/scripts/sync-pii.mjs +7 -68
- package/src/api-compat.js +5 -294
- package/src/channels/adapters/telegram.js +3 -298
- package/src/channels/bridge.js +1 -59
- package/src/channels/eventlog.js +3 -57
- package/src/channels/gateway.js +1 -114
- package/src/channels/invoke.js +1 -172
- package/src/channels/normalize.js +1 -58
- package/src/channels/pairing.js +1 -95
- package/src/channels/service.js +1 -329
- package/src/channels/stream.js +5 -104
- package/src/cli-errors.js +3 -136
- package/src/connections.js +1 -160
- package/src/connectors.js +1 -100
- package/src/engines/antigravity.js +5 -235
- package/src/engines/args.js +1 -47
- package/src/engines/claude-warm.js +3 -0
- package/src/engines/claude.js +6 -586
- package/src/engines/cli-agents.js +7 -312
- package/src/engines/codex-appserver.js +12 -0
- package/src/engines/codex.js +6 -481
- package/src/engines/custom.js +17 -577
- package/src/engines/prompt.js +6 -32
- package/src/engines/stream-formats.js +2 -222
- package/src/entitlement.js +1 -77
- package/src/env.js +3 -628
- package/src/events/capability.js +1 -134
- package/src/events/event.js +1 -183
- package/src/events/reach.js +1 -31
- package/src/events/ref.js +1 -63
- package/src/events/scm-connection.js +1 -188
- package/src/events/scopes.js +1 -20
- package/src/events/skill-manifest.js +1 -338
- package/src/events/skill-scan.js +3 -217
- package/src/events/view.js +1 -96
- package/src/mcp-capabilities.js +2 -139
- package/src/mcp-local.js +0 -0
- package/src/mcp-quarantine.js +1 -110
- package/src/mcp-sessions.js +1 -0
- package/src/net.js +1 -107
- package/src/pii/index.js +1 -29
- package/src/pii/net.js +1 -111
- package/src/pii/pii-detect.js +2 -296
- package/src/pii/pii-redact.js +1 -470
- package/src/pii/pipeline.js +1 -137
- package/src/pii/sanitize.js +2 -179
- package/src/pii/tool-harness.js +1 -184
- package/src/pii/tool-rank.js +1 -110
- package/src/proc.js +3 -91
- package/src/relay-timeout.js +1 -21
- package/src/rpc-child.js +3 -0
- package/src/runs.js +1 -49
- package/src/sanitize.js +1 -7
- package/src/scm.js +1 -76
- package/src/server.js +10 -1492
- package/src/service.js +11 -176
- package/src/sign-in.js +1 -91
- package/src/skills.js +1 -399
- package/src/ssrf.js +1 -70
- package/src/update.js +1 -216
- package/src/warm-pool.js +1 -0
- package/src/warm.js +1 -0
- package/src/workdir.js +1 -108
- package/src/worktree.js +3 -125
package/src/api-compat.js
CHANGED
|
@@ -1,296 +1,7 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
// This intentionally implements the text conversation subset shared by coding
|
|
4
|
-
// agents. Provider-hosted features (token accounting, stored responses, remote
|
|
5
|
-
// function tools, logprobs, etc.) cannot be reproduced by a local CLI runner and
|
|
6
|
-
// are rejected when accepting them would produce misleading behavior.
|
|
1
|
+
import{randomUUID as l}from"node:crypto";import{normalizeNames as h}from"./mcp-quarantine.js";const _=new Set(["claude","codex","antigravity","pi","opencode","kiro","copilot","deepseek"]);class i extends Error{constructor(e,s=400,n=null){super(e),this.status=s,this.param=n}}function u(t){return t==null?"":typeof t=="string"?t:Array.isArray(t)?t.map(e=>typeof e=="string"?e:!e||typeof e!="object"?"":typeof e.text=="string"?e.text:typeof e.content=="string"?e.content:e.type==="tool_result"?u(e.content):"").filter(Boolean).join(`
|
|
2
|
+
`):String(t)}function c(t,e){if(!(t==null||typeof t=="string")){if(!Array.isArray(t))throw new i(`${e} must contain text`,400,e);for(const s of t){if(typeof s=="string")continue;const n=s?.type;if(!(s&&typeof s=="object"&&(!n||["text","input_text","output_text"].includes(n))&&typeof s.text=="string")){if(n==="tool_result"){c(s.content,e);continue}throw new i(`${e} contains unsupported non-text content`,400,e)}}}}function d(t=[]){return t.map(e=>({role:e?.role==="assistant"?"assistant":"user",content:u(e?.content)})).filter(e=>e.content)}function g(t,e={}){const s=String(t||"codex").trim()||"codex",n=s.indexOf("/"),o=n<0?s:s.slice(0,n),a=String(e.agent||"").trim()||(_.has(o)?o:"codex");if(!_.has(a))throw new i(`Unknown ChatPanel agent "${a}"`,400,"model");let p=String(e.model||"").trim();!p&&n>=0&&_.has(o)&&(p=s.slice(n+1)),!p&&!_.has(s)&&(p=s);const m=e.permission_mode||e.permissionMode||"default";if(!["default","acceptEdits","bypassPermissions"].includes(m))throw new i("chatpanel.permission_mode must be default, acceptEdits, or bypassPermissions",400,"chatpanel.permission_mode");return{agent:a,requestedModel:s,options:{workingDir:e.working_dir||e.workingDir||process.env.CHATPANEL_API_WORKING_DIR||"",permissionMode:m,useLocalConfig:e.use_local_config??e.useLocalConfig??!0,mcpDisabled:h(e.mcp_disabled??e.mcpDisabled),...p?{model:p}:{}}}}function A(t={}){if(!Array.isArray(t.messages)||!t.messages.length)throw new i("messages must be a non-empty array",400,"messages");if(t.tools?.length)throw new i("OpenAI tool calling is not supported by the bridge adapter",400,"tools");for(const n of t.messages){if(!["system","developer","user","assistant"].includes(n?.role))throw new i(`Unsupported message role "${n?.role||""}"`,400,"messages");c(n.content,"messages")}const e=t.messages.filter(n=>n?.role==="system"||n?.role==="developer").map(n=>u(n.content)).filter(Boolean).join(`
|
|
7
3
|
|
|
8
|
-
|
|
9
|
-
|
|
4
|
+
`),s=d(t.messages.filter(n=>n?.role!=="system"&&n?.role!=="developer"));if(!s.length)throw new i("messages must contain user or assistant text",400,"messages");return{...g(t.model,t.chatpanel),system:e,messages:s,stream:t.stream===!0}}function b(t={}){if(Array.isArray(t.prompt))for(const s of t.prompt)c(s,"prompt");else c(t.prompt,"prompt");const e=Array.isArray(t.prompt)?t.prompt.map(u).join(`
|
|
5
|
+
`):u(t.prompt);if(!e)throw new i("prompt must contain text",400,"prompt");return{...g(t.model,t.chatpanel),system:"",messages:[{role:"user",content:e}],stream:t.stream===!0}}function q(t={}){if(t.tools?.length)throw new i("Responses API tool calling is not supported by the bridge adapter",400,"tools");let e=t.input;if(typeof e=="string"&&(e=[{role:"user",content:e}]),!Array.isArray(e)||!e.length)throw new i("input must be a string or non-empty array",400,"input");c(t.instructions,"instructions");for(const o of e){if(!["system","developer","user","assistant"].includes(o?.role))throw new i("input currently supports only text message items",400,"input");c(o.content,"input")}const s=[u(t.instructions)];for(const o of e)(o?.role==="system"||o?.role==="developer")&&s.push(u(o.content));const n=d(e.filter(o=>o?.role!=="system"&&o?.role!=="developer"));if(!n.length)throw new i("input must contain user or assistant text",400,"input");return{...g(t.model,t.chatpanel),system:s.filter(Boolean).join(`
|
|
10
6
|
|
|
11
|
-
const
|
|
12
|
-
|
|
13
|
-
export class CompatError extends Error {
|
|
14
|
-
constructor(message, status = 400, param = null) {
|
|
15
|
-
super(message);
|
|
16
|
-
this.status = status;
|
|
17
|
-
this.param = param;
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
function textOf(content) {
|
|
22
|
-
if (content == null) return '';
|
|
23
|
-
if (typeof content === 'string') return content;
|
|
24
|
-
if (!Array.isArray(content)) return String(content);
|
|
25
|
-
return content.map((part) => {
|
|
26
|
-
if (typeof part === 'string') return part;
|
|
27
|
-
if (!part || typeof part !== 'object') return '';
|
|
28
|
-
if (typeof part.text === 'string') return part.text;
|
|
29
|
-
if (typeof part.content === 'string') return part.content;
|
|
30
|
-
if (part.type === 'tool_result') return textOf(part.content);
|
|
31
|
-
return '';
|
|
32
|
-
}).filter(Boolean).join('\n');
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
function assertTextContent(content, param) {
|
|
36
|
-
if (content == null || typeof content === 'string') return;
|
|
37
|
-
if (!Array.isArray(content)) throw new CompatError(`${param} must contain text`, 400, param);
|
|
38
|
-
for (const part of content) {
|
|
39
|
-
if (typeof part === 'string') continue;
|
|
40
|
-
const type = part?.type;
|
|
41
|
-
if (part && typeof part === 'object' && (!type || ['text', 'input_text', 'output_text'].includes(type)) && typeof part.text === 'string') continue;
|
|
42
|
-
if (type === 'tool_result') {
|
|
43
|
-
assertTextContent(part.content, param);
|
|
44
|
-
continue;
|
|
45
|
-
}
|
|
46
|
-
throw new CompatError(`${param} contains unsupported non-text content`, 400, param);
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
function normalizeMessages(items = []) {
|
|
51
|
-
return items.map((item) => ({
|
|
52
|
-
role: item?.role === 'assistant' ? 'assistant' : 'user',
|
|
53
|
-
content: textOf(item?.content),
|
|
54
|
-
})).filter((item) => item.content);
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
function resolveTarget(model, chatpanel = {}) {
|
|
58
|
-
const requested = String(model || 'codex').trim() || 'codex';
|
|
59
|
-
const slash = requested.indexOf('/');
|
|
60
|
-
const prefix = slash < 0 ? requested : requested.slice(0, slash);
|
|
61
|
-
const explicitAgent = String(chatpanel.agent || '').trim();
|
|
62
|
-
const agent = explicitAgent || (AGENT_IDS.has(prefix) ? prefix : 'codex');
|
|
63
|
-
if (!AGENT_IDS.has(agent)) throw new CompatError(`Unknown ChatPanel agent "${agent}"`, 400, 'model');
|
|
64
|
-
|
|
65
|
-
let engineModel = String(chatpanel.model || '').trim();
|
|
66
|
-
if (!engineModel && slash >= 0 && AGENT_IDS.has(prefix)) engineModel = requested.slice(slash + 1);
|
|
67
|
-
if (!engineModel && !AGENT_IDS.has(requested)) engineModel = requested;
|
|
68
|
-
|
|
69
|
-
const permissionMode = chatpanel.permission_mode || chatpanel.permissionMode || 'default';
|
|
70
|
-
if (!['default', 'acceptEdits', 'bypassPermissions'].includes(permissionMode)) {
|
|
71
|
-
throw new CompatError('chatpanel.permission_mode must be default, acceptEdits, or bypassPermissions', 400, 'chatpanel.permission_mode');
|
|
72
|
-
}
|
|
73
|
-
return {
|
|
74
|
-
agent,
|
|
75
|
-
requestedModel: requested,
|
|
76
|
-
options: {
|
|
77
|
-
workingDir: chatpanel.working_dir || chatpanel.workingDir || process.env.CHATPANEL_API_WORKING_DIR || '',
|
|
78
|
-
permissionMode,
|
|
79
|
-
useLocalConfig: chatpanel.use_local_config ?? chatpanel.useLocalConfig ?? true,
|
|
80
|
-
// Servers in the agent's OWN MCP config to leave out of this run โ one that can't
|
|
81
|
-
// authenticate or can't be reached otherwise kills the whole turn (see mcp-quarantine.js).
|
|
82
|
-
mcpDisabled: normalizeNames(chatpanel.mcp_disabled ?? chatpanel.mcpDisabled),
|
|
83
|
-
...(engineModel ? { model: engineModel } : {}),
|
|
84
|
-
},
|
|
85
|
-
};
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
export function parseChatCompletion(body = {}) {
|
|
89
|
-
if (!Array.isArray(body.messages) || !body.messages.length) {
|
|
90
|
-
throw new CompatError('messages must be a non-empty array', 400, 'messages');
|
|
91
|
-
}
|
|
92
|
-
if (body.tools?.length) throw new CompatError('OpenAI tool calling is not supported by the bridge adapter', 400, 'tools');
|
|
93
|
-
for (const message of body.messages) {
|
|
94
|
-
if (!['system', 'developer', 'user', 'assistant'].includes(message?.role)) {
|
|
95
|
-
throw new CompatError(`Unsupported message role "${message?.role || ''}"`, 400, 'messages');
|
|
96
|
-
}
|
|
97
|
-
assertTextContent(message.content, 'messages');
|
|
98
|
-
}
|
|
99
|
-
const system = body.messages
|
|
100
|
-
.filter((m) => m?.role === 'system' || m?.role === 'developer')
|
|
101
|
-
.map((m) => textOf(m.content)).filter(Boolean).join('\n\n');
|
|
102
|
-
const messages = normalizeMessages(body.messages.filter((m) => m?.role !== 'system' && m?.role !== 'developer'));
|
|
103
|
-
if (!messages.length) throw new CompatError('messages must contain user or assistant text', 400, 'messages');
|
|
104
|
-
return { ...resolveTarget(body.model, body.chatpanel), system, messages, stream: body.stream === true };
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
export function parseCompletion(body = {}) {
|
|
108
|
-
if (Array.isArray(body.prompt)) {
|
|
109
|
-
for (const prompt of body.prompt) assertTextContent(prompt, 'prompt');
|
|
110
|
-
} else {
|
|
111
|
-
assertTextContent(body.prompt, 'prompt');
|
|
112
|
-
}
|
|
113
|
-
const prompt = Array.isArray(body.prompt) ? body.prompt.map(textOf).join('\n') : textOf(body.prompt);
|
|
114
|
-
if (!prompt) throw new CompatError('prompt must contain text', 400, 'prompt');
|
|
115
|
-
return {
|
|
116
|
-
...resolveTarget(body.model, body.chatpanel),
|
|
117
|
-
system: '',
|
|
118
|
-
messages: [{ role: 'user', content: prompt }],
|
|
119
|
-
stream: body.stream === true,
|
|
120
|
-
};
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
export function parseResponse(body = {}) {
|
|
124
|
-
if (body.tools?.length) throw new CompatError('Responses API tool calling is not supported by the bridge adapter', 400, 'tools');
|
|
125
|
-
let input = body.input;
|
|
126
|
-
if (typeof input === 'string') input = [{ role: 'user', content: input }];
|
|
127
|
-
if (!Array.isArray(input) || !input.length) throw new CompatError('input must be a string or non-empty array', 400, 'input');
|
|
128
|
-
assertTextContent(body.instructions, 'instructions');
|
|
129
|
-
for (const item of input) {
|
|
130
|
-
if (!['system', 'developer', 'user', 'assistant'].includes(item?.role)) {
|
|
131
|
-
throw new CompatError('input currently supports only text message items', 400, 'input');
|
|
132
|
-
}
|
|
133
|
-
assertTextContent(item.content, 'input');
|
|
134
|
-
}
|
|
135
|
-
const systemParts = [textOf(body.instructions)];
|
|
136
|
-
for (const item of input) {
|
|
137
|
-
if (item?.role === 'system' || item?.role === 'developer') systemParts.push(textOf(item.content));
|
|
138
|
-
}
|
|
139
|
-
const messages = normalizeMessages(input.filter((item) => item?.role !== 'system' && item?.role !== 'developer'));
|
|
140
|
-
if (!messages.length) throw new CompatError('input must contain user or assistant text', 400, 'input');
|
|
141
|
-
return {
|
|
142
|
-
...resolveTarget(body.model, body.chatpanel),
|
|
143
|
-
system: systemParts.filter(Boolean).join('\n\n'),
|
|
144
|
-
messages,
|
|
145
|
-
stream: body.stream === true,
|
|
146
|
-
};
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
export function parseAnthropicMessage(body = {}) {
|
|
150
|
-
if (!Array.isArray(body.messages) || !body.messages.length) {
|
|
151
|
-
throw new CompatError('messages must be a non-empty array', 400, 'messages');
|
|
152
|
-
}
|
|
153
|
-
if (body.tools?.length) throw new CompatError('Anthropic tool use is not supported by the bridge adapter', 400, 'tools');
|
|
154
|
-
assertTextContent(body.system, 'system');
|
|
155
|
-
for (const message of body.messages) {
|
|
156
|
-
if (!['user', 'assistant'].includes(message?.role)) {
|
|
157
|
-
throw new CompatError(`Unsupported message role "${message?.role || ''}"`, 400, 'messages');
|
|
158
|
-
}
|
|
159
|
-
assertTextContent(message.content, 'messages');
|
|
160
|
-
}
|
|
161
|
-
const messages = normalizeMessages(body.messages);
|
|
162
|
-
if (!messages.length) throw new CompatError('messages must contain text', 400, 'messages');
|
|
163
|
-
return {
|
|
164
|
-
...resolveTarget(body.model, body.chatpanel),
|
|
165
|
-
system: textOf(body.system),
|
|
166
|
-
messages,
|
|
167
|
-
stream: body.stream === true,
|
|
168
|
-
};
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
export function openAIError(error) {
|
|
172
|
-
return {
|
|
173
|
-
error: {
|
|
174
|
-
message: error?.message || String(error),
|
|
175
|
-
type: error instanceof CompatError ? 'invalid_request_error' : 'api_error',
|
|
176
|
-
param: error?.param || null,
|
|
177
|
-
code: null,
|
|
178
|
-
},
|
|
179
|
-
};
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
export function anthropicError(error) {
|
|
183
|
-
return {
|
|
184
|
-
type: 'error',
|
|
185
|
-
error: {
|
|
186
|
-
type: error instanceof CompatError ? 'invalid_request_error' : 'api_error',
|
|
187
|
-
message: error?.message || String(error),
|
|
188
|
-
},
|
|
189
|
-
};
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
const zeroUsage = () => ({ prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 });
|
|
193
|
-
const responseUsage = () => ({ input_tokens: 0, input_tokens_details: { cached_tokens: 0 }, output_tokens: 0, output_tokens_details: { reasoning_tokens: 0 }, total_tokens: 0 });
|
|
194
|
-
|
|
195
|
-
export function createChatCompletion(model, text, { id = `chatcmpl-${randomUUID()}`, created = Math.floor(Date.now() / 1000) } = {}) {
|
|
196
|
-
return {
|
|
197
|
-
id, object: 'chat.completion', created, model,
|
|
198
|
-
choices: [{ index: 0, message: { role: 'assistant', content: text, refusal: null }, logprobs: null, finish_reason: 'stop' }],
|
|
199
|
-
usage: zeroUsage(),
|
|
200
|
-
};
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
export function createCompletion(model, text, { id = `cmpl-${randomUUID()}`, created = Math.floor(Date.now() / 1000) } = {}) {
|
|
204
|
-
return {
|
|
205
|
-
id, object: 'text_completion', created, model,
|
|
206
|
-
choices: [{ text, index: 0, logprobs: null, finish_reason: 'stop' }],
|
|
207
|
-
usage: zeroUsage(),
|
|
208
|
-
};
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
export function completionStream(model, onWrite, { id = `cmpl-${randomUUID()}`, created = Math.floor(Date.now() / 1000) } = {}) {
|
|
212
|
-
const chunk = (text, finish_reason = null) => ({
|
|
213
|
-
id, object: 'text_completion', created, model,
|
|
214
|
-
choices: [{ text, index: 0, logprobs: null, finish_reason }],
|
|
215
|
-
});
|
|
216
|
-
return {
|
|
217
|
-
delta(text) { if (text) onWrite(chunk(text)); },
|
|
218
|
-
done() { onWrite(chunk('', 'stop')); },
|
|
219
|
-
};
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
export function chatCompletionStream(model, onWrite, { id = `chatcmpl-${randomUUID()}`, created = Math.floor(Date.now() / 1000) } = {}) {
|
|
223
|
-
const chunk = (delta, finish_reason = null) => ({
|
|
224
|
-
id, object: 'chat.completion.chunk', created, model,
|
|
225
|
-
choices: [{ index: 0, delta, logprobs: null, finish_reason }],
|
|
226
|
-
});
|
|
227
|
-
let started = false;
|
|
228
|
-
return {
|
|
229
|
-
delta(text) {
|
|
230
|
-
if (!started) { onWrite(chunk({ role: 'assistant', content: '' })); started = true; }
|
|
231
|
-
if (text) onWrite(chunk({ content: text }));
|
|
232
|
-
},
|
|
233
|
-
done() {
|
|
234
|
-
if (!started) onWrite(chunk({ role: 'assistant', content: '' }));
|
|
235
|
-
onWrite(chunk({}, 'stop'));
|
|
236
|
-
},
|
|
237
|
-
};
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
function responseObject(model, text, { id, created, status = 'completed' }) {
|
|
241
|
-
const itemId = `msg_${id.slice(-24)}`;
|
|
242
|
-
return {
|
|
243
|
-
id, object: 'response', created_at: created, status, error: null, incomplete_details: null,
|
|
244
|
-
instructions: null, max_output_tokens: null, model,
|
|
245
|
-
output: status === 'completed' ? [{ id: itemId, type: 'message', status: 'completed', role: 'assistant', content: [{ type: 'output_text', text, annotations: [], logprobs: [] }] }] : [],
|
|
246
|
-
parallel_tool_calls: false, previous_response_id: null, reasoning: { effort: null, summary: null }, store: false,
|
|
247
|
-
temperature: null, text: { format: { type: 'text' } }, tool_choice: 'none', tools: [], top_p: null,
|
|
248
|
-
truncation: 'disabled', usage: status === 'completed' ? responseUsage() : null, user: null, metadata: {},
|
|
249
|
-
};
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
export function createResponse(model, text, { id = `resp_${randomUUID()}`, created = Math.floor(Date.now() / 1000) } = {}) {
|
|
253
|
-
return responseObject(model, text, { id, created });
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
export function responseStream(model, onWrite, { id = `resp_${randomUUID()}`, created = Math.floor(Date.now() / 1000) } = {}) {
|
|
257
|
-
const itemId = `msg_${id.slice(-24)}`;
|
|
258
|
-
let sequence = 0;
|
|
259
|
-
let text = '';
|
|
260
|
-
onWrite({ type: 'response.created', sequence_number: sequence++, response: responseObject(model, '', { id, created, status: 'in_progress' }) });
|
|
261
|
-
onWrite({ type: 'response.in_progress', sequence_number: sequence++, response: responseObject(model, '', { id, created, status: 'in_progress' }) });
|
|
262
|
-
onWrite({ type: 'response.output_item.added', sequence_number: sequence++, output_index: 0, item: { id: itemId, type: 'message', status: 'in_progress', role: 'assistant', content: [] } });
|
|
263
|
-
onWrite({ type: 'response.content_part.added', sequence_number: sequence++, item_id: itemId, output_index: 0, content_index: 0, part: { type: 'output_text', text: '', annotations: [], logprobs: [] } });
|
|
264
|
-
return {
|
|
265
|
-
delta(value) {
|
|
266
|
-
if (!value) return;
|
|
267
|
-
text += value;
|
|
268
|
-
onWrite({ type: 'response.output_text.delta', sequence_number: sequence++, item_id: itemId, output_index: 0, content_index: 0, delta: value, logprobs: [] });
|
|
269
|
-
},
|
|
270
|
-
done() {
|
|
271
|
-
onWrite({ type: 'response.output_text.done', sequence_number: sequence++, item_id: itemId, output_index: 0, content_index: 0, text, logprobs: [] });
|
|
272
|
-
const part = { type: 'output_text', text, annotations: [], logprobs: [] };
|
|
273
|
-
onWrite({ type: 'response.content_part.done', sequence_number: sequence++, item_id: itemId, output_index: 0, content_index: 0, part });
|
|
274
|
-
const item = { id: itemId, type: 'message', status: 'completed', role: 'assistant', content: [part] };
|
|
275
|
-
onWrite({ type: 'response.output_item.done', sequence_number: sequence++, output_index: 0, item });
|
|
276
|
-
onWrite({ type: 'response.completed', sequence_number: sequence++, response: responseObject(model, text, { id, created }) });
|
|
277
|
-
},
|
|
278
|
-
};
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
export function createAnthropicMessage(model, text, { id = `msg_${randomUUID()}` } = {}) {
|
|
282
|
-
return { id, type: 'message', role: 'assistant', model, content: [{ type: 'text', text }], stop_reason: 'end_turn', stop_sequence: null, usage: { input_tokens: 0, output_tokens: 0 } };
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
export function anthropicStream(model, onWrite, { id = `msg_${randomUUID()}` } = {}) {
|
|
286
|
-
onWrite('message_start', { type: 'message_start', message: { id, type: 'message', role: 'assistant', model, content: [], stop_reason: null, stop_sequence: null, usage: { input_tokens: 0, output_tokens: 0 } } });
|
|
287
|
-
onWrite('content_block_start', { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } });
|
|
288
|
-
return {
|
|
289
|
-
delta(text) { if (text) onWrite('content_block_delta', { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text } }); },
|
|
290
|
-
done() {
|
|
291
|
-
onWrite('content_block_stop', { type: 'content_block_stop', index: 0 });
|
|
292
|
-
onWrite('message_delta', { type: 'message_delta', delta: { stop_reason: 'end_turn', stop_sequence: null }, usage: { output_tokens: 0 } });
|
|
293
|
-
onWrite('message_stop', { type: 'message_stop' });
|
|
294
|
-
},
|
|
295
|
-
};
|
|
296
|
-
}
|
|
7
|
+
`),messages:n,stream:t.stream===!0}}function $(t={}){if(!Array.isArray(t.messages)||!t.messages.length)throw new i("messages must be a non-empty array",400,"messages");if(t.tools?.length)throw new i("Anthropic tool use is not supported by the bridge adapter",400,"tools");c(t.system,"system");for(const s of t.messages){if(!["user","assistant"].includes(s?.role))throw new i(`Unsupported message role "${s?.role||""}"`,400,"messages");c(s.content,"messages")}const e=d(t.messages);if(!e.length)throw new i("messages must contain text",400,"messages");return{...g(t.model,t.chatpanel),system:u(t.system),messages:e,stream:t.stream===!0}}function C(t){return{error:{message:t?.message||String(t),type:t instanceof i?"invalid_request_error":"api_error",param:t?.param||null,code:null}}}function D(t){return{type:"error",error:{type:t instanceof i?"invalid_request_error":"api_error",message:t?.message||String(t)}}}const x=()=>({prompt_tokens:0,completion_tokens:0,total_tokens:0}),y=()=>({input_tokens:0,input_tokens_details:{cached_tokens:0},output_tokens:0,output_tokens_details:{reasoning_tokens:0},total_tokens:0});function M(t,e,{id:s=`chatcmpl-${l()}`,created:n=Math.floor(Date.now()/1e3)}={}){return{id:s,object:"chat.completion",created:n,model:t,choices:[{index:0,message:{role:"assistant",content:e,refusal:null},logprobs:null,finish_reason:"stop"}],usage:x()}}function j(t,e,{id:s=`cmpl-${l()}`,created:n=Math.floor(Date.now()/1e3)}={}){return{id:s,object:"text_completion",created:n,model:t,choices:[{text:e,index:0,logprobs:null,finish_reason:"stop"}],usage:x()}}function S(t,e,{id:s=`cmpl-${l()}`,created:n=Math.floor(Date.now()/1e3)}={}){const o=(r,a=null)=>({id:s,object:"text_completion",created:n,model:t,choices:[{text:r,index:0,logprobs:null,finish_reason:a}]});return{delta(r){r&&e(o(r))},done(){e(o("","stop"))}}}function v(t,e,{id:s=`chatcmpl-${l()}`,created:n=Math.floor(Date.now()/1e3)}={}){const o=(a,p=null)=>({id:s,object:"chat.completion.chunk",created:n,model:t,choices:[{index:0,delta:a,logprobs:null,finish_reason:p}]});let r=!1;return{delta(a){r||(e(o({role:"assistant",content:""})),r=!0),a&&e(o({content:a}))},done(){r||e(o({role:"assistant",content:""})),e(o({},"stop"))}}}function f(t,e,{id:s,created:n,status:o="completed"}){const r=`msg_${s.slice(-24)}`;return{id:s,object:"response",created_at:n,status:o,error:null,incomplete_details:null,instructions:null,max_output_tokens:null,model:t,output:o==="completed"?[{id:r,type:"message",status:"completed",role:"assistant",content:[{type:"output_text",text:e,annotations:[],logprobs:[]}]}]:[],parallel_tool_calls:!1,previous_response_id:null,reasoning:{effort:null,summary:null},store:!1,temperature:null,text:{format:{type:"text"}},tool_choice:"none",tools:[],top_p:null,truncation:"disabled",usage:o==="completed"?y():null,user:null,metadata:{}}}function I(t,e,{id:s=`resp_${l()}`,created:n=Math.floor(Date.now()/1e3)}={}){return f(t,e,{id:s,created:n})}function E(t,e,{id:s=`resp_${l()}`,created:n=Math.floor(Date.now()/1e3)}={}){const o=`msg_${s.slice(-24)}`;let r=0,a="";return e({type:"response.created",sequence_number:r++,response:f(t,"",{id:s,created:n,status:"in_progress"})}),e({type:"response.in_progress",sequence_number:r++,response:f(t,"",{id:s,created:n,status:"in_progress"})}),e({type:"response.output_item.added",sequence_number:r++,output_index:0,item:{id:o,type:"message",status:"in_progress",role:"assistant",content:[]}}),e({type:"response.content_part.added",sequence_number:r++,item_id:o,output_index:0,content_index:0,part:{type:"output_text",text:"",annotations:[],logprobs:[]}}),{delta(p){p&&(a+=p,e({type:"response.output_text.delta",sequence_number:r++,item_id:o,output_index:0,content_index:0,delta:p,logprobs:[]}))},done(){e({type:"response.output_text.done",sequence_number:r++,item_id:o,output_index:0,content_index:0,text:a,logprobs:[]});const p={type:"output_text",text:a,annotations:[],logprobs:[]};e({type:"response.content_part.done",sequence_number:r++,item_id:o,output_index:0,content_index:0,part:p});const m={id:o,type:"message",status:"completed",role:"assistant",content:[p]};e({type:"response.output_item.done",sequence_number:r++,output_index:0,item:m}),e({type:"response.completed",sequence_number:r++,response:f(t,a,{id:s,created:n})})}}}function P(t,e,{id:s=`msg_${l()}`}={}){return{id:s,type:"message",role:"assistant",model:t,content:[{type:"text",text:e}],stop_reason:"end_turn",stop_sequence:null,usage:{input_tokens:0,output_tokens:0}}}function U(t,e,{id:s=`msg_${l()}`}={}){return e("message_start",{type:"message_start",message:{id:s,type:"message",role:"assistant",model:t,content:[],stop_reason:null,stop_sequence:null,usage:{input_tokens:0,output_tokens:0}}}),e("content_block_start",{type:"content_block_start",index:0,content_block:{type:"text",text:""}}),{delta(n){n&&e("content_block_delta",{type:"content_block_delta",index:0,delta:{type:"text_delta",text:n}})},done(){e("content_block_stop",{type:"content_block_stop",index:0}),e("message_delta",{type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{output_tokens:0}}),e("message_stop",{type:"message_stop"})}}}export{i as CompatError,D as anthropicError,U as anthropicStream,v as chatCompletionStream,S as completionStream,P as createAnthropicMessage,M as createChatCompletion,j as createCompletion,I as createResponse,C as openAIError,$ as parseAnthropicMessage,A as parseChatCompletion,b as parseCompletion,q as parseResponse,E as responseStream};
|
|
@@ -1,299 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
// Edit there, then run: npm run sync:channels
|
|
4
|
-
//
|
|
5
|
-
// Vendored rather than depended on: the bridge ships zero runtime dependencies so a
|
|
6
|
-
// curl one-liner install cannot fail on someone's registry, and so the compiled
|
|
7
|
-
// single-file binary has nothing to resolve. Package imports are rewritten to the
|
|
8
|
-
// vendored engines (src/pii, src/events) by the sync script.
|
|
1
|
+
import{normalizeTelegram as tt,actorId as U}from"../normalize.js";import{buildInvocation as et,redactInbound as at,outboundText as A,appendTurn as nt,appendInvoked as ot,appendRedacted as st,appendEgress as rt}from"../invoke.js";import*as it from"../bridge.js";import{splitForTelegram as F,createGate as ct}from"../stream.js";import{createVault as dt}from"../../pii/index.js";const P="api.telegram.org",ht=["ChatPanel โ drive your local agent from here.","","Send a message and I run it on your machine.","/pair <code> โ enroll this chat (ChatPanel โ Settings โ Channels)","/new โ start fresh (forget this conversation + new privacy vault)","/stop โ stop the current run","/help โ this message"].join(`
|
|
2
|
+
`);function lt(m,d){return[!d||d==="any"?"":["You are answering a message sent from the user's PHONE, relayed to this machine.",d==="device"?"You cannot read files, run commands, browse the web, or change anything.":"You can READ files and search the user's ChatPanel history. You cannot write or edit files, run shell commands, or browse the web โ those are switched off for messages from a phone, and no tool will grant them.","If a request needs something you cannot do, say so plainly in your FIRST reply and offer what you can do instead. Never begin work you cannot finish.","Answers are read on a phone: be brief, and put the answer first."].join(" "),m].filter(Boolean).join(`
|
|
9
3
|
|
|
10
|
-
|
|
11
|
-
// OUTBOUND-ONLY, so this mirrors Claude Code Remote Control's key property: the machine never
|
|
12
|
-
// opens an inbound port, works behind NAT, needs no tunnel. The adapter is dumb transport;
|
|
13
|
-
// normalize โ gate โ redact โ invoke โ stream โ restore is the shared core it drives.
|
|
14
|
-
|
|
15
|
-
import { normalizeTelegram, actorId } from '../normalize.js';
|
|
16
|
-
import {
|
|
17
|
-
buildInvocation, redactInbound, outboundText, appendTurn,
|
|
18
|
-
appendInvoked, appendRedacted, appendEgress,
|
|
19
|
-
} from '../invoke.js';
|
|
20
|
-
import * as bridge from '../bridge.js';
|
|
21
|
-
import { splitForTelegram, createGate } from '../stream.js';
|
|
22
|
-
import { createVault } from '../../pii/index.js';
|
|
23
|
-
|
|
24
|
-
const TG_HOST = 'api.telegram.org';
|
|
25
|
-
|
|
26
|
-
const HELP = [
|
|
27
|
-
'ChatPanel โ drive your local agent from here.',
|
|
28
|
-
'',
|
|
29
|
-
'Send a message and I run it on your machine.',
|
|
30
|
-
'/pair <code> โ enroll this chat (ChatPanel โ Settings โ Channels)',
|
|
31
|
-
'/new โ start fresh (forget this conversation + new privacy vault)',
|
|
32
|
-
'/stop โ stop the current run',
|
|
33
|
-
'/help โ this message',
|
|
34
|
-
].join('\n');
|
|
35
|
-
|
|
36
|
-
/**
|
|
37
|
-
* Start the long-poll loop. Returns the loop promise; abort `signal` to stop it. Everything
|
|
38
|
-
* it needs is injected โ a bot token, the bridge address+token, a pairing store, an event sink
|
|
39
|
-
* โ so nothing here reads a secret or reaches for global state.
|
|
40
|
-
*/
|
|
41
|
-
// What a turn driven from a phone can actually DO, told to the agent up front.
|
|
42
|
-
//
|
|
43
|
-
// Without this the agent plans as if it were sitting at a terminal: asked to create a note it
|
|
44
|
-
// announced it would look for a notes folder, discovered writes were not enabled, said "let me
|
|
45
|
-
// check what notes tools are available" โ and stopped mid-thought, having done nothing and
|
|
46
|
-
// explained nothing. The ceiling is real and enforced elsewhere (reach caps the toolset); the
|
|
47
|
-
// agent simply had no way to know about it, so it spent a turn discovering it and left the
|
|
48
|
-
// user staring at half a sentence.
|
|
49
|
-
export function channelSystem(userSystem, reach) {
|
|
50
|
-
const limits = !reach || reach === 'any' ? '' : [
|
|
51
|
-
"You are answering a message sent from the user's PHONE, relayed to this machine.",
|
|
52
|
-
reach === 'device'
|
|
53
|
-
? 'You cannot read files, run commands, browse the web, or change anything.'
|
|
54
|
-
: "You can READ files and search the user's ChatPanel history. You cannot write or edit "
|
|
55
|
-
+ 'files, run shell commands, or browse the web โ those are switched off for messages '
|
|
56
|
-
+ 'from a phone, and no tool will grant them.',
|
|
57
|
-
'If a request needs something you cannot do, say so plainly in your FIRST reply and offer '
|
|
58
|
-
+ 'what you can do instead. Never begin work you cannot finish.',
|
|
59
|
-
'Answers are read on a phone: be brief, and put the answer first.',
|
|
60
|
-
].join(' ');
|
|
61
|
-
return [limits, userSystem].filter(Boolean).join('\n\n');
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
export function startTelegram({
|
|
65
|
-
botToken,
|
|
66
|
-
baseUrl,
|
|
67
|
-
token, // bridge token
|
|
68
|
-
pairing, // createPairingStore(...)
|
|
69
|
-
savePairing = async () => {},
|
|
70
|
-
appender, // createEventLog(...) or nullEventLog()
|
|
71
|
-
agent = 'claude',
|
|
72
|
-
// Which transport answers, and with what. `bridge` runs a CLI agent on this machine;
|
|
73
|
-
// `gateway` reaches any destination the user configured there โ an API provider or, via the
|
|
74
|
-
// gateway's own bridge backend, the same CLI agents. The adapter must not be able to tell
|
|
75
|
-
// which it has: both expose chat()/cancel() and fold into one reply state.
|
|
76
|
-
transport = bridge,
|
|
77
|
-
model = '',
|
|
78
|
-
provider = '',
|
|
79
|
-
system = '',
|
|
80
|
-
// Read at the START OF EACH MESSAGE rather than captured when the loop starts.
|
|
81
|
-
//
|
|
82
|
-
// `chats` below holds every conversation's history AND its privacy vault, and it lives only
|
|
83
|
-
// as long as this loop. Settings used to be baked in at start, so changing the model โ or
|
|
84
|
-
// the privacy mode, or anything else โ had to stop and respawn the loop, which silently threw
|
|
85
|
-
// all of that away: the next message arrived as "a fresh session with no prior conversation",
|
|
86
|
-
// and PERSON_1 stopped meaning the same person. Switching which model answers is not a
|
|
87
|
-
// reason to forget what you were talking about.
|
|
88
|
-
route = null,
|
|
89
|
-
redact = { tier: 'basic' },
|
|
90
|
-
privacy = 'standard',
|
|
91
|
-
logger = console,
|
|
92
|
-
signal, // AbortSignal to stop the whole loop
|
|
93
|
-
}) {
|
|
94
|
-
const api = `https://${TG_HOST}/bot${botToken}`;
|
|
95
|
-
const fileApi = `https://${TG_HOST}/file/bot${botToken}`;
|
|
96
|
-
// Per-chat session: a persistent vault (stable placeholders across turns), the live run id
|
|
97
|
-
// (/stop), and the redacted conversation history (multi-turn context).
|
|
98
|
-
const chats = new Map(); // chatId -> { vault, runId, history }
|
|
99
|
-
const freshChat = () => ({ vault: createVault(), runId: null, history: [] });
|
|
100
|
-
const chatState = (id) => {
|
|
101
|
-
if (!chats.has(id)) chats.set(id, freshChat());
|
|
102
|
-
return chats.get(id);
|
|
103
|
-
};
|
|
104
|
-
|
|
105
|
-
async function tg(method, body) {
|
|
106
|
-
const res = await fetch(`${api}/${method}`, {
|
|
107
|
-
method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), signal,
|
|
108
|
-
});
|
|
109
|
-
return res.json();
|
|
110
|
-
}
|
|
111
|
-
const send = (chatId, text) => tg('sendMessage', { chat_id: chatId, text });
|
|
112
|
-
const edit = (chatId, messageId, text) => tg('editMessageText', { chat_id: chatId, message_id: messageId, text });
|
|
113
|
-
|
|
114
|
-
// Resolve Telegram photos to the { dataUrl } shape the bridge's engines expect (Claude Code
|
|
115
|
-
// writes them to temp files and reads them as vision). A failed fetch drops that one image
|
|
116
|
-
// rather than failing the whole turn.
|
|
117
|
-
async function toBridgeImages(photos) {
|
|
118
|
-
const out = [];
|
|
119
|
-
for (const p of photos || []) {
|
|
120
|
-
try {
|
|
121
|
-
const info = await tg('getFile', { file_id: p.fileId });
|
|
122
|
-
const fp = info?.result?.file_path;
|
|
123
|
-
if (!fp) continue;
|
|
124
|
-
const bin = await fetch(`${fileApi}/${fp}`, { signal });
|
|
125
|
-
const buf = Buffer.from(await bin.arrayBuffer());
|
|
126
|
-
const mime = /\.png$/i.test(fp) ? 'image/png' : /\.webp$/i.test(fp) ? 'image/webp' : 'image/jpeg';
|
|
127
|
-
out.push({ dataUrl: `data:${mime};base64,${buf.toString('base64')}` });
|
|
128
|
-
} catch (e) { logger.warn?.(`[telegram] image fetch failed: ${e?.message || e}`); }
|
|
129
|
-
}
|
|
130
|
-
return out;
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
async function handleCommand(norm) {
|
|
134
|
-
const id = actorId('telegram', norm.chatId);
|
|
135
|
-
const { name, args } = norm.command;
|
|
136
|
-
// `/start <code>` is what a t.me/<bot>?start=<code> link SENDS. Telegram turns the link
|
|
137
|
-
// into that first message, so tapping "Pair this phone" in ChatPanel enrolls in one tap โ
|
|
138
|
-
// no six digits thumbed in from another screen. Bare /start is still the greeting.
|
|
139
|
-
const pairCode = name === 'pair' || (name === 'start' && args) ? args : '';
|
|
140
|
-
if (pairCode) {
|
|
141
|
-
const r = pairing.redeem(id, pairCode, { label: norm.from?.name || '' });
|
|
142
|
-
await savePairing();
|
|
143
|
-
return void send(norm.chatId, r.ok
|
|
144
|
-
? `โ
paired (reach: ${r.reach}). Send me anything โ I'll run it on your machine.`
|
|
145
|
-
: `โ ${r.reason}`);
|
|
146
|
-
}
|
|
147
|
-
if (name === 'help' || name === 'start') return void send(norm.chatId, HELP);
|
|
148
|
-
if (name === 'pair') return void send(norm.chatId, 'send /pair <code> โ get the code in ChatPanel โ Settings โ Channels');
|
|
149
|
-
if (name === 'new') {
|
|
150
|
-
chats.set(norm.chatId, freshChat());
|
|
151
|
-
return void send(norm.chatId, '๐งน fresh conversation.');
|
|
152
|
-
}
|
|
153
|
-
if (name === 'stop') {
|
|
154
|
-
const st = chatState(norm.chatId);
|
|
155
|
-
const ok = await ((route && route().transport) || transport).cancel(st.runId, { baseUrl, token });
|
|
156
|
-
st.runId = null;
|
|
157
|
-
return void send(norm.chatId, ok ? 'โน stopped.' : 'nothing running.');
|
|
158
|
-
}
|
|
159
|
-
return void send(norm.chatId, `unknown command /${name} โ try /help`);
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
async function handleMessage(norm) {
|
|
163
|
-
const id = actorId('telegram', norm.chatId);
|
|
164
|
-
// AUTHENTICATION gate: an unpaired sender cannot drive anything. This proves WHO, not WHAT
|
|
165
|
-
// โ tool scoping (reach โ per-actor allowlist) is the next layer and lives above the bridge.
|
|
166
|
-
const reach = pairing.reachOf(id);
|
|
167
|
-
if (!reach) {
|
|
168
|
-
return void send(norm.chatId, '๐ not paired. Get a code in the ChatPanel extension, then send: /pair <code>');
|
|
169
|
-
}
|
|
170
|
-
if (!norm.text && !norm.photos.length) return;
|
|
171
|
-
const st = chatState(norm.chatId);
|
|
172
|
-
|
|
173
|
-
// Contract + audit BEFORE anything leaves for the agent.
|
|
174
|
-
let invocation;
|
|
175
|
-
try { invocation = buildInvocation(norm); }
|
|
176
|
-
catch (e) { return void send(norm.chatId, `โ ๏ธ ${e.message}`); }
|
|
177
|
-
|
|
178
|
-
const { redacted, counts } = redactInbound(norm.text, st.vault, redact);
|
|
179
|
-
await appendInvoked(appender, invocation);
|
|
180
|
-
await appendRedacted(appender, counts);
|
|
181
|
-
|
|
182
|
-
const images = await toBridgeImages(norm.photos);
|
|
183
|
-
const placeholder = await tg('sendMessage', { chat_id: norm.chatId, text: 'โฆ' });
|
|
184
|
-
const replyId = placeholder?.result?.message_id;
|
|
185
|
-
const gate = createGate(1200); // ~1 edit/sec, Telegram's ceiling for a chat
|
|
186
|
-
let shown = '';
|
|
187
|
-
|
|
188
|
-
// Replay prior turns as context; the new (redacted) message is the live one. buildCliPrompt
|
|
189
|
-
// on the bridge renders all-but-last as history and the last as "answer this now".
|
|
190
|
-
const messages = [...st.history, { role: 'user', content: redacted }];
|
|
191
|
-
|
|
192
|
-
// Whatever the settings say RIGHT NOW โ see `route` above.
|
|
193
|
-
const live = (route && route()) || {};
|
|
194
|
-
const useTransport = live.transport || transport;
|
|
195
|
-
try {
|
|
196
|
-
const finalState = await useTransport.chat(
|
|
197
|
-
{
|
|
198
|
-
agent: live.agent ?? agent,
|
|
199
|
-
model: live.model ?? model,
|
|
200
|
-
provider: live.provider ?? provider,
|
|
201
|
-
system: channelSystem(live.system ?? system, reach),
|
|
202
|
-
messages,
|
|
203
|
-
images,
|
|
204
|
-
options: { reach },
|
|
205
|
-
},
|
|
206
|
-
{
|
|
207
|
-
baseUrl: live.baseUrl || baseUrl, token, signal,
|
|
208
|
-
onEvent: (ev, state) => {
|
|
209
|
-
if (state.runId) st.runId = state.runId;
|
|
210
|
-
// Driven by the folded STATE, not by an event's `type`: the bridge emits
|
|
211
|
-
// {type:'delta'} and the gateway emits OpenAI chunks, and this has to work on both.
|
|
212
|
-
// The `first !== shown` guard below makes a no-text event a no-op anyway.
|
|
213
|
-
if (replyId && (state.done || gate.ready())) {
|
|
214
|
-
const text = outboundText(state.text, st.vault, { privacy });
|
|
215
|
-
const first = splitForTelegram(text || 'โฆ')[0];
|
|
216
|
-
if (first && first !== shown) { shown = first; edit(norm.chatId, replyId, first).catch(() => {}); }
|
|
217
|
-
}
|
|
218
|
-
},
|
|
219
|
-
},
|
|
220
|
-
);
|
|
221
|
-
st.runId = null;
|
|
222
|
-
|
|
223
|
-
const restored = outboundText(finalState.text, st.vault, { privacy });
|
|
224
|
-
const chunks = splitForTelegram(finalState.error ? `โ ๏ธ ${finalState.error}` : (restored || '(no output)'));
|
|
225
|
-
if (replyId) await edit(norm.chatId, replyId, chunks[0]);
|
|
226
|
-
else await send(norm.chatId, chunks[0]);
|
|
227
|
-
for (const extra of chunks.slice(1)) await send(norm.chatId, extra);
|
|
228
|
-
|
|
229
|
-
// Remember the exchange for follow-ups โ the REDACTED forms, so what we replay next turn
|
|
230
|
-
// never carries a real value and stays consistent with the vault. A failed turn (error /
|
|
231
|
-
// no text) records nothing, so history never implies an answer that didn't happen.
|
|
232
|
-
if (!finalState.error && finalState.text) st.history = appendTurn(st.history, redacted, finalState.text);
|
|
233
|
-
|
|
234
|
-
// Egress to Telegram, recorded: 'standard' restores real values (a third party sees
|
|
235
|
-
// them โ redacted:false); 'strict' keeps placeholders (redacted:true). controlled:false
|
|
236
|
-
// either way โ Telegram is not ours.
|
|
237
|
-
await appendEgress(appender, { host: TG_HOST, redacted: privacy === 'strict', controlled: false });
|
|
238
|
-
} catch (e) {
|
|
239
|
-
st.runId = null;
|
|
240
|
-
const msg = `โ ๏ธ ${e?.message || e}`;
|
|
241
|
-
if (replyId) await edit(norm.chatId, replyId, msg).catch(() => {});
|
|
242
|
-
else await send(norm.chatId, msg).catch(() => {});
|
|
243
|
-
}
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
// A sleep that gives up when the loop is asked to stop, so Ctrl-C is immediate rather than
|
|
247
|
-
// "immediate in up to five seconds".
|
|
248
|
-
const nap = (ms) => new Promise((resolve) => {
|
|
249
|
-
if (signal?.aborted) return resolve();
|
|
250
|
-
let t;
|
|
251
|
-
const done = () => { clearTimeout(t); signal?.removeEventListener?.('abort', done); resolve(); };
|
|
252
|
-
t = setTimeout(done, ms);
|
|
253
|
-
signal?.addEventListener?.('abort', done, { once: true });
|
|
254
|
-
});
|
|
255
|
-
|
|
256
|
-
async function loop() {
|
|
257
|
-
let offset = 0;
|
|
258
|
-
logger.log?.('[telegram] long-poll started (outbound-only; no inbound port).');
|
|
259
|
-
while (!signal?.aborted) {
|
|
260
|
-
let updates;
|
|
261
|
-
try {
|
|
262
|
-
const res = await tg('getUpdates', { offset, timeout: 30, allowed_updates: ['message'] });
|
|
263
|
-
// Telegram REFUSES with a normal JSON body, not an HTTP error this code would throw
|
|
264
|
-
// on: a bad token answers {ok:false, 401} INSTANTLY, so `res.result || []` turned a
|
|
265
|
-
// wrong token into a silent hot loop โ no message, no long-poll delay, and an API
|
|
266
|
-
// hammered hard enough to get rate-limited. The two refusals that actually happen
|
|
267
|
-
// during setup are named, because "nothing arrives" is the same symptom as "it works
|
|
268
|
-
// and nobody has texted you".
|
|
269
|
-
if (res && res.ok === false) {
|
|
270
|
-
const code = res.error_code;
|
|
271
|
-
const hint = code === 401 ? ' โ check the bot token (@BotFather โ /mybots โ API token)'
|
|
272
|
-
: code === 409 ? ' โ another chatpanel-channels (or another poller) is already reading this bot'
|
|
273
|
-
: '';
|
|
274
|
-
logger.error?.(`[telegram] getUpdates refused: ${res.description || `error_code ${code}`}${hint}`);
|
|
275
|
-
await nap(5000);
|
|
276
|
-
continue;
|
|
277
|
-
}
|
|
278
|
-
updates = res?.result || [];
|
|
279
|
-
} catch (e) {
|
|
280
|
-
if (signal?.aborted) break;
|
|
281
|
-
logger.warn?.(`[telegram] getUpdates failed: ${e?.message || e}; retrying in 2s`);
|
|
282
|
-
await nap(2000);
|
|
283
|
-
continue;
|
|
284
|
-
}
|
|
285
|
-
for (const u of updates) {
|
|
286
|
-
offset = u.update_id + 1;
|
|
287
|
-
const norm = normalizeTelegram(u);
|
|
288
|
-
if (!norm) continue;
|
|
289
|
-
// Fire-and-forget per message so one slow turn doesn't stall the poll; errors are
|
|
290
|
-
// caught so a single bad message never kills the loop.
|
|
291
|
-
const run = norm.command ? handleCommand(norm) : handleMessage(norm);
|
|
292
|
-
Promise.resolve(run).catch((e) => logger.error?.(`[telegram] handler error: ${e?.message || e}`));
|
|
293
|
-
}
|
|
294
|
-
}
|
|
295
|
-
logger.log?.('[telegram] stopped.');
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
return loop();
|
|
299
|
-
}
|
|
4
|
+
`)}function wt({botToken:m,baseUrl:d,token:v,pairing:C,savePairing:Y=async()=>{},appender:$,agent:G="claude",transport:k=it,model:H="",provider:L="",system:N="",route:g=null,redact:R={tier:"basic"},privacy:x="standard",logger:h=console,signal:c}){const q=`https://${P}/bot${m}`,z=`https://${P}/file/bot${m}`,w=new Map,E=()=>({vault:dt(),runId:null,history:[]}),j=t=>(w.has(t)||w.set(t,E()),w.get(t));async function f(t,n){return(await fetch(`${q}/${t}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n),signal:c})).json()}const r=(t,n)=>f("sendMessage",{chat_id:t,text:n}),S=(t,n,e)=>f("editMessageText",{chat_id:t,message_id:n,text:e});async function D(t){const n=[];for(const e of t||[])try{const o=(await f("getFile",{file_id:e.fileId}))?.result?.file_path;if(!o)continue;const s=await fetch(`${z}/${o}`,{signal:c}),p=Buffer.from(await s.arrayBuffer()),T=/\.png$/i.test(o)?"image/png":/\.webp$/i.test(o)?"image/webp":"image/jpeg";n.push({dataUrl:`data:${T};base64,${p.toString("base64")}`})}catch(a){h.warn?.(`[telegram] image fetch failed: ${a?.message||a}`)}return n}async function J(t){const n=U("telegram",t.chatId),{name:e,args:a}=t.command,o=e==="pair"||e==="start"&&a?a:"";if(o){const s=C.redeem(n,o,{label:t.from?.name||""});return await Y(),void r(t.chatId,s.ok?`โ
paired (reach: ${s.reach}). Send me anything โ I'll run it on your machine.`:`โ ${s.reason}`)}if(e==="help"||e==="start")return void r(t.chatId,ht);if(e==="pair")return void r(t.chatId,"send /pair <code> โ get the code in ChatPanel โ Settings โ Channels");if(e==="new")return w.set(t.chatId,E()),void r(t.chatId,"๐งน fresh conversation.");if(e==="stop"){const s=j(t.chatId),p=await(g&&g().transport||k).cancel(s.runId,{baseUrl:d,token:v});return s.runId=null,void r(t.chatId,p?"โน stopped.":"nothing running.")}r(t.chatId,`unknown command /${e} โ try /help`)}async function V(t){const n=U("telegram",t.chatId),e=C.reachOf(n);if(!e)return void r(t.chatId,"๐ not paired. Get a code in the ChatPanel extension, then send: /pair <code>");if(!t.text&&!t.photos.length)return;const a=j(t.chatId);let o;try{o=et(t)}catch(i){return void r(t.chatId,`โ ๏ธ ${i.message}`)}const{redacted:s,counts:p}=at(t.text,a.vault,R);await ot($,o),await st($,p);const T=await D(t.photos),l=(await f("sendMessage",{chat_id:t.chatId,text:"โฆ"}))?.result?.message_id,Q=ct(1200);let M="";const W=[...a.history,{role:"user",content:s}],u=g&&g()||{},X=u.transport||k;try{const i=await X.chat({agent:u.agent??G,model:u.model??H,provider:u.provider??L,system:lt(u.system??N,e),messages:W,images:T,options:{reach:e}},{baseUrl:u.baseUrl||d,token:v,signal:c,onEvent:(O,I)=>{if(I.runId&&(a.runId=I.runId),l&&(I.done||Q.ready())){const Z=A(I.text,a.vault,{privacy:x}),b=F(Z||"โฆ")[0];b&&b!==M&&(M=b,S(t.chatId,l,b).catch(()=>{}))}}});a.runId=null;const y=A(i.text,a.vault,{privacy:x}),_=F(i.error?`โ ๏ธ ${i.error}`:y||"(no output)");l?await S(t.chatId,l,_[0]):await r(t.chatId,_[0]);for(const O of _.slice(1))await r(t.chatId,O);!i.error&&i.text&&(a.history=nt(a.history,s,i.text)),await rt($,{host:P,redacted:x==="strict",controlled:!1})}catch(i){a.runId=null;const y=`โ ๏ธ ${i?.message||i}`;l?await S(t.chatId,l,y).catch(()=>{}):await r(t.chatId,y).catch(()=>{})}}const B=t=>new Promise(n=>{if(c?.aborted)return n();let e;const a=()=>{clearTimeout(e),c?.removeEventListener?.("abort",a),n()};e=setTimeout(a,t),c?.addEventListener?.("abort",a,{once:!0})});async function K(){let t=0;for(h.log?.("[telegram] long-poll started (outbound-only; no inbound port).");!c?.aborted;){let n;try{const e=await f("getUpdates",{offset:t,timeout:30,allowed_updates:["message"]});if(e&&e.ok===!1){const a=e.error_code,o=a===401?" โ check the bot token (@BotFather โ /mybots โ API token)":a===409?" โ another chatpanel-channels (or another poller) is already reading this bot":"";h.error?.(`[telegram] getUpdates refused: ${e.description||`error_code ${a}`}${o}`),await B(5e3);continue}n=e?.result||[]}catch(e){if(c?.aborted)break;h.warn?.(`[telegram] getUpdates failed: ${e?.message||e}; retrying in 2s`),await B(2e3);continue}for(const e of n){t=e.update_id+1;const a=tt(e);if(!a)continue;const o=a.command?J(a):V(a);Promise.resolve(o).catch(s=>h.error?.(`[telegram] handler error: ${s?.message||s}`))}}h.log?.("[telegram] stopped.")}return K()}export{lt as channelSystem,wt as startTelegram};
|