ubiquity-core 0.1.1

Core types and traits for Ubiquity consciousness-aware mesh
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
// Cloudflare Worker for command execution with Durable Objects

export default {
  async fetch(request, env) {
    const url = new URL(request.url);
    const path = url.pathname;

    // Route requests to appropriate handlers
    if (path.startsWith('/api/commands/execute')) {
      return handleExecute(request, env);
    } else if (path.match(/^\/api\/commands\/[^\/]+\/cancel$/)) {
      return handleCancel(request, env);
    } else if (path.match(/^\/api\/commands\/[^\/]+\/status$/)) {
      return handleStatus(request, env);
    } else if (path.startsWith('/ws/')) {
      return handleWebSocket(request, env);
    }

    return new Response('Not Found', { status: 404 });
  }
};

async function handleExecute(request, env) {
  try {
    const { request: commandRequest, namespace_id } = await request.json();
    
    // Create a new Durable Object for this command
    const id = env.COMMAND_EXECUTOR.newUniqueId();
    const executor = env.COMMAND_EXECUTOR.get(id);
    
    // Initialize the executor with the command
    const response = await executor.fetch(new Request('http://internal/execute', {
      method: 'POST',
      body: JSON.stringify(commandRequest)
    }));
    
    if (!response.ok) {
      return new Response('Failed to initialize command', { status: 500 });
    }
    
    // Return the WebSocket URL for streaming
    const wsUrl = `${new URL(request.url).origin}/ws/${id.toString()}`;
    
    return new Response(JSON.stringify({
      durable_object_id: id.toString(),
      websocket_url: wsUrl
    }), {
      headers: { 'Content-Type': 'application/json' }
    });
  } catch (error) {
    return new Response(JSON.stringify({ error: error.message }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
}

async function handleCancel(request, env) {
  const url = new URL(request.url);
  const commandId = url.pathname.split('/')[3];
  
  try {
    const id = env.COMMAND_EXECUTOR.idFromString(commandId);
    const executor = env.COMMAND_EXECUTOR.get(id);
    
    return await executor.fetch(new Request('http://internal/cancel', {
      method: 'POST'
    }));
  } catch (error) {
    return new Response(JSON.stringify({ error: error.message }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
}

async function handleStatus(request, env) {
  const url = new URL(request.url);
  const commandId = url.pathname.split('/')[3];
  
  try {
    const id = env.COMMAND_EXECUTOR.idFromString(commandId);
    const executor = env.COMMAND_EXECUTOR.get(id);
    
    return await executor.fetch(new Request('http://internal/status'));
  } catch (error) {
    return new Response(JSON.stringify({ error: error.message }), {
      status: 404,
      headers: { 'Content-Type': 'application/json' }
    });
  }
}

async function handleWebSocket(request, env) {
  const url = new URL(request.url);
  const durableObjectId = url.pathname.split('/')[2];
  
  try {
    const id = env.COMMAND_EXECUTOR.idFromString(durableObjectId);
    const executor = env.COMMAND_EXECUTOR.get(id);
    
    return await executor.fetch(new Request('http://internal/websocket', {
      headers: request.headers
    }));
  } catch (error) {
    return new Response('WebSocket connection failed', { status: 500 });
  }
}

// Durable Object implementation
export class CommandExecutor {
  constructor(state, env) {
    this.state = state;
    this.env = env;
    this.websockets = [];
    this.commandResult = null;
    this.eventHistory = [];
    this.command = null;
    this.cancelled = false;
    this.startTime = null;
  }

  async fetch(request) {
    const url = new URL(request.url);
    const path = url.pathname;

    switch (path) {
      case '/execute':
        return this.handleExecute(request);
      case '/websocket':
        return this.handleWebSocket(request);
      case '/cancel':
        return this.handleCancel(request);
      case '/status':
        return this.handleStatus(request);
      default:
        return new Response('Not Found', { status: 404 });
    }
  }

  async handleExecute(request) {
    try {
      this.command = await request.json();
      this.startTime = Date.now();
      
      // Start execution in the background
      this.executeCommand();
      
      return new Response('OK', { status: 200 });
    } catch (error) {
      return new Response(JSON.stringify({ error: error.message }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }
  }

  async handleWebSocket(request) {
    const upgradeHeader = request.headers.get('Upgrade');
    if (!upgradeHeader || upgradeHeader !== 'websocket') {
      return new Response('Expected Upgrade: websocket', { status: 426 });
    }

    const [client, server] = Object.values(new WebSocketPair());
    
    await this.handleWebSocketConnection(server);
    
    return new Response(null, {
      status: 101,
      webSocket: client,
    });
  }

  async handleWebSocketConnection(websocket) {
    websocket.accept();
    this.websockets.push(websocket);
    
    // Send any historical events
    for (const event of this.eventHistory) {
      websocket.send(JSON.stringify({
        type: 'Event',
        event: event
      }));
    }
    
    // Handle incoming messages
    websocket.addEventListener('message', async (event) => {
      try {
        const message = JSON.parse(event.data);
        
        switch (message.type) {
          case 'Subscribe':
            // Already subscribed by connecting
            break;
          case 'Cancel':
            this.cancelled = true;
            break;
        }
      } catch (error) {
        websocket.send(JSON.stringify({
          type: 'Error',
          message: error.message
        }));
      }
    });
    
    // Clean up on close
    websocket.addEventListener('close', () => {
      this.websockets = this.websockets.filter(ws => ws !== websocket);
    });
  }

  async handleCancel(request) {
    this.cancelled = true;
    
    const event = {
      type: 'Cancelled',
      command_id: this.command.id,
      duration_ms: Date.now() - this.startTime,
      timestamp: new Date().toISOString()
    };
    
    this.broadcastEvent(event);
    
    return new Response('OK', { status: 200 });
  }

  async handleStatus(request) {
    if (!this.commandResult) {
      return new Response('Not Found', { status: 404 });
    }
    
    return new Response(JSON.stringify(this.commandResult), {
      headers: { 'Content-Type': 'application/json' }
    });
  }

  async executeCommand() {
    const commandId = this.command.id;
    
    // Send start event
    this.broadcastEvent({
      type: 'Started',
      command_id: commandId,
      command: this.command.command,
      args: this.command.args,
      timestamp: new Date().toISOString()
    });
    
    try {
      // Simulate command execution
      const result = await this.simulateCommand(this.command);
      
      // Send output events
      for (const line of result.stdout) {
        if (this.cancelled) break;
        
        this.broadcastEvent({
          type: 'Stdout',
          command_id: commandId,
          data: line,
          timestamp: new Date().toISOString()
        });
        
        await this.delay(10);
      }
      
      for (const line of result.stderr) {
        if (this.cancelled) break;
        
        this.broadcastEvent({
          type: 'Stderr',
          command_id: commandId,
          data: line,
          timestamp: new Date().toISOString()
        });
        
        await this.delay(10);
      }
      
      // Send progress events
      for (const [percentage, message] of result.progress || []) {
        if (this.cancelled) break;
        
        this.broadcastEvent({
          type: 'Progress',
          command_id: commandId,
          percentage: percentage,
          message: message,
          timestamp: new Date().toISOString()
        });
        
        await this.delay(50);
      }
      
      const duration = Date.now() - this.startTime;
      
      if (!this.cancelled) {
        // Send completion event
        this.broadcastEvent({
          type: 'Completed',
          command_id: commandId,
          exit_code: result.exitCode,
          duration_ms: duration,
          timestamp: new Date().toISOString()
        });
        
        // Store result
        this.commandResult = {
          id: commandId,
          exit_code: result.exitCode,
          stdout: result.stdout.join('\n'),
          stderr: result.stderr.join('\n'),
          duration_ms: duration,
          cancelled: false
        };
      } else {
        this.commandResult = {
          id: commandId,
          exit_code: null,
          stdout: '',
          stderr: '',
          duration_ms: duration,
          cancelled: true
        };
      }
    } catch (error) {
      const duration = Date.now() - this.startTime;
      
      this.broadcastEvent({
        type: 'Failed',
        command_id: commandId,
        error: error.message,
        duration_ms: duration,
        timestamp: new Date().toISOString()
      });
      
      this.commandResult = {
        id: commandId,
        exit_code: -1,
        stdout: '',
        stderr: error.message,
        duration_ms: duration,
        cancelled: false
      };
    }
  }

  async simulateCommand(command) {
    // This is a simplified simulation
    // In production, this would execute in a secure sandbox
    
    const commands = {
      echo: () => ({
        stdout: command.args,
        stderr: [],
        exitCode: 0
      }),
      
      ls: () => ({
        stdout: ['file1.txt', 'file2.js', 'directory/', 'README.md'],
        stderr: [],
        exitCode: 0,
        progress: [[50, 'Listing files...']]
      }),
      
      cat: () => {
        if (command.stdin) {
          return {
            stdout: command.stdin.split('\n'),
            stderr: [],
            exitCode: 0
          };
        } else if (command.args.length > 0) {
          return {
            stdout: [`Contents of ${command.args[0]}`],
            stderr: [],
            exitCode: 0
          };
        } else {
          return {
            stdout: [],
            stderr: ['cat: missing file operand'],
            exitCode: 1
          };
        }
      },
      
      sleep: () => {
        const seconds = parseInt(command.args[0]) || 1;
        const progress = [];
        for (let i = 0; i < 10; i++) {
          progress.push([(i + 1) * 10, `Sleeping... ${(i + 1) * 10}%`]);
        }
        return {
          stdout: [],
          stderr: [],
          exitCode: 0,
          progress,
          duration: seconds * 1000
        };
      }
    };
    
    const executor = commands[command.command];
    if (executor) {
      const result = executor();
      
      // Simulate execution time
      if (result.duration) {
        await this.delay(result.duration);
      }
      
      return result;
    } else {
      return {
        stdout: [],
        stderr: [`${command.command}: command not found`],
        exitCode: 127
      };
    }
  }

  broadcastEvent(event) {
    this.eventHistory.push(event);
    
    const message = JSON.stringify({
      type: 'Event',
      event: event
    });
    
    // Send to all connected WebSockets
    this.websockets = this.websockets.filter(ws => {
      try {
        ws.send(message);
        return true;
      } catch (error) {
        // Remove closed connections
        return false;
      }
    });
  }

  delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
}