agent-state-machine 2.3.0 → 2.5.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/bin/cli.js +65 -9
- package/lib/llm.js +134 -22
- package/lib/remote/client.js +19 -6
- package/lib/runtime/agent.js +127 -3
- package/lib/runtime/runtime.js +127 -5
- package/package.json +1 -1
- package/templates/project-builder/config.js +4 -4
- package/vercel-server/api/config/[token].js +76 -0
- package/vercel-server/api/history/[token].js +1 -0
- package/vercel-server/api/ws/cli.js +39 -20
- package/vercel-server/local-server.js +98 -11
- package/vercel-server/public/remote/assets/index-BHvHkNOe.css +1 -0
- package/vercel-server/public/remote/assets/index-BSL55rdk.js +188 -0
- package/vercel-server/public/remote/index.html +2 -2
- package/vercel-server/ui/src/App.jsx +36 -1
- package/vercel-server/ui/src/components/ContentCard.jsx +350 -19
- package/vercel-server/ui/src/components/Footer.jsx +1 -6
- package/vercel-server/ui/src/components/Header.jsx +59 -11
- package/vercel-server/ui/src/components/SettingsModal.jsx +130 -0
- package/vercel-server/ui/src/index.css +53 -0
- package/vercel-server/public/remote/assets/index-BTLc1QSv.js +0 -168
- package/vercel-server/public/remote/assets/index-DLa4X08t.css +0 -1
package/lib/runtime/runtime.js
CHANGED
|
@@ -68,6 +68,9 @@ export class WorkflowRuntime {
|
|
|
68
68
|
this.status = savedState.status || 'IDLE';
|
|
69
69
|
this.startedAt = savedState.startedAt || null;
|
|
70
70
|
|
|
71
|
+
// Load usage totals
|
|
72
|
+
this._usageTotals = savedState.usage || null;
|
|
73
|
+
|
|
71
74
|
// Create memory proxy for auto-persistence
|
|
72
75
|
this.memory = createMemoryProxy(this._rawMemory, () => this.persist());
|
|
73
76
|
|
|
@@ -197,12 +200,67 @@ export class WorkflowRuntime {
|
|
|
197
200
|
memory: this._rawMemory,
|
|
198
201
|
_error: this._error,
|
|
199
202
|
startedAt: this.startedAt,
|
|
200
|
-
lastUpdatedAt: new Date().toISOString()
|
|
203
|
+
lastUpdatedAt: new Date().toISOString(),
|
|
204
|
+
usage: this._usageTotals
|
|
201
205
|
};
|
|
202
206
|
|
|
203
207
|
fs.writeFileSync(this.stateFile, JSON.stringify(state, null, 2));
|
|
204
208
|
}
|
|
205
209
|
|
|
210
|
+
/**
|
|
211
|
+
* Update running token usage totals
|
|
212
|
+
* @param {string} agentName - Name of the agent that generated the usage
|
|
213
|
+
* @param {object} usage - Usage object with inputTokens, outputTokens, etc.
|
|
214
|
+
*/
|
|
215
|
+
updateUsageTotals(agentName, usage) {
|
|
216
|
+
if (!usage) return;
|
|
217
|
+
|
|
218
|
+
if (!this._usageTotals) {
|
|
219
|
+
this._usageTotals = {
|
|
220
|
+
totalInputTokens: 0,
|
|
221
|
+
totalOutputTokens: 0,
|
|
222
|
+
totalCachedTokens: 0,
|
|
223
|
+
totalCost: 0,
|
|
224
|
+
agentUsage: {},
|
|
225
|
+
modelUsage: {}
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// Update totals
|
|
230
|
+
this._usageTotals.totalInputTokens += usage.inputTokens || 0;
|
|
231
|
+
this._usageTotals.totalOutputTokens += usage.outputTokens || 0;
|
|
232
|
+
this._usageTotals.totalCachedTokens += usage.cachedTokens || 0;
|
|
233
|
+
this._usageTotals.totalCost += usage.cost || 0;
|
|
234
|
+
|
|
235
|
+
// Per-agent tracking
|
|
236
|
+
if (!this._usageTotals.agentUsage[agentName]) {
|
|
237
|
+
this._usageTotals.agentUsage[agentName] = { inputTokens: 0, outputTokens: 0, calls: 0 };
|
|
238
|
+
}
|
|
239
|
+
this._usageTotals.agentUsage[agentName].inputTokens += usage.inputTokens || 0;
|
|
240
|
+
this._usageTotals.agentUsage[agentName].outputTokens += usage.outputTokens || 0;
|
|
241
|
+
this._usageTotals.agentUsage[agentName].calls += usage.calls || 1;
|
|
242
|
+
|
|
243
|
+
// Per-model tracking
|
|
244
|
+
if (usage.models) {
|
|
245
|
+
for (const [model, modelUsage] of Object.entries(usage.models)) {
|
|
246
|
+
if (!this._usageTotals.modelUsage[model]) {
|
|
247
|
+
this._usageTotals.modelUsage[model] = { inputTokens: 0, outputTokens: 0 };
|
|
248
|
+
}
|
|
249
|
+
this._usageTotals.modelUsage[model].inputTokens += modelUsage.inputTokens || 0;
|
|
250
|
+
this._usageTotals.modelUsage[model].outputTokens += modelUsage.outputTokens || 0;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
this.persist();
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Reset usage totals
|
|
259
|
+
*/
|
|
260
|
+
resetUsageTotals() {
|
|
261
|
+
this._usageTotals = null;
|
|
262
|
+
}
|
|
263
|
+
|
|
206
264
|
/**
|
|
207
265
|
* Prepend an event to history.jsonl (newest first)
|
|
208
266
|
*/
|
|
@@ -527,6 +585,31 @@ export class WorkflowRuntime {
|
|
|
527
585
|
}
|
|
528
586
|
}
|
|
529
587
|
|
|
588
|
+
/**
|
|
589
|
+
* Handle config update from remote browser UI
|
|
590
|
+
* Called by RemoteClient when it receives a config_update message
|
|
591
|
+
*/
|
|
592
|
+
handleRemoteConfigUpdate(config) {
|
|
593
|
+
if (config.fullAuto !== undefined) {
|
|
594
|
+
const wasFullAuto = this.workflowConfig.fullAuto;
|
|
595
|
+
this.workflowConfig.fullAuto = config.fullAuto;
|
|
596
|
+
if (wasFullAuto !== config.fullAuto) {
|
|
597
|
+
console.log(`${C.cyan}Remote: Full-auto mode ${config.fullAuto ? 'enabled' : 'disabled'}${C.reset}`);
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
if (config.autoSelectDelay !== undefined) {
|
|
602
|
+
this.workflowConfig.autoSelectDelay = config.autoSelectDelay;
|
|
603
|
+
console.log(`${C.dim}Remote: Auto-select delay set to ${config.autoSelectDelay}s${C.reset}`);
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
if (config.stop) {
|
|
607
|
+
console.log(`\n${C.yellow}${C.bold}Remote: Stop requested${C.reset}`);
|
|
608
|
+
// Trigger graceful shutdown
|
|
609
|
+
process.emit('SIGINT');
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
|
|
530
613
|
/**
|
|
531
614
|
* Read the user's response from an interaction file
|
|
532
615
|
*/
|
|
@@ -562,14 +645,14 @@ export class WorkflowRuntime {
|
|
|
562
645
|
showStatus() {
|
|
563
646
|
console.log(`\n${C.bold}Workflow: ${C.cyan}${this.workflowName}${C.reset}`);
|
|
564
647
|
console.log(`${C.dim}${'─'.repeat(40)}${C.reset}`);
|
|
565
|
-
|
|
648
|
+
|
|
566
649
|
let statusColor = C.reset;
|
|
567
650
|
if (this.status === 'COMPLETED') statusColor = C.green;
|
|
568
651
|
if (this.status === 'FAILED') statusColor = C.red;
|
|
569
652
|
if (this.status === 'STOPPED') statusColor = C.yellow;
|
|
570
653
|
if (this.status === 'RUNNING') statusColor = C.blue;
|
|
571
654
|
if (this.status === 'IDLE') statusColor = C.gray;
|
|
572
|
-
|
|
655
|
+
|
|
573
656
|
console.log(`Status: ${statusColor}${this.status}${C.reset}`);
|
|
574
657
|
|
|
575
658
|
if (this.startedAt) {
|
|
@@ -580,6 +663,36 @@ export class WorkflowRuntime {
|
|
|
580
663
|
console.log(`Error: ${C.red}${this._error}${C.reset}`);
|
|
581
664
|
}
|
|
582
665
|
|
|
666
|
+
// Display token usage if available
|
|
667
|
+
if (this._usageTotals && (this._usageTotals.totalInputTokens > 0 || this._usageTotals.totalOutputTokens > 0)) {
|
|
668
|
+
console.log(`\n${C.bold}Token Usage:${C.reset}`);
|
|
669
|
+
const formatTokens = (count) => {
|
|
670
|
+
if (count >= 1000000) return `${(count / 1000000).toFixed(1)}M`;
|
|
671
|
+
if (count >= 10000) return `${Math.round(count / 1000)}k`;
|
|
672
|
+
if (count >= 1000) return `${(count / 1000).toFixed(1)}k`;
|
|
673
|
+
return count.toString();
|
|
674
|
+
};
|
|
675
|
+
console.log(` Input: ${formatTokens(this._usageTotals.totalInputTokens)}`);
|
|
676
|
+
console.log(` Output: ${formatTokens(this._usageTotals.totalOutputTokens)}`);
|
|
677
|
+
if (this._usageTotals.totalCachedTokens > 0) {
|
|
678
|
+
console.log(` Cached: ${formatTokens(this._usageTotals.totalCachedTokens)}`);
|
|
679
|
+
}
|
|
680
|
+
console.log(` ${C.bold}Total: ${formatTokens(this._usageTotals.totalInputTokens + this._usageTotals.totalOutputTokens)}${C.reset}`);
|
|
681
|
+
if (this._usageTotals.totalCost > 0) {
|
|
682
|
+
console.log(` ${C.cyan}Cost: $${this._usageTotals.totalCost.toFixed(4)}${C.reset}`);
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
// Show per-model breakdown if multiple models used
|
|
686
|
+
const models = Object.keys(this._usageTotals.modelUsage || {});
|
|
687
|
+
if (models.length > 1) {
|
|
688
|
+
console.log(`\n${C.dim}By Model:${C.reset}`);
|
|
689
|
+
for (const model of models) {
|
|
690
|
+
const m = this._usageTotals.modelUsage[model];
|
|
691
|
+
console.log(` ${model}: ${formatTokens(m.inputTokens)} in / ${formatTokens(m.outputTokens)} out`);
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
|
|
583
696
|
const memoryKeys = Object.keys(this._rawMemory).filter((k) => !k.startsWith('_'));
|
|
584
697
|
console.log(`\nMemory Keys: ${C.yellow}${memoryKeys.length}${C.reset}`);
|
|
585
698
|
if (memoryKeys.length > 0) {
|
|
@@ -633,6 +746,7 @@ export class WorkflowRuntime {
|
|
|
633
746
|
this._error = null;
|
|
634
747
|
this.status = 'IDLE';
|
|
635
748
|
this.startedAt = null;
|
|
749
|
+
this.resetUsageTotals();
|
|
636
750
|
|
|
637
751
|
// Recreate memory proxy
|
|
638
752
|
this.memory = createMemoryProxy(this._rawMemory, () => this.persist());
|
|
@@ -663,6 +777,7 @@ export class WorkflowRuntime {
|
|
|
663
777
|
this._error = null;
|
|
664
778
|
this.status = 'IDLE';
|
|
665
779
|
this.startedAt = null;
|
|
780
|
+
this.resetUsageTotals();
|
|
666
781
|
|
|
667
782
|
// Recreate memory proxy
|
|
668
783
|
this.memory = createMemoryProxy(this._rawMemory, () => this.persist());
|
|
@@ -689,6 +804,9 @@ export class WorkflowRuntime {
|
|
|
689
804
|
onInteractionResponse: (slug, targetKey, response) => {
|
|
690
805
|
this.handleRemoteInteraction(slug, targetKey, response);
|
|
691
806
|
},
|
|
807
|
+
onConfigUpdate: (config) => {
|
|
808
|
+
this.handleRemoteConfigUpdate(config);
|
|
809
|
+
},
|
|
692
810
|
onStatusChange: (status) => {
|
|
693
811
|
if (status === 'disconnected') {
|
|
694
812
|
console.log(`${C.yellow}Remote: Connection lost, attempting to reconnect...${C.reset}`);
|
|
@@ -700,10 +818,14 @@ export class WorkflowRuntime {
|
|
|
700
818
|
|
|
701
819
|
await this.remoteClient.connect();
|
|
702
820
|
|
|
703
|
-
// Send existing history if connected
|
|
821
|
+
// Send existing history if connected, including current config
|
|
704
822
|
if (this.remoteClient.connected) {
|
|
705
823
|
const history = this.loadHistory();
|
|
706
|
-
|
|
824
|
+
const config = {
|
|
825
|
+
fullAuto: this.workflowConfig.fullAuto || false,
|
|
826
|
+
autoSelectDelay: this.workflowConfig.autoSelectDelay ?? 20,
|
|
827
|
+
};
|
|
828
|
+
await this.remoteClient.sendSessionInit(history, config);
|
|
707
829
|
}
|
|
708
830
|
|
|
709
831
|
this.remoteEnabled = true;
|
package/package.json
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
export const config = {
|
|
2
2
|
models: {
|
|
3
|
-
fast: "gemini -m gemini-2.5-
|
|
4
|
-
low: "gemini -m gemini-2.5-
|
|
5
|
-
med: "gemini -m gemini-2.5-
|
|
6
|
-
high: "gemini -m gemini-2.5-
|
|
3
|
+
fast: "gemini -m gemini-2.5-pro",
|
|
4
|
+
low: "gemini -m gemini-2.5-pro",
|
|
5
|
+
med: "gemini -m gemini-2.5-pro",
|
|
6
|
+
high: "gemini -m gemini-2.5-pro",
|
|
7
7
|
},
|
|
8
8
|
apiKeys: {
|
|
9
9
|
gemini: process.env.GEMINI_API_KEY,
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File: /vercel-server/api/config/[token].js
|
|
3
|
+
*
|
|
4
|
+
* POST endpoint for browser config updates (fullAuto, autoSelectDelay, stop)
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import {
|
|
8
|
+
getSession,
|
|
9
|
+
updateSession,
|
|
10
|
+
pushConfigUpdate,
|
|
11
|
+
} from '../../lib/redis.js';
|
|
12
|
+
|
|
13
|
+
export default async function handler(req, res) {
|
|
14
|
+
// Enable CORS
|
|
15
|
+
res.setHeader('Access-Control-Allow-Origin', '*');
|
|
16
|
+
res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');
|
|
17
|
+
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
|
|
18
|
+
|
|
19
|
+
if (req.method === 'OPTIONS') {
|
|
20
|
+
return res.status(200).end();
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
if (req.method !== 'POST') {
|
|
24
|
+
return res.status(405).json({ error: 'Method not allowed' });
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const { token } = req.query;
|
|
28
|
+
|
|
29
|
+
if (!token) {
|
|
30
|
+
return res.status(400).json({ error: 'Missing token parameter' });
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
try {
|
|
34
|
+
// Validate session
|
|
35
|
+
const session = await getSession(token);
|
|
36
|
+
if (!session) {
|
|
37
|
+
return res.status(404).json({ error: 'Session not found or expired' });
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Check if CLI is connected
|
|
41
|
+
if (!session.cliConnected) {
|
|
42
|
+
return res.status(503).json({ error: 'CLI is disconnected. Cannot update config.' });
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Parse body
|
|
46
|
+
const body = typeof req.body === 'string' ? JSON.parse(req.body) : req.body;
|
|
47
|
+
const { fullAuto, autoSelectDelay, stop } = body;
|
|
48
|
+
|
|
49
|
+
// Build config update object with only provided fields
|
|
50
|
+
const configUpdate = {};
|
|
51
|
+
if (fullAuto !== undefined) configUpdate.fullAuto = fullAuto;
|
|
52
|
+
if (autoSelectDelay !== undefined) configUpdate.autoSelectDelay = autoSelectDelay;
|
|
53
|
+
if (stop !== undefined) configUpdate.stop = stop;
|
|
54
|
+
|
|
55
|
+
if (Object.keys(configUpdate).length === 0) {
|
|
56
|
+
return res.status(400).json({ error: 'No config fields provided' });
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// Push config update to pending queue for CLI to poll
|
|
60
|
+
await pushConfigUpdate(token, configUpdate);
|
|
61
|
+
|
|
62
|
+
// Update session metadata with new config (except stop which is transient)
|
|
63
|
+
if (!stop) {
|
|
64
|
+
const currentConfig = session.config || { fullAuto: false, autoSelectDelay: 20 };
|
|
65
|
+
const newConfig = { ...currentConfig };
|
|
66
|
+
if (fullAuto !== undefined) newConfig.fullAuto = fullAuto;
|
|
67
|
+
if (autoSelectDelay !== undefined) newConfig.autoSelectDelay = autoSelectDelay;
|
|
68
|
+
await updateSession(token, { config: newConfig });
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
return res.status(200).json({ success: true });
|
|
72
|
+
} catch (err) {
|
|
73
|
+
console.error('Error updating config:', err);
|
|
74
|
+
return res.status(500).json({ error: err.message });
|
|
75
|
+
}
|
|
76
|
+
}
|
|
@@ -42,6 +42,7 @@ export default async function handler(req, res) {
|
|
|
42
42
|
return res.status(200).json({
|
|
43
43
|
workflowName: session.workflowName,
|
|
44
44
|
cliConnected: session.cliConnected,
|
|
45
|
+
config: session.config || { fullAuto: false, autoSelectDelay: 20 },
|
|
45
46
|
entries,
|
|
46
47
|
});
|
|
47
48
|
} catch (err) {
|
|
@@ -14,6 +14,8 @@ import {
|
|
|
14
14
|
setCLIConnected,
|
|
15
15
|
addEvent,
|
|
16
16
|
setEvents,
|
|
17
|
+
peekConfigUpdate,
|
|
18
|
+
popConfigUpdate,
|
|
17
19
|
redis,
|
|
18
20
|
KEYS,
|
|
19
21
|
} from '../../lib/redis.js';
|
|
@@ -59,10 +61,14 @@ async function handlePost(req, res) {
|
|
|
59
61
|
try {
|
|
60
62
|
switch (action) {
|
|
61
63
|
case 'session_init': {
|
|
62
|
-
const { workflowName, history } = body;
|
|
64
|
+
const { workflowName, history, config } = body;
|
|
63
65
|
|
|
64
|
-
// Create session
|
|
65
|
-
await createSession(sessionToken, {
|
|
66
|
+
// Create session with initial config
|
|
67
|
+
await createSession(sessionToken, {
|
|
68
|
+
workflowName,
|
|
69
|
+
cliConnected: true,
|
|
70
|
+
config: config || null,
|
|
71
|
+
});
|
|
66
72
|
|
|
67
73
|
// Replace events with the provided history snapshot (single source of truth)
|
|
68
74
|
await setEvents(sessionToken, history || []);
|
|
@@ -140,7 +146,7 @@ async function handlePost(req, res) {
|
|
|
140
146
|
}
|
|
141
147
|
|
|
142
148
|
/**
|
|
143
|
-
* Handle GET requests - long-poll for interaction responses
|
|
149
|
+
* Handle GET requests - long-poll for interaction responses and config updates
|
|
144
150
|
* Uses efficient polling with 5-second intervals (Upstash doesn't support BLPOP)
|
|
145
151
|
*/
|
|
146
152
|
async function handleGet(req, res) {
|
|
@@ -165,8 +171,7 @@ async function handleGet(req, res) {
|
|
|
165
171
|
|
|
166
172
|
// Poll every 5 seconds (10 calls per 50s timeout vs 50 calls before)
|
|
167
173
|
while (Date.now() - startTime < timeoutMs) {
|
|
168
|
-
//
|
|
169
|
-
// We only remove AFTER CLI confirms receipt via DELETE request
|
|
174
|
+
// Check for pending interactions first (higher priority)
|
|
170
175
|
const pending = await redis.lindex(pendingKey, 0);
|
|
171
176
|
|
|
172
177
|
if (pending) {
|
|
@@ -175,9 +180,6 @@ async function handleGet(req, res) {
|
|
|
175
180
|
// Generate a receipt ID so CLI can confirm
|
|
176
181
|
const receiptId = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
177
182
|
|
|
178
|
-
// DON'T remove yet - CLI will confirm with DELETE request
|
|
179
|
-
// This prevents data loss if response doesn't reach CLI
|
|
180
|
-
|
|
181
183
|
return res.status(200).json({
|
|
182
184
|
type: 'interaction_response',
|
|
183
185
|
receiptId,
|
|
@@ -185,11 +187,24 @@ async function handleGet(req, res) {
|
|
|
185
187
|
});
|
|
186
188
|
}
|
|
187
189
|
|
|
188
|
-
//
|
|
190
|
+
// Check for pending config updates
|
|
191
|
+
const configUpdate = await peekConfigUpdate(token);
|
|
192
|
+
|
|
193
|
+
if (configUpdate) {
|
|
194
|
+
const receiptId = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
195
|
+
|
|
196
|
+
return res.status(200).json({
|
|
197
|
+
type: 'config_update',
|
|
198
|
+
receiptId,
|
|
199
|
+
...configUpdate,
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// Wait 5 seconds before checking again
|
|
189
204
|
await new Promise((resolve) => setTimeout(resolve, 5000));
|
|
190
205
|
}
|
|
191
206
|
|
|
192
|
-
// Timeout - no interaction received
|
|
207
|
+
// Timeout - no interaction or config update received
|
|
193
208
|
return res.status(204).end();
|
|
194
209
|
} catch (err) {
|
|
195
210
|
console.error('Error polling for interactions:', err);
|
|
@@ -198,25 +213,29 @@ async function handleGet(req, res) {
|
|
|
198
213
|
}
|
|
199
214
|
|
|
200
215
|
/**
|
|
201
|
-
* Handle DELETE requests - CLI confirms receipt of interaction
|
|
202
|
-
* This removes the
|
|
216
|
+
* Handle DELETE requests - CLI confirms receipt of interaction or config update
|
|
217
|
+
* This removes the item from the pending queue
|
|
203
218
|
*/
|
|
204
219
|
async function handleDelete(req, res) {
|
|
205
|
-
const { token } = req.query;
|
|
220
|
+
const { token, type = 'interaction' } = req.query;
|
|
206
221
|
|
|
207
222
|
if (!token) {
|
|
208
223
|
return res.status(400).json({ error: 'Missing token parameter' });
|
|
209
224
|
}
|
|
210
225
|
|
|
211
|
-
const channel = KEYS.interactions(token);
|
|
212
|
-
const pendingKey = `${channel}:pending`;
|
|
213
|
-
|
|
214
226
|
try {
|
|
215
|
-
|
|
216
|
-
|
|
227
|
+
if (type === 'config') {
|
|
228
|
+
// Remove pending config update
|
|
229
|
+
await popConfigUpdate(token);
|
|
230
|
+
} else {
|
|
231
|
+
// Remove pending interaction (default)
|
|
232
|
+
const channel = KEYS.interactions(token);
|
|
233
|
+
const pendingKey = `${channel}:pending`;
|
|
234
|
+
await redis.lpop(pendingKey);
|
|
235
|
+
}
|
|
217
236
|
return res.status(200).json({ success: true });
|
|
218
237
|
} catch (err) {
|
|
219
|
-
console.error('Error confirming
|
|
238
|
+
console.error('Error confirming receipt:', err);
|
|
220
239
|
return res.status(500).json({ error: err.message });
|
|
221
240
|
}
|
|
222
241
|
}
|
|
@@ -42,6 +42,8 @@ function createSession(token, data) {
|
|
|
42
42
|
cliConnected: true,
|
|
43
43
|
history: data.history || [],
|
|
44
44
|
pendingInteractions: [],
|
|
45
|
+
pendingConfigUpdates: [],
|
|
46
|
+
config: data.config || { fullAuto: false, autoSelectDelay: 20 },
|
|
45
47
|
createdAt: Date.now(),
|
|
46
48
|
};
|
|
47
49
|
sessions.set(token, session);
|
|
@@ -66,6 +68,23 @@ function broadcastToSession(token, event) {
|
|
|
66
68
|
}
|
|
67
69
|
}
|
|
68
70
|
|
|
71
|
+
/**
|
|
72
|
+
* Broadcast "update" to trigger browser refetch
|
|
73
|
+
* The browser SSE handler listens for this string to call fetchData()
|
|
74
|
+
*/
|
|
75
|
+
function broadcastUpdate(token) {
|
|
76
|
+
const clients = sseClients.get(token);
|
|
77
|
+
if (!clients) return;
|
|
78
|
+
|
|
79
|
+
for (const client of clients) {
|
|
80
|
+
try {
|
|
81
|
+
client.write('data: update\n\n');
|
|
82
|
+
} catch (e) {
|
|
83
|
+
clients.delete(client);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
69
88
|
/**
|
|
70
89
|
* Parse request body
|
|
71
90
|
*/
|
|
@@ -122,8 +141,8 @@ async function handleCliPost(req, res) {
|
|
|
122
141
|
|
|
123
142
|
switch (action) {
|
|
124
143
|
case 'session_init': {
|
|
125
|
-
const { workflowName, history } = body;
|
|
126
|
-
createSession(sessionToken, { workflowName, history });
|
|
144
|
+
const { workflowName, history, config } = body;
|
|
145
|
+
createSession(sessionToken, { workflowName, history, config });
|
|
127
146
|
|
|
128
147
|
broadcastToSession(sessionToken, {
|
|
129
148
|
type: 'cli_connected',
|
|
@@ -138,6 +157,9 @@ async function handleCliPost(req, res) {
|
|
|
138
157
|
});
|
|
139
158
|
}
|
|
140
159
|
|
|
160
|
+
// Trigger browser refetch to pick up config and latest state
|
|
161
|
+
broadcastUpdate(sessionToken);
|
|
162
|
+
|
|
141
163
|
return sendJson(res, 200, { success: true });
|
|
142
164
|
}
|
|
143
165
|
|
|
@@ -186,7 +208,7 @@ async function handleCliPost(req, res) {
|
|
|
186
208
|
}
|
|
187
209
|
|
|
188
210
|
/**
|
|
189
|
-
* Handle CLI GET (long-poll for interactions)
|
|
211
|
+
* Handle CLI GET (long-poll for interactions and config updates)
|
|
190
212
|
* Peeks at first item without removing - CLI confirms via DELETE
|
|
191
213
|
*/
|
|
192
214
|
async function handleCliGet(req, res, query) {
|
|
@@ -204,11 +226,11 @@ async function handleCliGet(req, res, query) {
|
|
|
204
226
|
const timeoutMs = Math.min(parseInt(timeout, 10), 55000);
|
|
205
227
|
const startTime = Date.now();
|
|
206
228
|
|
|
207
|
-
// Poll for pending interactions
|
|
229
|
+
// Poll for pending interactions and config updates
|
|
208
230
|
const checkInterval = setInterval(() => {
|
|
231
|
+
// Check interactions first (higher priority)
|
|
209
232
|
if (session.pendingInteractions.length > 0) {
|
|
210
233
|
clearInterval(checkInterval);
|
|
211
|
-
// Peek at first item WITHOUT removing - CLI will confirm via DELETE
|
|
212
234
|
const interaction = session.pendingInteractions[0];
|
|
213
235
|
return sendJson(res, 200, {
|
|
214
236
|
type: 'interaction_response',
|
|
@@ -216,6 +238,16 @@ async function handleCliGet(req, res, query) {
|
|
|
216
238
|
});
|
|
217
239
|
}
|
|
218
240
|
|
|
241
|
+
// Check config updates
|
|
242
|
+
if (session.pendingConfigUpdates && session.pendingConfigUpdates.length > 0) {
|
|
243
|
+
clearInterval(checkInterval);
|
|
244
|
+
const configUpdate = session.pendingConfigUpdates[0];
|
|
245
|
+
return sendJson(res, 200, {
|
|
246
|
+
type: 'config_update',
|
|
247
|
+
...configUpdate,
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
|
|
219
251
|
if (Date.now() - startTime >= timeoutMs) {
|
|
220
252
|
clearInterval(checkInterval);
|
|
221
253
|
res.writeHead(204);
|
|
@@ -230,11 +262,11 @@ async function handleCliGet(req, res, query) {
|
|
|
230
262
|
}
|
|
231
263
|
|
|
232
264
|
/**
|
|
233
|
-
* Handle CLI DELETE (confirm receipt of interaction)
|
|
234
|
-
* Removes the first pending
|
|
265
|
+
* Handle CLI DELETE (confirm receipt of interaction or config update)
|
|
266
|
+
* Removes the first pending item after CLI confirms receipt
|
|
235
267
|
*/
|
|
236
268
|
function handleCliDelete(req, res, query) {
|
|
237
|
-
const { token } = query;
|
|
269
|
+
const { token, type = 'interaction' } = query;
|
|
238
270
|
|
|
239
271
|
if (!token) {
|
|
240
272
|
return sendJson(res, 400, { error: 'Missing token' });
|
|
@@ -245,9 +277,16 @@ function handleCliDelete(req, res, query) {
|
|
|
245
277
|
return sendJson(res, 404, { error: 'Session not found' });
|
|
246
278
|
}
|
|
247
279
|
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
session.
|
|
280
|
+
if (type === 'config') {
|
|
281
|
+
// Remove the first pending config update
|
|
282
|
+
if (session.pendingConfigUpdates && session.pendingConfigUpdates.length > 0) {
|
|
283
|
+
session.pendingConfigUpdates.shift();
|
|
284
|
+
}
|
|
285
|
+
} else {
|
|
286
|
+
// Remove the first pending interaction (default)
|
|
287
|
+
if (session.pendingInteractions.length > 0) {
|
|
288
|
+
session.pendingInteractions.shift();
|
|
289
|
+
}
|
|
251
290
|
}
|
|
252
291
|
|
|
253
292
|
return sendJson(res, 200, { success: true });
|
|
@@ -318,6 +357,7 @@ function handleHistoryGet(res, token) {
|
|
|
318
357
|
return sendJson(res, 200, {
|
|
319
358
|
workflowName: session.workflowName,
|
|
320
359
|
cliConnected: session.cliConnected,
|
|
360
|
+
config: session.config || { fullAuto: false, autoSelectDelay: 20 },
|
|
321
361
|
entries: session.history,
|
|
322
362
|
});
|
|
323
363
|
}
|
|
@@ -352,6 +392,47 @@ async function handleSubmitPost(req, res, token) {
|
|
|
352
392
|
return sendJson(res, 200, { success: true });
|
|
353
393
|
}
|
|
354
394
|
|
|
395
|
+
/**
|
|
396
|
+
* Handle config update POST from browser
|
|
397
|
+
*/
|
|
398
|
+
async function handleConfigPost(req, res, token) {
|
|
399
|
+
const session = getSession(token);
|
|
400
|
+
if (!session) {
|
|
401
|
+
return sendJson(res, 404, { error: 'Session not found' });
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
if (!session.cliConnected) {
|
|
405
|
+
return sendJson(res, 503, { error: 'CLI is disconnected' });
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
const body = await parseBody(req);
|
|
409
|
+
const { fullAuto, autoSelectDelay, stop } = body;
|
|
410
|
+
|
|
411
|
+
// Build config update object
|
|
412
|
+
const configUpdate = {};
|
|
413
|
+
if (fullAuto !== undefined) configUpdate.fullAuto = fullAuto;
|
|
414
|
+
if (autoSelectDelay !== undefined) configUpdate.autoSelectDelay = autoSelectDelay;
|
|
415
|
+
if (stop !== undefined) configUpdate.stop = stop;
|
|
416
|
+
|
|
417
|
+
if (Object.keys(configUpdate).length === 0) {
|
|
418
|
+
return sendJson(res, 400, { error: 'No config fields provided' });
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// Add to pending config updates for CLI to pick up
|
|
422
|
+
if (!session.pendingConfigUpdates) {
|
|
423
|
+
session.pendingConfigUpdates = [];
|
|
424
|
+
}
|
|
425
|
+
session.pendingConfigUpdates.push(configUpdate);
|
|
426
|
+
|
|
427
|
+
// Update session config (except stop which is transient)
|
|
428
|
+
if (!stop) {
|
|
429
|
+
if (fullAuto !== undefined) session.config.fullAuto = fullAuto;
|
|
430
|
+
if (autoSelectDelay !== undefined) session.config.autoSelectDelay = autoSelectDelay;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
return sendJson(res, 200, { success: true });
|
|
434
|
+
}
|
|
435
|
+
|
|
355
436
|
/**
|
|
356
437
|
* Serve session UI
|
|
357
438
|
*/
|
|
@@ -496,6 +577,12 @@ async function handleRequest(req, res) {
|
|
|
496
577
|
return handleSubmitPost(req, res, submitMatch[1]);
|
|
497
578
|
}
|
|
498
579
|
|
|
580
|
+
// Route: Config
|
|
581
|
+
const configMatch = pathname.match(/^\/api\/config\/([^/]+)$/);
|
|
582
|
+
if (configMatch && req.method === 'POST') {
|
|
583
|
+
return handleConfigPost(req, res, configMatch[1]);
|
|
584
|
+
}
|
|
585
|
+
|
|
499
586
|
// Route: Static files
|
|
500
587
|
if (pathname === '/') {
|
|
501
588
|
const defaultToken = getDefaultSessionToken();
|