@gricha/perry 0.2.6 → 0.3.1

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.
Files changed (44) hide show
  1. package/dist/agent/router.js +127 -0
  2. package/dist/agent/run.js +157 -99
  3. package/dist/agent/static.js +32 -0
  4. package/dist/agent/web/assets/index-CYo-1I5o.css +1 -0
  5. package/dist/agent/web/assets/index-CZjSxNrg.js +104 -0
  6. package/dist/agent/web/index.html +2 -2
  7. package/dist/client/api.js +19 -0
  8. package/dist/client/docker-proxy.js +2 -16
  9. package/dist/client/port-forward.js +23 -0
  10. package/dist/client/proxy.js +2 -16
  11. package/dist/config/loader.js +2 -6
  12. package/dist/index.js +1 -15
  13. package/dist/perry-worker +0 -0
  14. package/dist/session-manager/adapters/claude.js +256 -0
  15. package/dist/session-manager/adapters/index.js +2 -0
  16. package/dist/session-manager/adapters/opencode.js +317 -0
  17. package/dist/session-manager/bun-handler.js +175 -0
  18. package/dist/session-manager/index.js +3 -0
  19. package/dist/session-manager/manager.js +302 -0
  20. package/dist/session-manager/ring-buffer.js +66 -0
  21. package/dist/session-manager/types.js +1 -0
  22. package/dist/session-manager/websocket.js +153 -0
  23. package/dist/sessions/agents/utils.js +6 -2
  24. package/dist/sessions/parser.js +1 -11
  25. package/dist/shared/base-websocket.js +39 -7
  26. package/dist/shared/format-utils.js +15 -0
  27. package/dist/shared/path-utils.js +8 -0
  28. package/dist/ssh/sync.js +1 -8
  29. package/dist/tailscale/index.js +20 -6
  30. package/dist/terminal/bun-handler.js +151 -0
  31. package/package.json +4 -7
  32. package/dist/agent/web/assets/index-BwItLEFi.css +0 -1
  33. package/dist/agent/web/assets/index-DhU_amC3.js +0 -104
  34. package/dist/chat/base-chat-websocket.js +0 -86
  35. package/dist/chat/base-claude-session.js +0 -169
  36. package/dist/chat/base-opencode-session.js +0 -181
  37. package/dist/chat/handler.js +0 -47
  38. package/dist/chat/host-handler.js +0 -41
  39. package/dist/chat/host-opencode-handler.js +0 -144
  40. package/dist/chat/index.js +0 -2
  41. package/dist/chat/opencode-handler.js +0 -100
  42. package/dist/chat/opencode-server.js +0 -285
  43. package/dist/chat/opencode-websocket.js +0 -31
  44. package/dist/chat/websocket.js +0 -33
