@aretaxia/sandbox-remote 0.0.0-stage → 0.1.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.
@@ -0,0 +1,38 @@
1
+ import { createHash, timingSafeEqual } from 'node:crypto';
2
+ import { readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
+
4
+ const idPattern = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
5
+ const digestPattern = /^[0-9a-f]{64}$/;
6
+ const cookiePrefix = 'sandbox_pilot=';
7
+ export const deviceDigest = (secret) => createHash('sha256').update(secret).digest('hex');
8
+
9
+ export function matchesDeviceCookie(cookie, digest) {
10
+ const token = cookie?.split(/;\s*/).find((item) => item.startsWith(cookiePrefix))?.slice(cookiePrefix.length);
11
+ return Boolean(token && /^[A-Za-z0-9_-]{43}$/.test(token) &&
12
+ timingSafeEqual(Buffer.from(deviceDigest(token), 'hex'), Buffer.from(digest, 'hex')));
13
+ }
14
+
15
+ export function loadDevice(path, origin, environmentId) {
16
+ let record;
17
+ try { record = JSON.parse(readFileSync(path, 'utf8')); }
18
+ catch (error) {
19
+ if (error.code === 'ENOENT') return;
20
+ throw new Error('The saved Sandbox phone record could not be read.');
21
+ }
22
+ if (record?.version !== 1 || record.origin !== origin || record.environmentId !== environmentId ||
23
+ typeof record.ownerId !== 'string' || !idPattern.test(record.ownerId) ||
24
+ typeof record.digest !== 'string' || !digestPattern.test(record.digest) ||
25
+ !Number.isSafeInteger(record.expiresAt) || record.expiresAt <= Date.now()) return;
26
+ return { ownerId: record.ownerId, environmentId, digest: record.digest, expiresAt: record.expiresAt, approved: true };
27
+ }
28
+
29
+ export function saveDevice(path, origin, device) {
30
+ const stage = path + '.' + process.pid + '.new';
31
+ try {
32
+ writeFileSync(stage, JSON.stringify({
33
+ version: 1, origin, environmentId: device.environmentId, ownerId: device.ownerId,
34
+ digest: device.digest, expiresAt: device.expiresAt,
35
+ }), { mode: 0o600, flag: 'wx' });
36
+ renameSync(stage, path);
37
+ } finally { rmSync(stage, { force: true }); }
38
+ }
@@ -0,0 +1,179 @@
1
+ import assert from 'node:assert/strict';
2
+ import { createServer } from 'node:http';
3
+ import WebSocket from 'ws';
4
+
5
+ const fixturePage = `<!doctype html><html lang="en"><meta charset="utf-8">
6
+ <meta name="viewport" content="width=device-width,initial-scale=1">
7
+ <title>Sandbox live preview test</title>
8
+ <style>
9
+ body{background:#14151a;color:#f2f3f5;font:17px/1.5 system-ui;margin:0;padding:28px 20px}
10
+ main{max-width:480px;margin:auto}h1{font-size:30px}button,input{font:inherit;padding:12px;border-radius:8px}
11
+ button{background:#ff737f;color:#14151a;border:0;font-weight:700}input{width:100%;box-sizing:border-box}
12
+ label{display:block;margin:20px 0}output{display:block;margin:12px 0;color:#b9f6cd}
13
+ </style>
14
+ <main><h1>Live from smac2</h1><p>This page is running on the Mac.</p><p id="clock" aria-label="Mac browser clock"></p>
15
+ <button id="hit">Test tap</button><output id="result">No taps yet</output>
16
+ <label>Test typing <input id="typing" autocomplete="off"></label><output id="typed"></output></main>
17
+ <script>
18
+ let count = 0;
19
+ const clock = document.getElementById('clock');
20
+ function tick(){clock.textContent = new Date().toLocaleTimeString()}
21
+ setInterval(tick, 1000);tick();
22
+ document.getElementById('hit').onclick = () => {
23
+ document.getElementById('result').textContent = 'Tap received on smac2 (' + ++count + ')';
24
+ void fetch('/tap', {method:'POST'});
25
+ };
26
+ document.getElementById('typing').oninput = (event) => {
27
+ document.getElementById('typed').textContent = event.target.value;
28
+ if (event.target.value.trim().toLowerCase() === 'sandbox') void fetch('/typed', {method:'POST'});
29
+ };
30
+ </script></html>`;
31
+
32
+ export async function startPilotPreview(chat, approvedUrl) {
33
+ const target = approvedUrl ? new URL(approvedUrl) : null;
34
+ if (target) {
35
+ assert(target.protocol === 'http:' && target.hostname === '127.0.0.1' &&
36
+ target.port && !target.username && !target.password && !target.hash, 'Use an approved loopback HTTP dev server URL');
37
+ }
38
+ const fixture = target ? null : createServer((request, response) => {
39
+ if (request.method === 'GET' && request.url === '/') {
40
+ response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' });
41
+ response.end(fixturePage);
42
+ } else if (request.method === 'POST' && ['/tap', '/typed'].includes(request.url)) {
43
+ console.log(request.url === '/tap'
44
+ ? 'Preview test page received a tap on smac2.'
45
+ : 'Preview test page received the test text on smac2.');
46
+ response.writeHead(204).end();
47
+ } else {
48
+ response.writeHead(404).end();
49
+ }
50
+ });
51
+ if (fixture) {
52
+ await new Promise((resolve, reject) => {
53
+ fixture.once('error', reject);
54
+ fixture.listen(0, '127.0.0.1', resolve);
55
+ });
56
+ }
57
+ const url = target?.href ?? 'http://127.0.0.1:' + fixture.address().port + '/';
58
+ const tabs = new Map();
59
+ const owners = new Map();
60
+ const closing = new Set();
61
+
62
+ function closeTab(threadId, tab) {
63
+ if (tab.closing) return tab.closing;
64
+ tab.closing = (async () => {
65
+ try {
66
+ const { tabId } = await tab.open;
67
+ await chat.previewCommand('close', { threadId, tabId }, () => true);
68
+ } finally {
69
+ if (tabs.get(threadId) === tab) tabs.delete(threadId);
70
+ }
71
+ })();
72
+ closing.add(tab.closing);
73
+ void tab.closing.finally(() => closing.delete(tab.closing)).catch(() => {});
74
+ return tab.closing;
75
+ }
76
+
77
+ async function command(action, data, paired, active) {
78
+ const { threadId } = data;
79
+ const tab = tabs.get(threadId);
80
+ if (action === 'open') {
81
+ assert.equal(data.url, url, 'Preview target is outside the pilot');
82
+ if (tab?.closing) await tab.closing.catch(() => {});
83
+ assert(active(), 'Pairing revoked');
84
+ const current = tabs.get(threadId);
85
+ if (current) {
86
+ assert.equal(current.paired, paired, 'Preview belongs to a different pairing');
87
+ return { tabId: (await current.open).tabId };
88
+ }
89
+ const dimension = (value, max, fallback) =>
90
+ Number.isInteger(value) ? Math.max(240, Math.min(max, value)) : fallback;
91
+ const viewport = { _tag: 'freeform',
92
+ width: dimension(data.viewport?.width, 1024, 390),
93
+ height: dimension(data.viewport?.height, 768, 690) };
94
+ const next = { paired, open: chat.previewCommand('open',
95
+ { threadId, url, viewport, runtime: 'server', reveal: false }, active) };
96
+ tabs.set(threadId, next);
97
+ try {
98
+ const opened = await next.open;
99
+ assert(opened?.threadId === threadId && typeof opened.tabId === 'string', 'Invalid preview tab');
100
+ next.id = opened.tabId;
101
+ return { tabId: next.id };
102
+ } catch (error) {
103
+ if (tabs.get(threadId) === next) tabs.delete(threadId);
104
+ throw error;
105
+ }
106
+ }
107
+ assert(tab?.paired === paired && tab.id === data.tabId && !tab.closing && active(), 'Unknown preview tab');
108
+ if (action === 'close') await closeTab(threadId, tab);
109
+ else await chat.previewCommand('adjust', { threadId, tabId: tab.id, hardReload: true }, active);
110
+ return { accepted: true };
111
+ }
112
+
113
+ function authorize(threadId, tabId, paired) {
114
+ const tab = tabs.get(threadId);
115
+ return tab?.paired === paired && tab.id === tabId && !tab.closing;
116
+ }
117
+
118
+ async function bridge(phone, threadId, tabId, interactive, active) {
119
+ const current = owners.get(tabId) ?? new Set();
120
+ if (current.size >= 2) {
121
+ phone.close(1008, 'Preview already open');
122
+ return;
123
+ }
124
+ current.add(phone);
125
+ owners.set(tabId, current);
126
+ let upstream;
127
+ let alive = true;
128
+ let firstFrame = false;
129
+ let acknowledged = false;
130
+ const heartbeat = setInterval(() => {
131
+ if (!alive || !active() || phone.bufferedAmount > 2 * 1024 * 1024) { phone.terminate(); return; }
132
+ alive = false;
133
+ phone.ping();
134
+ if (upstream?.readyState === WebSocket.OPEN) phone.send('{"type":"sandboxHeartbeat"}');
135
+ }, 5_000);
136
+ phone.on('pong', () => { alive = true; });
137
+ phone.once('close', () => {
138
+ clearInterval(heartbeat);
139
+ upstream?.terminate();
140
+ current.delete(phone);
141
+ if (!current.size) owners.delete(tabId);
142
+ });
143
+ phone.on('error', () => phone.terminate());
144
+ try {
145
+ upstream = await chat.previewStream(threadId, tabId, interactive, active);
146
+ if (!active() || phone.readyState !== WebSocket.OPEN) { upstream.terminate(); return; }
147
+ upstream.once('close', () => phone.close(1011, 'Mac preview stream closed'));
148
+ upstream.on('message', (data, isBinary) => {
149
+ if (!active() || phone.readyState !== WebSocket.OPEN) return;
150
+ if (phone.bufferedAmount > 2 * 1024 * 1024) { phone.terminate(); return; }
151
+ if (isBinary) firstFrame = true;
152
+ phone.send(data, { binary: isBinary });
153
+ });
154
+ phone.on('message', (data, isBinary) => {
155
+ if (isBinary || !active() || upstream.readyState !== WebSocket.OPEN) return;
156
+ if (upstream.bufferedAmount > 32 * 1024) { phone.terminate(); return; }
157
+ upstream.send(data, { binary: false });
158
+ if (!acknowledged && firstFrame && data.toString() === '{"type":"ack"}') {
159
+ acknowledged = true;
160
+ console.log('Phone acknowledged a live preview frame (' + (interactive ? 'interactive' : 'passive') + ').');
161
+ }
162
+ });
163
+ } catch {
164
+ phone.close(1011, 'Mac preview unavailable');
165
+ }
166
+ }
167
+
168
+ function revoke() {
169
+ for (const [threadId, tab] of tabs) void closeTab(threadId, tab).catch(() => {});
170
+ }
171
+
172
+ async function close() {
173
+ fixture?.close();
174
+ revoke();
175
+ await Promise.allSettled(closing);
176
+ }
177
+
178
+ return { url, command, authorize, bridge, revoke, close };
179
+ }
@@ -0,0 +1,364 @@
1
+ import assert from 'node:assert/strict';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { readFileSync, writeFileSync } from 'node:fs';
4
+ import WebSocket from 'ws';
5
+ import { runT3Cli } from './sandbox-remote-t3-cli.mjs';
6
+
7
+ const base = 'http://127.0.0.1:3773';
8
+ const protocol = '2';
9
+
10
+ function threadTimestamp(thread) {
11
+ const iso = thread?.updatedAt ?? thread?.createdAt ?? '';
12
+ const ms = Date.parse(typeof iso === 'string' ? iso : '');
13
+ return Number.isFinite(ms) ? ms : 0;
14
+ }
15
+
16
+ function selectThreadByTitle(allThreads, title) {
17
+ const active = allThreads.filter((thread) => !thread.deletedAt);
18
+ const exact = active.filter((thread) => thread.title === title);
19
+ const candidates = exact.length
20
+ ? exact
21
+ : active.filter((thread) => typeof thread.title === 'string' &&
22
+ thread.title.trim().toLowerCase() === title.trim().toLowerCase());
23
+ assert(candidates.length > 0, `Could not find a T3 thread matching "${title}" (${active.length} active thread(s) found).`);
24
+ const nonArchived = candidates.filter((thread) => !thread.archivedAt);
25
+ const pool = nonArchived.length ? nonArchived : candidates;
26
+ return [...pool].sort((left, right) => threadTimestamp(right) - threadTimestamp(left))[0];
27
+ }
28
+
29
+ export async function openPilotChat(
30
+ threadTitle,
31
+ expectedEnvironmentId,
32
+ extraTitles = [],
33
+ { preview = false, sessionPath, threadId: explicitThreadId } = {},
34
+ ) {
35
+ const label = sessionPath ? 'Aretaxia Sandbox · Remote Access' : 'Sandbox cellular chat pilot ' + randomUUID();
36
+ const scopes = ['orchestration:read', 'orchestration:operate'];
37
+ if (preview) scopes.push('preview:operate');
38
+ const scopedByTarget = Boolean(threadTitle || explicitThreadId || extraTitles.length);
39
+ let token;
40
+ let closed = false;
41
+ let revoked = false;
42
+ let checkSession;
43
+ const sockets = new Set();
44
+ const submissions = new Map();
45
+
46
+ const cli = (...args) => runT3Cli(process.env.SANDBOX_T3_EXECUTABLE || 't3', args);
47
+ async function json(path, options = {}) {
48
+ assert(!revoked, 'T3 revoked Sandbox access. Run setup:remote -- reauthorize to restore access.');
49
+ const response = await fetch(base + path, {
50
+ ...options,
51
+ headers: {
52
+ ...(token ? { Authorization: 'Bearer ' + token } : {}),
53
+ 'x-t3-orchestration-protocol': protocol,
54
+ },
55
+ signal: AbortSignal.timeout(8000),
56
+ });
57
+ assert(response.ok, 'Local T3 returned HTTP ' + response.status);
58
+ return response.json();
59
+ }
60
+
61
+ async function close() {
62
+ if (closed) return;
63
+ closed = true;
64
+ clearInterval(checkSession);
65
+ for (const ws of sockets) ws.terminate();
66
+ if (!token || sessionPath) return;
67
+ const owned = JSON.parse(cli('auth', 'session', 'list', '--json')).filter((entry) => entry.client?.label === label);
68
+ assert.equal(owned.length, 1, 'Could not identify the pilot T3 session to revoke');
69
+ cli('auth', 'session', 'revoke', owned[0].sessionId);
70
+ assert.equal((await json('/api/auth/session')).authenticated, false);
71
+ console.log('Revoked the temporary local T3 chat session.');
72
+ }
73
+
74
+ async function connect(onFrame) {
75
+ const { ticket } = await json('/api/auth/websocket-ticket/rpc', { method: 'POST' });
76
+ assert(ticket && !closed, 'Could not open a local T3 socket');
77
+ const params = new URLSearchParams({ orchestrationProtocol: protocol, wsTicket: ticket });
78
+ const ws = new WebSocket('ws://127.0.0.1:3773/ws?' + params);
79
+ sockets.add(ws);
80
+ ws.once('close', () => sockets.delete(ws));
81
+ ws.on('error', () => ws.terminate());
82
+ ws.on('message', (raw) => {
83
+ try {
84
+ const data = JSON.parse(raw.toString());
85
+ for (const frame of Array.isArray(data) ? data : [data]) onFrame(frame, ws);
86
+ } catch {
87
+ ws.terminate();
88
+ }
89
+ });
90
+ return ws;
91
+ }
92
+
93
+ function request(ws, id, tag, payload) {
94
+ const send = () => ws.send(JSON.stringify({
95
+ _tag: 'Request', id, tag, payload, headers: [['x-t3-orchestration-protocol', protocol]],
96
+ }));
97
+ if (ws.readyState === WebSocket.OPEN) send();
98
+ else ws.once('open', send);
99
+ }
100
+
101
+ try {
102
+ const environment = await json('/.well-known/t3/environment');
103
+ assert.equal(environment.environmentId, expectedEnvironmentId, 'Unexpected T3 environment');
104
+ let saved;
105
+ if (sessionPath) {
106
+ try { saved = JSON.parse(readFileSync(sessionPath, 'utf8')); }
107
+ catch (error) { if (error.code !== 'ENOENT') throw new Error('Could not read the saved Sandbox authorization.'); }
108
+ }
109
+ if (saved) {
110
+ assert(saved.environmentId === expectedEnvironmentId &&
111
+ JSON.stringify(saved.scopes) === JSON.stringify(scopes) && typeof saved.token === 'string' && saved.token,
112
+ 'Sandbox authorization changed. Run setup:remote -- reauthorize.');
113
+ token = saved.token;
114
+ assert((await json('/api/auth/session')).authenticated,
115
+ 'T3 no longer authorizes Sandbox. Run setup:remote -- reauthorize to restore access.');
116
+ } else {
117
+ const grant = JSON.parse(cli('auth', 'pairing', 'create', ...scopes.flatMap((scope) => ['--scope', scope]),
118
+ '--ttl', '5m', '--label', label, '--json'));
119
+ const auth = await json('/oauth/token', { method: 'POST', body: new URLSearchParams({
120
+ grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',
121
+ subject_token: grant.credential,
122
+ subject_token_type: 'urn:t3:params:oauth:token-type:environment-bootstrap',
123
+ requested_token_type: 'urn:ietf:params:oauth:token-type:access_token',
124
+ scope: scopes.join(' '), client_label: label,
125
+ }) });
126
+ token = auth.access_token;
127
+ assert(typeof token === 'string' && token, 'Local T3 did not issue a session');
128
+ assert.deepEqual(auth.scope.split(/\s+/).sort(), [...scopes].sort());
129
+ if (sessionPath) {
130
+ const session = await json('/api/auth/session');
131
+ assert(session.authenticated, 'Could not verify Sandbox authorization.');
132
+ const owned = JSON.parse(cli('auth', 'session', 'list', '--json')).filter((entry) => entry.client?.label === label);
133
+ assert.equal(owned.length, 1, 'Expected one named Sandbox session.');
134
+ writeFileSync(sessionPath, JSON.stringify({ token, scopes, environmentId: expectedEnvironmentId,
135
+ sessionId: owned[0].sessionId }), { mode: 0o600, flag: 'wx' });
136
+ }
137
+ }
138
+
139
+ const shell = await json('/api/orchestration/shell');
140
+ const allThreads = shell.threads ?? shell.snapshot?.threads ?? [];
141
+ let threads = [];
142
+ if (scopedByTarget) {
143
+ const selected = [];
144
+ if (explicitThreadId) {
145
+ const match = allThreads.find((item) => item.id === explicitThreadId && !item.deletedAt);
146
+ assert(match, `Could not find T3 thread ${explicitThreadId}.`);
147
+ selected.push(match);
148
+ }
149
+ for (const title of [threadTitle, ...extraTitles].filter(Boolean)) {
150
+ const match = selectThreadByTitle(allThreads, title);
151
+ if (!selected.some((item) => item.id === match.id)) selected.push(match);
152
+ }
153
+ threads = selected;
154
+ } else {
155
+ threads = allThreads
156
+ .filter((thread) => !thread.deletedAt)
157
+ .sort((left, right) => threadTimestamp(right) - threadTimestamp(left));
158
+ }
159
+
160
+ const defaultThreadId = threads[0]?.id ?? null;
161
+ const defaultTitle = threads[0]?.title ?? threadTitle ?? 'No threads yet';
162
+
163
+ function verifyThread(targetId) {
164
+ assert(threads.some((thread) => thread.id === targetId), 'Thread is outside the pilot');
165
+ }
166
+
167
+ async function ensureThreadAllowed(targetId) {
168
+ if (threads.some((thread) => thread.id === targetId)) return;
169
+ if (!scopedByTarget) {
170
+ const fresh = await json('/api/orchestration/shell');
171
+ threads = (fresh.threads ?? fresh.snapshot?.threads ?? [])
172
+ .filter((thread) => !thread.deletedAt)
173
+ .sort((left, right) => threadTimestamp(right) - threadTimestamp(left));
174
+ }
175
+ verifyThread(targetId);
176
+ }
177
+
178
+ async function getThread(targetId) {
179
+ await ensureThreadAllowed(targetId);
180
+ return json('/api/orchestration/threads/' + encodeURIComponent(targetId));
181
+ }
182
+
183
+ async function getShell() {
184
+ const fresh = await json('/api/orchestration/shell');
185
+ const freshThreads = (fresh.threads ?? fresh.snapshot?.threads ?? []).filter((thread) => !thread.deletedAt);
186
+ const freshProjects = fresh.projects ?? fresh.snapshot?.projects ?? [];
187
+ if (!scopedByTarget) {
188
+ threads = [...freshThreads].sort((left, right) => threadTimestamp(right) - threadTimestamp(left));
189
+ return { projects: freshProjects, threads };
190
+ }
191
+ return {
192
+ projects: freshProjects.filter((project) =>
193
+ threads.some((thread) => thread.projectId === project.id)),
194
+ threads: freshThreads.filter((thread) =>
195
+ threads.some((allowed) => allowed.id === thread.id)),
196
+ };
197
+ }
198
+
199
+ async function snapshot(targetId = defaultThreadId) {
200
+ if (!targetId) {
201
+ return { type: 'chat', title: defaultTitle, messages: [] };
202
+ }
203
+ const raw = await getThread(targetId);
204
+ const messages = raw.projection?.messages ?? raw.messages ?? [];
205
+ return {
206
+ type: 'chat', title: raw.thread?.title ?? defaultTitle,
207
+ messages: messages.slice(-24).flatMap((message) => {
208
+ const text = message.text ?? message.content;
209
+ return typeof text === 'string' && ['user', 'assistant'].includes(message.role)
210
+ ? [{ role: message.role, text: text.slice(-6000) }]
211
+ : [];
212
+ }),
213
+ };
214
+ }
215
+
216
+ async function watch(onUpdate, onUnavailable, targetId = defaultThreadId, eventsOnly = false) {
217
+ if (!targetId) {
218
+ onUpdate({ type: 'chat', title: defaultTitle, messages: [] });
219
+ return () => {};
220
+ }
221
+ await ensureThreadAllowed(targetId);
222
+ const id = randomUUID();
223
+ let timer;
224
+ let loading = false;
225
+ let dirty = false;
226
+ let stopped = false;
227
+ function refresh() {
228
+ dirty = true;
229
+ if (timer || loading || stopped) return;
230
+ timer = setTimeout(async () => {
231
+ timer = undefined;
232
+ loading = true;
233
+ dirty = false;
234
+ try {
235
+ const state = eventsOnly ? { type: 'changed' } : await snapshot(targetId);
236
+ if (!stopped) onUpdate(state);
237
+ } catch {
238
+ if (!stopped) onUnavailable();
239
+ } finally {
240
+ loading = false;
241
+ if (dirty) refresh();
242
+ }
243
+ }, 150);
244
+ }
245
+ const ws = await connect((frame, socket) => {
246
+ if (String(frame.requestId ?? frame.id) !== id || frame._tag !== 'Chunk') return;
247
+ socket.send(JSON.stringify({ _tag: 'Ack', requestId: id }));
248
+ refresh();
249
+ });
250
+ ws.once('close', () => { if (!stopped) onUnavailable(); });
251
+ request(ws, id, 'orchestration.subscribeThread', { threadId: targetId });
252
+ refresh();
253
+ return () => { stopped = true; clearTimeout(timer); ws.close(); };
254
+ }
255
+
256
+ async function watchShell(onUpdate, onUnavailable) {
257
+ const id = randomUUID();
258
+ let stopped = false;
259
+ const ws = await connect((frame, socket) => {
260
+ if (String(frame.requestId ?? frame.id) !== id || frame._tag !== 'Chunk') return;
261
+ socket.send(JSON.stringify({ _tag: 'Ack', requestId: id }));
262
+ if (!stopped) onUpdate();
263
+ });
264
+ ws.once('close', () => { if (!stopped) onUnavailable(); });
265
+ request(ws, id, 'orchestration.subscribeShell', {});
266
+ return () => { stopped = true; ws.close(); };
267
+ }
268
+
269
+ async function rpc(tag, payload, isAuthorized) {
270
+ const requestId = randomUUID();
271
+ let resolveReply;
272
+ let rejectReply;
273
+ const reply = new Promise((resolve, reject) => { resolveReply = resolve; rejectReply = reject; });
274
+ const socket = await connect((frame) => {
275
+ if (frame._tag !== 'Exit' || String(frame.requestId ?? frame.id) !== requestId) return;
276
+ if (frame.exit?._tag === 'Success') resolveReply(frame.exit.value);
277
+ else rejectReply(new Error('T3 rejected the command'));
278
+ });
279
+ const timeout = setTimeout(() => rejectReply(new Error('Delivery could not be confirmed')), 8000);
280
+ socket.once('close', () => rejectReply(new Error('Delivery could not be confirmed')));
281
+ try {
282
+ const send = () => {
283
+ if (!isAuthorized()) { rejectReply(new Error('Pairing revoked')); return; }
284
+ request(socket, requestId, tag, payload);
285
+ };
286
+ if (socket.readyState === WebSocket.OPEN) send();
287
+ else socket.once('open', send);
288
+ return await reply;
289
+ } finally {
290
+ clearTimeout(timeout);
291
+ socket.close();
292
+ }
293
+ }
294
+
295
+ const dispatch = (payload, isAuthorized) => rpc('orchestration.dispatchCommand', payload, isAuthorized);
296
+
297
+ async function sendMessage(messageId, text, isAuthorized, targetId = defaultThreadId, mode = 'auto') {
298
+ assert(targetId, 'No T3 thread is selected');
299
+ await ensureThreadAllowed(targetId);
300
+ const key = targetId + ':' + messageId;
301
+ if (submissions.has(key)) return submissions.get(key);
302
+ assert(submissions.size < 32, 'Pilot message limit reached');
303
+ const result = dispatch({
304
+ type: 'message.dispatch', commandId: randomUUID(), messageId, threadId: targetId, text,
305
+ attachments: [], deliveryIntent: 'auto',
306
+ dispatchMode: { type: mode === 'queue' ? 'queue_after_active' : 'start_immediately' },
307
+ createdBy: 'user', creationSource: 'web',
308
+ }, isAuthorized);
309
+ submissions.set(key, result);
310
+ return result;
311
+ }
312
+
313
+ async function stopThread(targetId, isAuthorized) {
314
+ const raw = await getThread(targetId);
315
+ const runs = raw.projection?.runs ?? raw.runs ?? [];
316
+ const active = runs.filter((run) => ['preparing', 'starting', 'running', 'waiting'].includes(run.status));
317
+ assert.equal(active.length, 1, 'Expected one active run on the pilot thread');
318
+ await dispatch({ type: 'run.interrupt', commandId: randomUUID(), threadId: targetId, runId: active[0].id }, isAuthorized);
319
+ }
320
+
321
+ async function previewCommand(action, payload, isAuthorized) {
322
+ assert(preview && ['open', 'adjust', 'close'].includes(action), 'Preview operation unavailable');
323
+ await ensureThreadAllowed(payload.threadId);
324
+ return rpc('preview.' + action, payload, isAuthorized);
325
+ }
326
+
327
+ async function previewStream(targetId, tabId, interactive, isAuthorized) {
328
+ assert(preview, 'Preview is unavailable');
329
+ await ensureThreadAllowed(targetId);
330
+ const { ticket } = await json('/api/auth/websocket-ticket/media', { method: 'POST' });
331
+ assert(ticket && !closed && isAuthorized(), 'Could not open a local preview stream');
332
+ const params = new URLSearchParams({ threadId: targetId, tabId, wsTicket: ticket, maxWidth: '1024', maxHeight: '768' });
333
+ if (!interactive) params.set('interactive', 'false');
334
+ const ws = new WebSocket('ws://127.0.0.1:3773/api/preview-stream/ws?' + params, {
335
+ maxPayload: 2 * 1024 * 1024, perMessageDeflate: false,
336
+ });
337
+ sockets.add(ws);
338
+ ws.once('close', () => sockets.delete(ws));
339
+ ws.on('error', () => ws.terminate());
340
+ return ws;
341
+ }
342
+
343
+ if (sessionPath) {
344
+ checkSession = setInterval(() => {
345
+ void json('/api/auth/session').then((session) => {
346
+ if (!session.authenticated) {
347
+ revoked = true;
348
+ console.log('T3 revoked Aretaxia Sandbox remote access.');
349
+ void close();
350
+ }
351
+ }).catch(() => {});
352
+ }, 5000);
353
+ checkSession.unref();
354
+ }
355
+ return {
356
+ snapshot, watch, watchShell, sendMessage, stopThread, getShell, getThread, previewCommand, previewStream,
357
+ get threadIds() { return threads.map((thread) => thread.id); },
358
+ close,
359
+ };
360
+ } catch (error) {
361
+ await close();
362
+ throw error;
363
+ }
364
+ }
@@ -0,0 +1,33 @@
1
+ import assert from 'node:assert/strict';
2
+ import { execFileSync } from 'node:child_process';
3
+ import { extname } from 'node:path';
4
+
5
+ export function findWindowsT3() {
6
+ for (const name of ['t3.exe', 't3.cmd']) {
7
+ try {
8
+ const [path] = execFileSync('where.exe', [name], {
9
+ encoding: 'utf8', windowsHide: true, timeout: 5000,
10
+ }).trim().split(/\r?\n/);
11
+ if (path) return path;
12
+ } catch (error) {
13
+ if (error.status !== 1) throw error;
14
+ }
15
+ }
16
+ throw new Error('T3 Code CLI is missing. Install it from T3 Code and try again.');
17
+ }
18
+
19
+ export function runT3Cli(executable, args) {
20
+ const options = {
21
+ encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 12_000, windowsHide: true,
22
+ };
23
+ if (process.platform !== 'win32' || extname(executable).toLowerCase() !== '.cmd') {
24
+ return execFileSync(executable, args, options);
25
+ }
26
+ // Windows CMD shims require a command interpreter. Keep all values literal.
27
+ assert(!/["%!&|<>^\r\n]/.test(executable) &&
28
+ args.every((arg) => /^[\p{L}\p{N} .:·_-]+$/u.test(arg)), 'Invalid T3 CLI path or argument');
29
+ const command = [executable, ...args].map((value) => '"' + value + '"').join(' ');
30
+ return execFileSync('cmd.exe', ['/d', '/v:off', '/s', '/c', '"' + command + '"'], {
31
+ ...options, windowsVerbatimArguments: true,
32
+ });
33
+ }
@@ -0,0 +1,55 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { readFileSync } from 'node:fs';
3
+
4
+ const powershell = 'powershell.exe';
5
+ function command(script) {
6
+ return execFileSync(powershell, ['-NoProfile', '-NonInteractive', '-EncodedCommand',
7
+ Buffer.from("$ErrorActionPreference = 'Stop'; " + script, 'utf16le').toString('base64')],
8
+ { encoding: 'utf8', windowsHide: true, timeout: 20_000 }).trim();
9
+ }
10
+
11
+ const literal = (value) => "'" + value.replaceAll("'", "''") + "'";
12
+ const identity = '$identity = [Security.Principal.WindowsIdentity]::GetCurrent(); ';
13
+ const taskName = "$name = 'Aretaxia Sandbox Remote Access ' + $identity.User.Value; ";
14
+ const taskCommand = (script) => command(identity + taskName + script);
15
+
16
+ export function installWindowsTask(configPath, workingDirectory) {
17
+ // Only these two paths are embedded in the task. Runtime arguments are in JSON.
18
+ const script = [
19
+ '$config = Get-Content -LiteralPath ' + literal(configPath) + ' -Encoding UTF8 -Raw | ConvertFrom-Json',
20
+ 'foreach ($setting in $config.environment.PSObject.Properties) { [Environment]::SetEnvironmentVariable($setting.Name, [string]$setting.Value) }',
21
+ '$arguments = @($config.arguments)',
22
+ '& $config.node @arguments *>> $config.log',
23
+ 'exit $LASTEXITCODE',
24
+ ].join('; ');
25
+ const encoded = Buffer.from(script, 'utf16le').toString('base64');
26
+ taskCommand([
27
+ '$action = New-ScheduledTaskAction -Execute (Join-Path $PSHOME "powershell.exe") -Argument ' +
28
+ literal('-NoProfile -NonInteractive -WindowStyle Hidden -EncodedCommand ' + encoded) +
29
+ ' -WorkingDirectory ' + literal(workingDirectory),
30
+ '$trigger = New-ScheduledTaskTrigger -AtLogOn -User $identity.Name',
31
+ '$principal = New-ScheduledTaskPrincipal -UserId $identity.Name -LogonType Interactive -RunLevel Limited',
32
+ '$settings = New-ScheduledTaskSettingsSet -MultipleInstances IgnoreNew -ExecutionTimeLimit ([TimeSpan]::Zero) -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 1) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries',
33
+ 'Register-ScheduledTask -TaskName $name -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Force | Out-Null',
34
+ ].join('; '));
35
+ }
36
+
37
+ export function windowsTaskRunning() {
38
+ return taskCommand("(Get-ScheduledTask -TaskName $name -ErrorAction SilentlyContinue).State") === 'Running';
39
+ }
40
+
41
+ export function startWindowsTask() {
42
+ taskCommand('Start-ScheduledTask -TaskName $name');
43
+ }
44
+
45
+ export function removeWindowsTask() {
46
+ taskCommand('if (Get-ScheduledTask -TaskName $name -ErrorAction SilentlyContinue) { Unregister-ScheduledTask -TaskName $name -Confirm:$false }');
47
+ }
48
+
49
+ export function readWindowsTaskOptions(configPath) {
50
+ return JSON.parse(readFileSync(configPath, 'utf8')).arguments.slice(2);
51
+ }
52
+
53
+ export function openWindowsUrl(url) {
54
+ command('Start-Process ' + literal(url));
55
+ }