tacticremote 1.7.0 → 1.8.2
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/LICENSE +28 -0
- package/README.md +32 -41
- package/bin/tacticremote.js +51 -99
- package/package.json +29 -42
- package/bin/tactic-remote-server.js +0 -636
- package/lib/authChallengeManager.js +0 -1
- package/lib/bonjourPublisher.js +0 -68
- package/lib/claudeSessionManager.js +0 -1
- package/lib/claudeTransport.js +0 -1
- package/lib/errorCodes.js +0 -1
- package/lib/execSafe.js +0 -1
- package/lib/fileService.js +0 -1
- package/lib/hookInstaller.js +0 -253
- package/lib/outputParser.js +0 -1
- package/lib/pushClient.js +0 -1
- package/lib/rateLimiter.js +0 -1
- package/lib/serverIdentity.js +0 -1
- package/lib/streamJsonParser.js +0 -1
- package/lib/tmuxManager.js +0 -1
- package/lib/uploadService.js +0 -1
- package/lib/validators.js +0 -1
- package/middleware/authMiddleware.js +0 -152
- package/routes/httpHandler.js +0 -111
- package/routes/wsHandler.js +0 -1094
- package/server.js +0 -236
- package/shared/server-core/authChallengeManager.js +0 -108
- package/shared/server-core/claudeSessionManager.js +0 -222
- package/shared/server-core/claudeTransport.js +0 -176
- package/shared/server-core/errorCodes.js +0 -91
- package/shared/server-core/execSafe.js +0 -185
- package/shared/server-core/fileService.js +0 -155
- package/shared/server-core/outputParser.js +0 -174
- package/shared/server-core/protocol-manifest.json +0 -59
- package/shared/server-core/protocol-manifest.schema.json +0 -90
- package/shared/server-core/protocolManifest.js +0 -42
- package/shared/server-core/pushClient.js +0 -198
- package/shared/server-core/rateLimiter.js +0 -98
- package/shared/server-core/serverConnectionLifecycle.js +0 -118
- package/shared/server-core/serverHandshake.js +0 -72
- package/shared/server-core/serverIdentity.js +0 -102
- package/shared/server-core/streamJsonParser.js +0 -321
- package/shared/server-core/tmuxManager.js +0 -596
- package/shared/server-core/unixProcessLifecycle.js +0 -96
- package/shared/server-core/unixServerHooks.js +0 -148
- package/shared/server-core/unixWsRuntime.js +0 -412
- package/shared/server-core/uploadService.js +0 -321
- package/shared/server-core/validators.js +0 -274
- package/shared/server-core/windowsServerHooks.js +0 -174
- package/shared/server-core/windowsWsRuntime.js +0 -413
|
@@ -1,118 +0,0 @@
|
|
|
1
|
-
function emitClientCount(server) {
|
|
2
|
-
console.log(`__CLIENT_COUNT__:${server.externalClients.size}:${server.clients.size}`);
|
|
3
|
-
}
|
|
4
|
-
|
|
5
|
-
function handleServerConnection(server, ws, req, options) {
|
|
6
|
-
const {
|
|
7
|
-
checkWsAuth,
|
|
8
|
-
generateClientId,
|
|
9
|
-
buildConnectedPayload
|
|
10
|
-
} = options;
|
|
11
|
-
|
|
12
|
-
const clientIP = req.socket.remoteAddress || 'unknown';
|
|
13
|
-
const isInternal = clientIP === '127.0.0.1' || clientIP === '::1' || clientIP === '::ffff:127.0.0.1';
|
|
14
|
-
|
|
15
|
-
if (server.apiKey) {
|
|
16
|
-
const authResult = checkWsAuth(req, server.apiKey, clientIP);
|
|
17
|
-
if (!authResult.authenticated) {
|
|
18
|
-
const msg = authResult.rateLimited ? 'Too many failed attempts' : 'Unauthorized';
|
|
19
|
-
console.log(`🔒 ${msg} from ${clientIP}`);
|
|
20
|
-
ws.close(1008, msg);
|
|
21
|
-
return;
|
|
22
|
-
}
|
|
23
|
-
console.log(`🔓 Authenticated connection from ${clientIP}`);
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
const clientId = generateClientId();
|
|
27
|
-
server.clients.set(clientId, ws);
|
|
28
|
-
if (!isInternal) {
|
|
29
|
-
server.externalClients.set(clientId, ws);
|
|
30
|
-
}
|
|
31
|
-
ws._clientId = clientId;
|
|
32
|
-
ws._isInternal = isInternal;
|
|
33
|
-
|
|
34
|
-
server.clientState.set(clientId, {
|
|
35
|
-
currentPath: server.currentPath,
|
|
36
|
-
currentSession: null,
|
|
37
|
-
foreground: false,
|
|
38
|
-
supportsClientState: false
|
|
39
|
-
});
|
|
40
|
-
|
|
41
|
-
console.log(`✅ ${isInternal ? 'Internal' : 'iOS'} client connected: ${clientId} (${clientIP})`);
|
|
42
|
-
server.emitClientCount?.();
|
|
43
|
-
|
|
44
|
-
ws.isAlive = true;
|
|
45
|
-
ws.on('pong', () => { ws.isAlive = true; });
|
|
46
|
-
|
|
47
|
-
const clientState = server.clientState.get(clientId);
|
|
48
|
-
server.wsHandler.sendToClient(ws, buildConnectedPayload({
|
|
49
|
-
server,
|
|
50
|
-
ws,
|
|
51
|
-
clientId,
|
|
52
|
-
clientIP,
|
|
53
|
-
isInternal,
|
|
54
|
-
clientState
|
|
55
|
-
}));
|
|
56
|
-
|
|
57
|
-
ws.on('message', (data) => {
|
|
58
|
-
try {
|
|
59
|
-
const message = JSON.parse(data.toString());
|
|
60
|
-
server.wsHandler.handleMessage(ws, message);
|
|
61
|
-
} catch (error) {
|
|
62
|
-
console.error('Failed to parse message:', error);
|
|
63
|
-
}
|
|
64
|
-
});
|
|
65
|
-
|
|
66
|
-
let connectionCleaned = false;
|
|
67
|
-
const cleanupConnection = (reason) => {
|
|
68
|
-
if (connectionCleaned) return;
|
|
69
|
-
connectionCleaned = true;
|
|
70
|
-
server.clients.delete(clientId);
|
|
71
|
-
server.externalClients.delete(clientId);
|
|
72
|
-
server.clientState.delete(clientId);
|
|
73
|
-
if (server.wsHandler.cleanupClient) server.wsHandler.cleanupClient(ws);
|
|
74
|
-
if (reason === 'close') {
|
|
75
|
-
console.log(`❌ ${isInternal ? 'Internal' : 'iOS'} client disconnected: ${clientId}`);
|
|
76
|
-
}
|
|
77
|
-
server.emitClientCount?.();
|
|
78
|
-
};
|
|
79
|
-
|
|
80
|
-
ws.on('close', () => cleanupConnection('close'));
|
|
81
|
-
ws.on('error', (error) => {
|
|
82
|
-
console.error(`WebSocket error (${clientId}):`, error.message);
|
|
83
|
-
cleanupConnection('error');
|
|
84
|
-
});
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
function startServerHeartbeat(server, options = {}) {
|
|
88
|
-
const {
|
|
89
|
-
intervalMs = 45000
|
|
90
|
-
} = options;
|
|
91
|
-
|
|
92
|
-
server.heartbeatInterval = setInterval(() => {
|
|
93
|
-
server.wss.clients.forEach((ws) => {
|
|
94
|
-
if (ws.isAlive === false) {
|
|
95
|
-
if (ws.missedHeartbeats === undefined) {
|
|
96
|
-
ws.missedHeartbeats = 0;
|
|
97
|
-
}
|
|
98
|
-
ws.missedHeartbeats++;
|
|
99
|
-
if (ws.missedHeartbeats >= 2) {
|
|
100
|
-
console.log(`💔 Client heartbeat timeout, terminating (${ws._clientId || 'unknown'})`);
|
|
101
|
-
return ws.terminate();
|
|
102
|
-
}
|
|
103
|
-
} else {
|
|
104
|
-
ws.missedHeartbeats = 0;
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
ws.isAlive = false;
|
|
108
|
-
ws.ping();
|
|
109
|
-
server.wsHandler.sendToClient(ws, { type: 'ping', timestamp: Date.now() });
|
|
110
|
-
});
|
|
111
|
-
}, intervalMs);
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
module.exports = {
|
|
115
|
-
emitClientCount,
|
|
116
|
-
handleServerConnection,
|
|
117
|
-
startServerHeartbeat
|
|
118
|
-
};
|
|
@@ -1,72 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Builds the `server` object for the `connected` handshake message, shared
|
|
3
|
-
* across all server variants so clients see a uniform shape regardless of
|
|
4
|
-
* whether they connect to a MacServer, LinuxServer, Windows, iOS-embedded
|
|
5
|
-
* Mac server, or npm `tacticremote` package.
|
|
6
|
-
*
|
|
7
|
-
* Clients (iOS) are NOT required to consume this object. Old clients that
|
|
8
|
-
* ignore it still work — the existing `capabilities` array remains
|
|
9
|
-
* authoritative for feature decisions. The `server` object adds:
|
|
10
|
-
* - appVersion: SemVer string from the variant's own package.json
|
|
11
|
-
* - protocolVersion: integer from the protocol manifest
|
|
12
|
-
* - platform: shipping-unit identifier (see VALID_PLATFORMS)
|
|
13
|
-
* - minimumSupportedClientProtocolVersion: server's floor for client proto
|
|
14
|
-
*
|
|
15
|
-
* @see shared/server-core/protocol-manifest.json
|
|
16
|
-
*/
|
|
17
|
-
|
|
18
|
-
const {
|
|
19
|
-
PROTOCOL_VERSION,
|
|
20
|
-
MINIMUM_SUPPORTED_CLIENT_PROTOCOL_VERSION
|
|
21
|
-
} = require('./protocolManifest');
|
|
22
|
-
|
|
23
|
-
const VALID_PLATFORMS = Object.freeze([
|
|
24
|
-
'mac-standalone', // MacServer/ (dev mode, future Homebrew install)
|
|
25
|
-
'mac-embedded', // iOS/ServerBundle/ — bundled inside the Mac app DMG
|
|
26
|
-
'linux', // LinuxServer/
|
|
27
|
-
'windows', // Windows/server/
|
|
28
|
-
'npm' // tactic-remote-server/ — installed via `npm i -g tacticremote`
|
|
29
|
-
]);
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
* Build the `server` object that goes into the `connected` handshake.
|
|
33
|
-
*
|
|
34
|
-
* @param {Object} opts
|
|
35
|
-
* @param {string} opts.platform - One of VALID_PLATFORMS
|
|
36
|
-
* @param {string} opts.appVersion - SemVer string (e.g. "1.6.7"), typically
|
|
37
|
-
* `require('./package.json').version` at the caller. For the npm variant,
|
|
38
|
-
* use `tactic-remote-server/package.json` — NOT the thin wrapper
|
|
39
|
-
* `package.npm.json`, which can lag behind.
|
|
40
|
-
* @param {Object} [opts.buildInfo] - Optional { commit, builtAt } metadata.
|
|
41
|
-
* Omit in production if you don't want to expose it.
|
|
42
|
-
* @returns {Object} The `server` object to include in the handshake.
|
|
43
|
-
*/
|
|
44
|
-
function buildServerHandshake({ platform, appVersion, buildInfo }) {
|
|
45
|
-
if (!VALID_PLATFORMS.includes(platform)) {
|
|
46
|
-
throw new Error(
|
|
47
|
-
`Invalid platform "${platform}". Must be one of: ${VALID_PLATFORMS.join(', ')}`
|
|
48
|
-
);
|
|
49
|
-
}
|
|
50
|
-
if (typeof appVersion !== 'string' || appVersion.length === 0) {
|
|
51
|
-
throw new Error('appVersion must be a non-empty string');
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
const out = {
|
|
55
|
-
appVersion,
|
|
56
|
-
protocolVersion: PROTOCOL_VERSION,
|
|
57
|
-
platform,
|
|
58
|
-
minimumSupportedClientProtocolVersion:
|
|
59
|
-
MINIMUM_SUPPORTED_CLIENT_PROTOCOL_VERSION
|
|
60
|
-
};
|
|
61
|
-
|
|
62
|
-
if (buildInfo && typeof buildInfo === 'object') {
|
|
63
|
-
out.buildInfo = buildInfo;
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
return out;
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
module.exports = {
|
|
70
|
-
buildServerHandshake,
|
|
71
|
-
VALID_PLATFORMS
|
|
72
|
-
};
|
|
@@ -1,102 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Server identity management.
|
|
3
|
-
* Generates and persists a unique serverId (UUID v4) and serverSecret (64 hex chars).
|
|
4
|
-
* On Windows: uses %APPDATA%/tactic-remote/server-identity.json.
|
|
5
|
-
* On other platforms: uses ~/.tactic-remote/server-identity.json.
|
|
6
|
-
* Idempotent: creates on first run, reuses on subsequent runs.
|
|
7
|
-
*/
|
|
8
|
-
|
|
9
|
-
const fs = require('fs');
|
|
10
|
-
const path = require('path');
|
|
11
|
-
const os = require('os');
|
|
12
|
-
const crypto = require('crypto');
|
|
13
|
-
|
|
14
|
-
const IDENTITY_DIR = process.platform === 'win32'
|
|
15
|
-
? path.join(process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming'), 'tactic-remote')
|
|
16
|
-
: path.join(os.homedir(), '.tactic-remote');
|
|
17
|
-
const IDENTITY_FILE = path.join(IDENTITY_DIR, 'server-identity.json');
|
|
18
|
-
|
|
19
|
-
/**
|
|
20
|
-
* Generate a UUID v4.
|
|
21
|
-
* Uses crypto.randomUUID() if available (Node 19+), otherwise manual generation.
|
|
22
|
-
* @returns {string}
|
|
23
|
-
*/
|
|
24
|
-
function generateUUID() {
|
|
25
|
-
if (typeof crypto.randomUUID === 'function') {
|
|
26
|
-
return crypto.randomUUID();
|
|
27
|
-
}
|
|
28
|
-
const bytes = crypto.randomBytes(16);
|
|
29
|
-
bytes[6] = (bytes[6] & 0x0f) | 0x40;
|
|
30
|
-
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
|
31
|
-
const hex = bytes.toString('hex');
|
|
32
|
-
return [
|
|
33
|
-
hex.slice(0, 8),
|
|
34
|
-
hex.slice(8, 12),
|
|
35
|
-
hex.slice(12, 16),
|
|
36
|
-
hex.slice(16, 20),
|
|
37
|
-
hex.slice(20, 32)
|
|
38
|
-
].join('-');
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
/**
|
|
42
|
-
* Generate a random server secret (64 hex characters = 32 bytes).
|
|
43
|
-
* @returns {string}
|
|
44
|
-
*/
|
|
45
|
-
function generateSecret() {
|
|
46
|
-
return crypto.randomBytes(32).toString('hex');
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
/**
|
|
50
|
-
* Load or create server identity.
|
|
51
|
-
* Returns { serverId, serverSecret } from the identity file.
|
|
52
|
-
* Creates the file with new values if it doesn't exist or is corrupted.
|
|
53
|
-
*
|
|
54
|
-
* @param {Object} [options] - Optional overrides for testing
|
|
55
|
-
* @param {string} [options.identityDir] - Directory to store identity file
|
|
56
|
-
* @param {string} [options.identityFile] - Full path to identity file
|
|
57
|
-
* @returns {{ serverId: string, serverSecret: string }}
|
|
58
|
-
*/
|
|
59
|
-
function loadOrCreate(options = {}) {
|
|
60
|
-
const identityDir = options.identityDir || IDENTITY_DIR;
|
|
61
|
-
const identityFile = options.identityFile || IDENTITY_FILE;
|
|
62
|
-
|
|
63
|
-
try {
|
|
64
|
-
const content = fs.readFileSync(identityFile, 'utf8');
|
|
65
|
-
const data = JSON.parse(content);
|
|
66
|
-
if (data.serverId && typeof data.serverId === 'string' &&
|
|
67
|
-
data.serverSecret && typeof data.serverSecret === 'string' &&
|
|
68
|
-
data.serverSecret.length >= 32) {
|
|
69
|
-
return { serverId: data.serverId, serverSecret: data.serverSecret };
|
|
70
|
-
}
|
|
71
|
-
} catch (_err) {
|
|
72
|
-
// File doesn't exist or is corrupted — create new identity
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
const identity = {
|
|
76
|
-
serverId: generateUUID(),
|
|
77
|
-
serverSecret: generateSecret()
|
|
78
|
-
};
|
|
79
|
-
|
|
80
|
-
try {
|
|
81
|
-
fs.mkdirSync(identityDir, { recursive: true });
|
|
82
|
-
} catch (_err) {
|
|
83
|
-
// Directory already exists
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
try {
|
|
87
|
-
fs.writeFileSync(identityFile, JSON.stringify(identity, null, 2), { mode: 0o600 });
|
|
88
|
-
console.log(`[identity] Created server identity: ${identity.serverId}`);
|
|
89
|
-
} catch (err) {
|
|
90
|
-
console.error(`[identity] Failed to write identity file: ${err.message}`);
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
return identity;
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
module.exports = {
|
|
97
|
-
loadOrCreate,
|
|
98
|
-
IDENTITY_DIR,
|
|
99
|
-
IDENTITY_FILE,
|
|
100
|
-
_generateUUID: generateUUID,
|
|
101
|
-
_generateSecret: generateSecret
|
|
102
|
-
};
|
|
@@ -1,321 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* StreamJsonParser — translates Claude stream-json NDJSON events
|
|
3
|
-
* into our WebSocket event payloads.
|
|
4
|
-
*
|
|
5
|
-
* Each function returns an array of event objects to broadcast
|
|
6
|
-
* (empty array = no-op, can return multiple events for one input).
|
|
7
|
-
*/
|
|
8
|
-
|
|
9
|
-
function extractToolDetail(toolName, toolInput) {
|
|
10
|
-
if (!toolInput || typeof toolInput !== 'object') return '';
|
|
11
|
-
switch (toolName) {
|
|
12
|
-
case 'Read': case 'Write': case 'Edit': return toolInput.file_path || '';
|
|
13
|
-
case 'Bash': return (toolInput.command || '').substring(0, 100);
|
|
14
|
-
case 'Glob': return toolInput.pattern || '';
|
|
15
|
-
case 'Grep': return toolInput.pattern || '';
|
|
16
|
-
case 'Agent': return toolInput.description || '';
|
|
17
|
-
default: return '';
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
/**
|
|
22
|
-
* Translate a single Claude stream-json event into WebSocket event(s).
|
|
23
|
-
*
|
|
24
|
-
* @param {Object} claudeEvent - Parsed JSON event from claude stdout
|
|
25
|
-
* @param {string} sessionId - The structured session ID
|
|
26
|
-
* @returns {Array<{event: string, payload: Object}>} WebSocket events to broadcast
|
|
27
|
-
*/
|
|
28
|
-
function translateEvent(claudeEvent, sessionId) {
|
|
29
|
-
if (!claudeEvent || !claudeEvent.type) return [];
|
|
30
|
-
|
|
31
|
-
switch (claudeEvent.type) {
|
|
32
|
-
case 'system':
|
|
33
|
-
return handleSystemEvent(claudeEvent, sessionId);
|
|
34
|
-
|
|
35
|
-
case 'stream_event':
|
|
36
|
-
return handleStreamEvent(claudeEvent, sessionId);
|
|
37
|
-
|
|
38
|
-
case 'assistant':
|
|
39
|
-
return handleAssistantEvent(claudeEvent, sessionId);
|
|
40
|
-
|
|
41
|
-
case 'result':
|
|
42
|
-
return handleResultEvent(claudeEvent, sessionId);
|
|
43
|
-
|
|
44
|
-
case 'rate_limit_event':
|
|
45
|
-
return handleRateLimitEvent(claudeEvent, sessionId);
|
|
46
|
-
|
|
47
|
-
case 'control_request':
|
|
48
|
-
return handleControlRequest(claudeEvent, sessionId);
|
|
49
|
-
|
|
50
|
-
default:
|
|
51
|
-
return [];
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
function handleSystemEvent(event, sessionId) {
|
|
56
|
-
const subtype = event.subtype;
|
|
57
|
-
|
|
58
|
-
if (subtype === 'init') {
|
|
59
|
-
return [{
|
|
60
|
-
event: 'structured_init',
|
|
61
|
-
payload: {
|
|
62
|
-
sessionId,
|
|
63
|
-
cwd: event.cwd || null,
|
|
64
|
-
model: event.model || null,
|
|
65
|
-
tools: event.tools || [],
|
|
66
|
-
session_id: event.session_id || sessionId
|
|
67
|
-
}
|
|
68
|
-
}];
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
if (subtype === 'hook_started') {
|
|
72
|
-
const hookName = event.hook_name;
|
|
73
|
-
if (hookName === 'PreToolUse' || hookName === 'PostToolUse') {
|
|
74
|
-
return [{
|
|
75
|
-
event: 'tool_use',
|
|
76
|
-
payload: {
|
|
77
|
-
event: hookName,
|
|
78
|
-
tool_name: event.tool_name || '',
|
|
79
|
-
tool_use_id: event.tool_use_id || '',
|
|
80
|
-
tool_detail: extractToolDetail(event.tool_name, event.tool_input),
|
|
81
|
-
session: sessionId,
|
|
82
|
-
timestamp: Date.now()
|
|
83
|
-
}
|
|
84
|
-
}];
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
if (hookName === 'Notification') {
|
|
88
|
-
const message = event.message || (event.data && event.data.message) || '';
|
|
89
|
-
if (message) {
|
|
90
|
-
return [{
|
|
91
|
-
event: 'notification',
|
|
92
|
-
payload: {
|
|
93
|
-
title: 'Claude',
|
|
94
|
-
body: message,
|
|
95
|
-
structured: true,
|
|
96
|
-
session: sessionId,
|
|
97
|
-
timestamp: Date.now()
|
|
98
|
-
}
|
|
99
|
-
}];
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
if (hookName === 'Stop') {
|
|
104
|
-
return [{
|
|
105
|
-
event: 'hook_event',
|
|
106
|
-
payload: {
|
|
107
|
-
event: 'Stop',
|
|
108
|
-
structured: true,
|
|
109
|
-
session: sessionId,
|
|
110
|
-
timestamp: Date.now()
|
|
111
|
-
}
|
|
112
|
-
}];
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
if (hookName === 'Start') {
|
|
116
|
-
return [{
|
|
117
|
-
event: 'hook_event',
|
|
118
|
-
payload: {
|
|
119
|
-
event: 'Start',
|
|
120
|
-
structured: true,
|
|
121
|
-
session: sessionId,
|
|
122
|
-
timestamp: Date.now()
|
|
123
|
-
}
|
|
124
|
-
}];
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
return [];
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
if (subtype === 'hook_response') {
|
|
131
|
-
const hookName = event.hook_name;
|
|
132
|
-
if (hookName === 'PostToolUse') {
|
|
133
|
-
return [{
|
|
134
|
-
event: 'tool_use',
|
|
135
|
-
payload: {
|
|
136
|
-
event: 'PostToolUse',
|
|
137
|
-
tool_name: event.tool_name || '',
|
|
138
|
-
tool_use_id: event.tool_use_id || '',
|
|
139
|
-
tool_detail: extractToolDetail(event.tool_name, event.tool_input),
|
|
140
|
-
session: sessionId,
|
|
141
|
-
timestamp: Date.now()
|
|
142
|
-
}
|
|
143
|
-
}];
|
|
144
|
-
}
|
|
145
|
-
return [];
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
return [];
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
function handleStreamEvent(event, sessionId) {
|
|
152
|
-
const inner = event.event;
|
|
153
|
-
if (!inner || !inner.type) return [];
|
|
154
|
-
|
|
155
|
-
switch (inner.type) {
|
|
156
|
-
case 'content_block_delta': {
|
|
157
|
-
const delta = inner.delta;
|
|
158
|
-
if (!delta) return [];
|
|
159
|
-
|
|
160
|
-
if (delta.type === 'text_delta' && delta.text) {
|
|
161
|
-
return [{
|
|
162
|
-
event: 'structured_delta',
|
|
163
|
-
payload: {
|
|
164
|
-
sessionId,
|
|
165
|
-
delta: delta.text,
|
|
166
|
-
blockType: 'text'
|
|
167
|
-
}
|
|
168
|
-
}];
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
if (delta.type === 'thinking_delta' && delta.thinking) {
|
|
172
|
-
return [{
|
|
173
|
-
event: 'structured_delta',
|
|
174
|
-
payload: {
|
|
175
|
-
sessionId,
|
|
176
|
-
delta: delta.thinking,
|
|
177
|
-
blockType: 'thinking'
|
|
178
|
-
}
|
|
179
|
-
}];
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
if (delta.type === 'input_json_delta' && delta.partial_json) {
|
|
183
|
-
return [{
|
|
184
|
-
event: 'structured_delta',
|
|
185
|
-
payload: {
|
|
186
|
-
sessionId,
|
|
187
|
-
delta: delta.partial_json,
|
|
188
|
-
blockType: 'tool_input'
|
|
189
|
-
}
|
|
190
|
-
}];
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
return [];
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
case 'content_block_start': {
|
|
197
|
-
const block = inner.content_block;
|
|
198
|
-
if (!block) return [];
|
|
199
|
-
|
|
200
|
-
if (block.type === 'tool_use') {
|
|
201
|
-
return [{
|
|
202
|
-
event: 'structured_tool_start',
|
|
203
|
-
payload: {
|
|
204
|
-
sessionId,
|
|
205
|
-
toolName: block.name || '',
|
|
206
|
-
toolUseId: block.id || ''
|
|
207
|
-
}
|
|
208
|
-
}];
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
if (block.type === 'thinking') {
|
|
212
|
-
return [{
|
|
213
|
-
event: 'structured_thinking_start',
|
|
214
|
-
payload: { sessionId }
|
|
215
|
-
}];
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
return [];
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
case 'content_block_stop':
|
|
222
|
-
return [{
|
|
223
|
-
event: 'structured_block_stop',
|
|
224
|
-
payload: {
|
|
225
|
-
sessionId,
|
|
226
|
-
index: inner.index
|
|
227
|
-
}
|
|
228
|
-
}];
|
|
229
|
-
|
|
230
|
-
case 'message_start':
|
|
231
|
-
return [{
|
|
232
|
-
event: 'structured_message_start',
|
|
233
|
-
payload: {
|
|
234
|
-
sessionId,
|
|
235
|
-
model: inner.message?.model || null
|
|
236
|
-
}
|
|
237
|
-
}];
|
|
238
|
-
|
|
239
|
-
case 'message_delta':
|
|
240
|
-
return [{
|
|
241
|
-
event: 'structured_message_delta',
|
|
242
|
-
payload: {
|
|
243
|
-
sessionId,
|
|
244
|
-
stopReason: inner.delta?.stop_reason || null,
|
|
245
|
-
usage: inner.usage || null
|
|
246
|
-
}
|
|
247
|
-
}];
|
|
248
|
-
|
|
249
|
-
case 'message_stop':
|
|
250
|
-
return [{
|
|
251
|
-
event: 'structured_message_stop',
|
|
252
|
-
payload: { sessionId }
|
|
253
|
-
}];
|
|
254
|
-
|
|
255
|
-
default:
|
|
256
|
-
return [];
|
|
257
|
-
}
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
function handleAssistantEvent(event, sessionId) {
|
|
261
|
-
return [{
|
|
262
|
-
event: 'structured_message',
|
|
263
|
-
payload: {
|
|
264
|
-
sessionId,
|
|
265
|
-
message: event.message || null,
|
|
266
|
-
session_id: event.session_id || sessionId
|
|
267
|
-
}
|
|
268
|
-
}];
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
function handleResultEvent(event, sessionId) {
|
|
272
|
-
const events = [{
|
|
273
|
-
event: 'structured_result',
|
|
274
|
-
payload: {
|
|
275
|
-
sessionId,
|
|
276
|
-
subtype: event.subtype || 'success',
|
|
277
|
-
isError: event.is_error || false,
|
|
278
|
-
result: event.result || null,
|
|
279
|
-
totalCostUsd: event.total_cost_usd ?? null,
|
|
280
|
-
durationMs: event.duration_ms ?? null,
|
|
281
|
-
durationApiMs: event.duration_api_ms ?? null,
|
|
282
|
-
session_id: event.session_id || sessionId
|
|
283
|
-
}
|
|
284
|
-
}];
|
|
285
|
-
|
|
286
|
-
return events;
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
function handleRateLimitEvent(event, sessionId) {
|
|
290
|
-
return [{
|
|
291
|
-
event: 'structured_rate_limit',
|
|
292
|
-
payload: {
|
|
293
|
-
sessionId,
|
|
294
|
-
rateLimitInfo: event.rate_limit_info || null
|
|
295
|
-
}
|
|
296
|
-
}];
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
function handleControlRequest(event, sessionId) {
|
|
300
|
-
const req = event.request;
|
|
301
|
-
if (!req || req.subtype !== 'can_use_tool') return [];
|
|
302
|
-
|
|
303
|
-
const isAskUser = req.tool_name === 'AskUserQuestion';
|
|
304
|
-
|
|
305
|
-
return [{
|
|
306
|
-
event: 'structured_approval_request',
|
|
307
|
-
payload: {
|
|
308
|
-
sessionId,
|
|
309
|
-
requestId: event.request_id || req.request_id || '',
|
|
310
|
-
toolName: req.tool_name || '',
|
|
311
|
-
toolDetail: extractToolDetail(req.tool_name, req.input),
|
|
312
|
-
toolInput: req.input || {},
|
|
313
|
-
toolUseId: req.tool_use_id || '',
|
|
314
|
-
reason: req.description || null,
|
|
315
|
-
isAskUserQuestion: isAskUser,
|
|
316
|
-
questions: isAskUser ? (req.input?.questions || []) : null
|
|
317
|
-
}
|
|
318
|
-
}];
|
|
319
|
-
}
|
|
320
|
-
|
|
321
|
-
module.exports = { translateEvent, extractToolDetail };
|