@@ -1,100 +0,0 @@
1
- import { BaseOpencodeSession } from './base-opencode-session';
2
- import { opencodeProvider } from '../sessions/agents/opencode';
3
- export class OpencodeSession extends BaseOpencodeSession {
4
- containerName;
5
- workDir;
6
- constructor(options, onMessage) {
7
- super(options.sessionId, options.model, onMessage);
8
- this.containerName = options.containerName;
9
- this.workDir = options.workDir || '/home/workspace';
10
- }
11
- getLogPrefix() {
12
- return 'opencode';
13
- }
14
- getNoOutputErrorMessage() {
15
- return 'No response from OpenCode. Check if OpenCode is configured in the workspace.';
16
- }
17
- getSpawnConfig(userMessage) {
18
- const args = [
19
- 'docker',
20
- 'exec',
21
- '-i',
22
- '-u',
23
- 'workspace',
24
- '-w',
25
- this.workDir,
26
- this.containerName,
27
- 'stdbuf',
28
- '-oL',
29
- 'opencode',
30
- 'run',
31
- '--format',
32
- 'json',
33
- ];
34
- if (this.sessionId) {
35
- args.push('--session', this.sessionId);
36
- }
37
- if (this.model) {
38
- args.push('--model', this.model);
39
- }
40
- args.push(userMessage);
41
- return {
42
- command: args,
43
- options: {},
44
- };
45
- }
46
- async loadHistory() {
47
- if (this.historyLoaded || !this.sessionId) {
48
- return;
49
- }
50
- this.historyLoaded = true;
51
- const exec = async (containerName, command, options) => {
52
- const args = ['exec'];
53
- if (options?.user) {
54
- args.push('-u', options.user);
55
- }
56
- args.push(containerName, ...command);
57
- const proc = Bun.spawn(['docker', ...args], {
58
- stdin: 'ignore',
59
- stdout: 'pipe',
60
- stderr: 'pipe',
61
- });
62
- const [stdout, stderr, exitCode] = await Promise.all([
63
- new Response(proc.stdout).text(),
64
- new Response(proc.stderr).text(),
65
- proc.exited,
66
- ]);
67
- return { stdout, stderr, exitCode };
68
- };
69
- try {
70
- const result = await opencodeProvider.getSessionMessages(this.containerName, this.sessionId, exec);
71
- if (result && result.messages.length > 0) {
72
- this.onMessage({
73
- type: 'system',
74
- content: `Loading ${result.messages.length} messages from session history...`,
75
- timestamp: new Date().toISOString(),
76
- });
77
- for (const msg of result.messages) {
78
- this.onMessage({
79
- type: msg.type,
80
- content: msg.content || '',
81
- toolName: msg.toolName,
82
- toolId: msg.toolId,
83
- timestamp: msg.timestamp || new Date().toISOString(),
84
- });
85
- }
86
- this.onMessage({
87
- type: 'system',
88
- content: 'Session history loaded',
89
- timestamp: new Date().toISOString(),
90
- });
91
- }
92
- }
93
- catch (err) {
94
- console.error('[opencode] Failed to load history:', err);
95
- }
96
- }
97
- }
98
- export function createOpencodeSession(options, onMessage) {
99
- return new OpencodeSession(options, onMessage);
100
- }
@@ -1,285 +0,0 @@
1
- import { execInContainer } from '../docker';
2
- const serverPorts = new Map();
3
- const serverStarting = new Map();
4
- async function findAvailablePort(containerName) {
5
- const script = `import socket; s=socket.socket(); s.bind(('', 0)); print(s.getsockname()[1]); s.close()`;
6
- const result = await execInContainer(containerName, ['python3', '-c', script], {
7
- user: 'workspace',
8
- });
9
- return parseInt(result.stdout.trim(), 10);
10
- }
11
- async function isServerRunning(containerName, port) {
12
- try {
13
- const result = await execInContainer(containerName, ['curl', '-s', '-o', '/dev/null', '-w', '%{http_code}', `http://localhost:${port}/session`], { user: 'workspace' });
14
- return result.stdout.trim() === '200';
15
- }
16
- catch {
17
- return false;
18
- }
19
- }
20
- async function startServer(containerName) {
21
- const existing = serverPorts.get(containerName);
22
- if (existing && (await isServerRunning(containerName, existing))) {
23
- return existing;
24
- }
25
- const starting = serverStarting.get(containerName);
26
- if (starting) {
27
- return starting;
28
- }
29
- const startPromise = (async () => {
30
- const port = await findAvailablePort(containerName);
31
- console.log(`[opencode-server] Starting server on port ${port} in ${containerName}`);
32
- await execInContainer(containerName, [
33
- 'sh',
34
- '-c',
35
- `nohup opencode serve --port ${port} --hostname 127.0.0.1 > /tmp/opencode-server.log 2>&1 &`,
36
- ], { user: 'workspace' });
37
- for (let i = 0; i < 30; i++) {
38
- await new Promise((resolve) => setTimeout(resolve, 500));
39
- if (await isServerRunning(containerName, port)) {
40
- console.log(`[opencode-server] Server started on port ${port}`);
41
- serverPorts.set(containerName, port);
42
- serverStarting.delete(containerName);
43
- return port;
44
- }
45
- }
46
- serverStarting.delete(containerName);
47
- throw new Error('Failed to start OpenCode server');
48
- })();
49
- serverStarting.set(containerName, startPromise);
50
- return startPromise;
51
- }
52
- export class OpenCodeServerSession {
53
- containerName;
54
- workDir;
55
- sessionId;
56
- model;
57
- sessionModel;
58
- onMessage;
59
- sseProcess = null;
60
- responseComplete = false;
61
- seenToolUse = new Set();
62
- seenToolResult = new Set();
63
- constructor(options, onMessage) {
64
- this.containerName = options.containerName;
65
- this.workDir = options.workDir || '/home/workspace';
66
- this.sessionId = options.sessionId;
67
- this.model = options.model;
68
- this.sessionModel = options.model;
69
- this.onMessage = onMessage;
70
- }
71
- async sendMessage(userMessage) {
72
- const port = await startServer(this.containerName);
73
- const baseUrl = `http://localhost:${port}`;
74
- this.onMessage({
75
- type: 'system',
76
- content: 'Processing your message...',
77
- timestamp: new Date().toISOString(),
78
- });
79
- try {
80
- if (!this.sessionId) {
81
- const sessionPayload = this.model ? JSON.stringify({ model: this.model }) : '{}';
82
- const createResult = await execInContainer(this.containerName, [
83
- 'curl',
84
- '-s',
85
- '-X',
86
- 'POST',
87
- `${baseUrl}/session`,
88
- '-H',
89
- 'Content-Type: application/json',
90
- '-d',
91
- sessionPayload,
92
- ], { user: 'workspace' });
93
- const session = JSON.parse(createResult.stdout);
94
- this.sessionId = session.id;
95
- this.sessionModel = this.model;
96
- this.onMessage({
97
- type: 'system',
98
- content: `Session started ${this.sessionId}`,
99
- timestamp: new Date().toISOString(),
100
- });
101
- }
102
- this.responseComplete = false;
103
- this.seenToolUse.clear();
104
- this.seenToolResult.clear();
105
- const { ready, done } = await this.startSSEStream(port);
106
- await ready;
107
- const messagePayload = JSON.stringify({
108
- parts: [{ type: 'text', text: userMessage }],
109
- });
110
- execInContainer(this.containerName, [
111
- 'curl',
112
- '-s',
113
- '-X',
114
- 'POST',
115
- `${baseUrl}/session/${this.sessionId}/message`,
116
- '-H',
117
- 'Content-Type: application/json',
118
- '-d',
119
- messagePayload,
120
- ], { user: 'workspace' }).catch((err) => {
121
- console.error('[opencode-server] Send error:', err);
122
- });
123
- await done;
124
- this.onMessage({
125
- type: 'done',
126
- content: 'Response complete',
127
- timestamp: new Date().toISOString(),
128
- });
129
- }
130
- catch (err) {
131
- console.error('[opencode-server] Error:', err);
132
- this.onMessage({
133
- type: 'error',
134
- content: err.message,
135
- timestamp: new Date().toISOString(),
136
- });
137
- }
138
- }
139
- async startSSEStream(port) {
140
- let resolveReady;
141
- let resolveDone;
142
- const ready = new Promise((r) => (resolveReady = r));
143
- const done = new Promise((r) => (resolveDone = r));
144
- const proc = Bun.spawn([
145
- 'docker',
146
- 'exec',
147
- '-i',
148
- this.containerName,
149
- 'curl',
150
- '-s',
151
- '-N',
152
- '--max-time',
153
- '120',
154
- `http://localhost:${port}/event`,
155
- ], {
156
- stdin: 'ignore',
157
- stdout: 'pipe',
158
- stderr: 'pipe',
159
- });
160
- this.sseProcess = proc;
161
- const decoder = new TextDecoder();
162
- let buffer = '';
163
- let hasReceivedData = false;
164
- const processChunk = (chunk) => {
165
- buffer += decoder.decode(chunk);
166
- if (!hasReceivedData) {
167
- hasReceivedData = true;
168
- resolveReady();
169
- }
170
- const lines = buffer.split('\n');
171
- buffer = lines.pop() || '';
172
- for (const line of lines) {
173
- if (!line.startsWith('data: '))
174
- continue;
175
- const data = line.slice(6).trim();
176
- if (!data)
177
- continue;
178
- try {
179
- const event = JSON.parse(data);
180
- this.handleEvent(event);
181
- if (event.type === 'session.idle') {
182
- this.responseComplete = true;
183
- proc.kill();
184
- resolveDone();
185
- return;
186
- }
187
- }
188
- catch {
189
- continue;
190
- }
191
- }
192
- };
193
- (async () => {
194
- if (!proc.stdout) {
195
- resolveReady();
196
- resolveDone();
197
- return;
198
- }
199
- for await (const chunk of proc.stdout) {
200
- processChunk(chunk);
201
- if (this.responseComplete)
202
- break;
203
- }
204
- resolveDone();
205
- })();
206
- setTimeout(() => {
207
- if (!hasReceivedData) {
208
- resolveReady();
209
- }
210
- }, 500);
211
- setTimeout(() => {
212
- if (!this.responseComplete) {
213
- proc.kill();
214
- resolveDone();
215
- }
216
- }, 120000);
217
- return { ready, done };
218
- }
219
- handleEvent(event) {
220
- const timestamp = new Date().toISOString();
221
- if (event.type === 'message.part.updated' && event.properties.part) {
222
- const part = event.properties.part;
223
- if (part.type === 'text' && event.properties.delta) {
224
- this.onMessage({
225
- type: 'assistant',
226
- content: event.properties.delta,
227
- timestamp,
228
- });
229
- }
230
- else if (part.type === 'tool' && part.tool) {
231
- const state = part.state;
232
- const partId = part.id;
233
- if (!this.seenToolUse.has(partId)) {
234
- this.seenToolUse.add(partId);
235
- this.onMessage({
236
- type: 'tool_use',
237
- content: JSON.stringify(state?.input, null, 2),
238
- toolName: state?.title || part.tool,
239
- toolId: partId,
240
- timestamp,
241
- });
242
- }
243
- if (state?.status === 'completed' && state?.output && !this.seenToolResult.has(partId)) {
244
- this.seenToolResult.add(partId);
245
- this.onMessage({
246
- type: 'tool_result',
247
- content: state.output,
248
- toolId: partId,
249
- timestamp,
250
- });
251
- }
252
- }
253
- }
254
- }
255
- async interrupt() {
256
- if (this.sseProcess) {
257
- this.sseProcess.kill();
258
- this.sseProcess = null;
259
- this.onMessage({
260
- type: 'system',
261
- content: 'Chat interrupted',
262
- timestamp: new Date().toISOString(),
263
- });
264
- }
265
- }
266
- setModel(model) {
267
- if (this.model !== model) {
268
- this.model = model;
269
- if (this.sessionModel !== model) {
270
- this.sessionId = undefined;
271
- this.onMessage({
272
- type: 'system',
273
- content: `Switching to model: ${model}`,
274
- timestamp: new Date().toISOString(),
275
- });
276
- }
277
- }
278
- }
279
- getSessionId() {
280
- return this.sessionId;
281
- }
282
- }
283
- export function createOpenCodeServerSession(options, onMessage) {
284
- return new OpenCodeServerSession(options, onMessage);
285
- }
@@ -1,31 +0,0 @@
1
- import { BaseChatWebSocketServer, } from './base-chat-websocket';
2
- import { createHostOpencodeSession } from './host-opencode-handler';
3
- import { createOpenCodeServerSession } from './opencode-server';
4
- export class OpencodeWebSocketServer extends BaseChatWebSocketServer {
5
- agentType = 'opencode';
6
- getConfig;
7
- constructor(options) {
8
- super(options);
9
- this.getConfig = options.getConfig;
10
- }
11
- createConnection(ws, workspaceName) {
12
- return {
13
- ws,
14
- session: null,
15
- workspaceName,
16
- };
17
- }
18
- createHostSession(sessionId, onMessage, messageModel, _projectPath) {
19
- const model = messageModel || this.getConfig?.()?.agents?.opencode?.model;
20
- return createHostOpencodeSession({ sessionId, model }, onMessage);
21
- }
22
- createContainerSession(containerName, sessionId, onMessage, messageModel) {
23
- const model = messageModel || this.getConfig?.()?.agents?.opencode?.model;
24
- return createOpenCodeServerSession({
25
- containerName,
26
- workDir: '/home/workspace',
27
- sessionId,
28
- model,
29
- }, onMessage);
30
- }
31
- }
@@ -1,33 +0,0 @@
1
- import { BaseChatWebSocketServer, } from './base-chat-websocket';
2
- import { createChatSession } from './handler';
3
- import { createHostChatSession } from './host-handler';
4
- export class ChatWebSocketServer extends BaseChatWebSocketServer {
5
- getConfig;
6
- agentType = '';
7
- constructor(options) {
8
- super(options);
9
- this.getConfig = options.getConfig;
10
- }
11
- createConnection(ws, workspaceName) {
12
- return {
13
- ws,
14
- session: null,
15
- workspaceName,
16
- };
17
- }
18
- createHostSession(sessionId, onMessage, messageModel, projectPath) {
19
- const config = this.getConfig();
20
- const model = messageModel || config.agents?.claude_code?.model;
21
- return createHostChatSession({ sessionId, model, workDir: projectPath }, onMessage);
22
- }
23
- createContainerSession(containerName, sessionId, onMessage, messageModel) {
24
- const config = this.getConfig();
25
- const model = messageModel || config.agents?.claude_code?.model;
26
- return createChatSession({
27
- containerName,
28
- workDir: '/home/workspace',
29
- sessionId,
30
- model,
31
- }, onMessage);
32
- }
33
- }