neoagent 3.2.1-beta.1 → 3.2.1-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/extensions/chrome-browser/background.mjs +318 -88
  2. package/extensions/chrome-browser/http.mjs +136 -0
  3. package/extensions/chrome-browser/protocol.mjs +511 -89
  4. package/flutter_app/lib/main_chat.dart +118 -739
  5. package/flutter_app/lib/main_controller.dart +29 -20
  6. package/flutter_app/lib/main_models.dart +3 -0
  7. package/flutter_app/lib/main_operations.dart +334 -321
  8. package/flutter_app/lib/main_settings.dart +4 -3
  9. package/flutter_app/lib/main_shared.dart +14 -11
  10. package/flutter_app/lib/src/desktop_companion_actions.dart +185 -31
  11. package/flutter_app/lib/src/desktop_companion_io.dart +319 -86
  12. package/flutter_app/windows/runner/flutter_window.cpp +143 -32
  13. package/lib/manager.js +106 -89
  14. package/lib/schema_migrations.js +67 -13
  15. package/package.json +20 -13
  16. package/runtime/paths.js +49 -5
  17. package/server/guest_agent.js +52 -30
  18. package/server/http/middleware.js +24 -0
  19. package/server/http/routes.js +4 -6
  20. package/server/public/.last_build_id +1 -1
  21. package/server/public/assets/fonts/MaterialIcons-Regular.otf +0 -0
  22. package/server/public/flutter_bootstrap.js +1 -1
  23. package/server/public/main.dart.js +30803 -30805
  24. package/server/routes/admin.js +1 -1
  25. package/server/routes/android.js +30 -34
  26. package/server/routes/browser.js +23 -15
  27. package/server/routes/desktop.js +18 -1
  28. package/server/routes/integrations.js +5 -1
  29. package/server/routes/memory.js +1 -0
  30. package/server/routes/settings.js +16 -5
  31. package/server/routes/social_reach.js +12 -3
  32. package/server/routes/social_video.js +4 -0
  33. package/server/services/ai/compaction.js +7 -2
  34. package/server/services/ai/history.js +44 -5
  35. package/server/services/ai/integrated_tools/http_request.js +8 -0
  36. package/server/services/ai/loop/agent_engine_core.js +358 -162
  37. package/server/services/ai/loop/callbacks.js +1 -0
  38. package/server/services/ai/loop/completion_judge.js +12 -0
  39. package/server/services/ai/loop/conversation_loop.js +348 -242
  40. package/server/services/ai/loop/messaging_delivery.js +129 -57
  41. package/server/services/ai/loop/model_call_guard.js +91 -0
  42. package/server/services/ai/loop/model_io.js +20 -45
  43. package/server/services/ai/loop/tool_dispatch.js +19 -8
  44. package/server/services/ai/loopPolicy.js +24 -19
  45. package/server/services/ai/model_discovery.js +227 -0
  46. package/server/services/ai/model_identity.js +71 -0
  47. package/server/services/ai/models.js +67 -162
  48. package/server/services/ai/providerRetry.js +17 -59
  49. package/server/services/ai/provider_selector.js +111 -0
  50. package/server/services/ai/providers/anthropic.js +2 -2
  51. package/server/services/ai/providers/claudeCode.js +21 -33
  52. package/server/services/ai/providers/githubCopilot.js +41 -20
  53. package/server/services/ai/providers/google.js +23 -5
  54. package/server/services/ai/providers/grok.js +4 -3
  55. package/server/services/ai/providers/grokOauth.js +19 -27
  56. package/server/services/ai/providers/nvidia.js +10 -5
  57. package/server/services/ai/providers/ollama.js +111 -84
  58. package/server/services/ai/providers/ollama_stream.js +142 -0
  59. package/server/services/ai/providers/openai.js +39 -5
  60. package/server/services/ai/providers/openaiCodex.js +11 -4
  61. package/server/services/ai/providers/openrouter.js +29 -7
  62. package/server/services/ai/providers/provider_error.js +36 -0
  63. package/server/services/ai/settings.js +26 -2
  64. package/server/services/ai/taskAnalysis.js +5 -1
  65. package/server/services/ai/terminal_reply.js +45 -0
  66. package/server/services/ai/toolEvidence.js +58 -29
  67. package/server/services/ai/tools.js +124 -111
  68. package/server/services/android/controller.js +770 -237
  69. package/server/services/android/process.js +140 -0
  70. package/server/services/android/sdk_download.js +143 -0
  71. package/server/services/android/uia.js +6 -5
  72. package/server/services/artifacts/store.js +24 -0
  73. package/server/services/browser/controller.js +736 -385
  74. package/server/services/browser/extension/gateway.js +40 -16
  75. package/server/services/browser/extension/protocol.js +12 -1
  76. package/server/services/browser/extension/provider.js +59 -47
  77. package/server/services/browser/extension/registry.js +155 -34
  78. package/server/services/cli/executor.js +62 -9
  79. package/server/services/desktop/gateway.js +41 -4
  80. package/server/services/desktop/protocol.js +3 -0
  81. package/server/services/desktop/provider.js +39 -42
  82. package/server/services/desktop/registry.js +137 -52
  83. package/server/services/integrations/figma/provider.js +78 -12
  84. package/server/services/integrations/github/common.js +11 -6
  85. package/server/services/integrations/github/provider.js +52 -53
  86. package/server/services/integrations/google/provider.js +55 -19
  87. package/server/services/integrations/home_assistant/network.js +17 -20
  88. package/server/services/integrations/home_assistant/provider.js +7 -5
  89. package/server/services/integrations/home_assistant/tools.js +17 -5
  90. package/server/services/integrations/http.js +51 -0
  91. package/server/services/integrations/manager.js +158 -53
  92. package/server/services/integrations/microsoft/provider.js +80 -13
  93. package/server/services/integrations/neoarchive/provider.js +55 -29
  94. package/server/services/integrations/neorecall/client.js +17 -10
  95. package/server/services/integrations/neorecall/provider.js +20 -11
  96. package/server/services/integrations/notion/provider.js +16 -13
  97. package/server/services/integrations/oauth_provider.js +115 -51
  98. package/server/services/integrations/slack/provider.js +98 -9
  99. package/server/services/integrations/spotify/provider.js +67 -71
  100. package/server/services/integrations/trello/provider.js +21 -7
  101. package/server/services/integrations/weather/provider.js +18 -12
  102. package/server/services/integrations/whatsapp/provider.js +76 -16
  103. package/server/services/manager.js +87 -1
  104. package/server/services/memory/embedding_index.js +20 -8
  105. package/server/services/memory/embeddings.js +151 -90
  106. package/server/services/memory/ingestion.js +50 -9
  107. package/server/services/memory/ingestion_documents.js +13 -3
  108. package/server/services/memory/manager.js +52 -19
  109. package/server/services/messaging/automation.js +84 -9
  110. package/server/services/messaging/http_platforms.js +33 -13
  111. package/server/services/messaging/inbound_queue.js +78 -24
  112. package/server/services/messaging/inbound_store.js +224 -0
  113. package/server/services/messaging/manager.js +326 -51
  114. package/server/services/messaging/typing_keepalive.js +5 -2
  115. package/server/services/network/http.js +210 -0
  116. package/server/services/network/safe_request.js +307 -0
  117. package/server/services/runtime/backends/local-vm.js +214 -66
  118. package/server/services/runtime/manager.js +17 -12
  119. package/server/services/social_reach/channels/github.js +10 -4
  120. package/server/services/social_reach/channels/reddit.js +4 -4
  121. package/server/services/social_reach/channels/rss.js +2 -2
  122. package/server/services/social_reach/channels/social_video.js +12 -7
  123. package/server/services/social_reach/channels/v2ex.js +21 -8
  124. package/server/services/social_reach/channels/x.js +2 -2
  125. package/server/services/social_reach/channels/xueqiu.js +5 -5
  126. package/server/services/social_reach/service.js +9 -6
  127. package/server/services/social_reach/utils.js +65 -14
  128. package/server/services/social_video/service.js +160 -50
  129. package/server/services/tasks/integration_runtime.js +18 -8
  130. package/server/services/tasks/runtime.js +39 -4
  131. package/server/services/voice/agentBridge.js +17 -4
  132. package/server/services/voice/bufferedLiveRelayAdapter.js +5 -0
  133. package/server/services/voice/liveSession.js +31 -0
  134. package/server/services/voice/openaiSpeech.js +33 -8
  135. package/server/services/voice/providers.js +233 -151
  136. package/server/services/voice/runtimeManager.js +118 -20
  137. package/server/services/voice/turnRunner.js +6 -0
  138. package/server/services/wearable/firmware_manifest.js +51 -13
  139. package/server/services/wearable/service.js +1 -0
  140. package/server/utils/abort.js +96 -0
  141. package/server/utils/cloud-security.js +110 -3
  142. package/server/utils/files.js +31 -0
  143. package/server/utils/image_payload.js +95 -0
  144. package/server/utils/retry.js +107 -0
@@ -1,5 +1,8 @@
1
+ 'use strict';
2
+
1
3
  const crypto = require('crypto');
2
4
  const db = require('../../db/database');
5
+ const { createAbortError } = require('../../utils/abort');
3
6
  const {
4
7
  DESKTOP_COMMANDS,
5
8
  FRAME_TYPE_VIDEO,
@@ -66,6 +69,7 @@ class DesktopCompanionRegistry {
66
69
  || DEFAULT_PRESENCE_TOUCH_INTERVAL_MS,
67
70
  );
68
71
  this.connectionsByUser = new Map();
72
+ this.closed = false;
69
73
  }
70
74
 
71
75
  _getUserMap(userId, create = false) {
@@ -199,6 +203,9 @@ class DesktopCompanionRegistry {
199
203
  }
200
204
 
201
205
  registerConnection({ userId, sessionId, ws, hello, remoteAddress = null, userAgent = null }) {
206
+ if (this.closed) {
207
+ throw new DesktopCompanionUnavailableError('Desktop companion registry is shutting down.');
208
+ }
202
209
  const record = this._upsertDeviceRecord(userId, hello, sessionId);
203
210
  const userMap = this._getUserMap(userId, true);
204
211
  const existing = userMap.get(record.deviceId);
@@ -249,11 +256,15 @@ class DesktopCompanionRegistry {
249
256
  // Only mark offline in the DB when this connection is still the active owner.
250
257
  // If a newer connection has already taken over (reconnect race), its
251
258
  // _upsertDeviceRecord already wrote status='online' and we must not clobber it.
252
- this.db.prepare(
253
- `UPDATE desktop_companion_devices
254
- SET status = 'offline', updated_at = datetime('now')
255
- WHERE user_id = ? AND device_id = ?`
256
- ).run(connection.userId, connection.deviceId);
259
+ try {
260
+ this.db.prepare(
261
+ `UPDATE desktop_companion_devices
262
+ SET status = 'offline', updated_at = datetime('now')
263
+ WHERE user_id = ? AND device_id = ?`
264
+ ).run(connection.userId, connection.deviceId);
265
+ } catch (error) {
266
+ console.warn('[DesktopCompanion] Failed to record disconnect:', error?.message);
267
+ }
257
268
  }
258
269
  }
259
270
 
@@ -300,18 +311,22 @@ class DesktopCompanionRegistry {
300
311
  const userMap = this._getUserMap(userId);
301
312
  const connection = userMap?.get(String(deviceId));
302
313
  if (!connection?.isOpen()) return;
303
- this.db.prepare(
304
- `UPDATE desktop_companion_devices
305
- SET status = 'online',
306
- last_seen_at = datetime('now'),
307
- updated_at = datetime('now')
308
- WHERE user_id = ? AND device_id = ? AND revoked_at IS NULL`
309
- ).run(userId, deviceId);
314
+ try {
315
+ this.db.prepare(
316
+ `UPDATE desktop_companion_devices
317
+ SET status = 'online',
318
+ last_seen_at = datetime('now'),
319
+ updated_at = datetime('now')
320
+ WHERE user_id = ? AND device_id = ? AND revoked_at IS NULL`
321
+ ).run(userId, deviceId);
322
+ } catch (error) {
323
+ console.warn('[DesktopCompanion] Failed to update presence:', error?.message);
324
+ }
310
325
  }
311
326
 
312
327
  isConnected(userId) {
313
328
  const userMap = this._getUserMap(userId);
314
- return userMap != null && userMap.size > 0;
329
+ return userMap != null && Array.from(userMap.values()).some((connection) => connection.isOpen());
315
330
  }
316
331
 
317
332
  getConnection(userId, deviceId) {
@@ -394,15 +409,19 @@ class DesktopCompanionRegistry {
394
409
  throw new DesktopCompanionUnavailableError();
395
410
  }
396
411
  const result = await connection.sendCommand(command, payload, options);
397
- this.touchConnection(userId, device.deviceId, {
398
- label: result?.device?.label,
399
- paused: result?.paused === true,
400
- activeDisplayId: result?.activeDisplayId || result?.device?.activeDisplayId,
401
- permissions: result?.permissions,
402
- capabilities: result?.capabilities,
403
- displays: result?.displays || result?.device?.displays,
404
- metadata: result?.device?.metadata,
405
- });
412
+ try {
413
+ this.touchConnection(userId, device.deviceId, {
414
+ label: result?.device?.label,
415
+ paused: typeof result?.paused === 'boolean' ? result.paused : null,
416
+ activeDisplayId: result?.activeDisplayId || result?.device?.activeDisplayId,
417
+ permissions: result?.permissions,
418
+ capabilities: result?.capabilities,
419
+ displays: result?.displays || result?.device?.displays,
420
+ metadata: result?.device?.metadata,
421
+ });
422
+ } catch (error) {
423
+ console.warn('[DesktopCompanion] Failed to record command result:', error?.message);
424
+ }
406
425
  return {
407
426
  ...result,
408
427
  device: this.getDeviceRecordByDeviceId(userId, device.deviceId),
@@ -429,13 +448,13 @@ class DesktopCompanionRegistry {
429
448
  };
430
449
  }
431
450
 
432
- async stopStream(userId, deviceId) {
451
+ async stopStream(userId, deviceId, options = {}) {
433
452
  const device = this.resolveDevice(userId, deviceId);
434
453
  const connection = this.getConnection(userId, device.deviceId);
435
454
  if (!connection || !connection.isOpen()) {
436
455
  throw new DesktopCompanionUnavailableError();
437
456
  }
438
- const result = await connection.sendCommand(DESKTOP_COMMANDS.STREAM_STOP, {});
457
+ const result = await connection.sendCommand(DESKTOP_COMMANDS.STREAM_STOP, {}, options);
439
458
  connection._streaming = false;
440
459
  return {
441
460
  ...result,
@@ -489,7 +508,7 @@ class DesktopCompanionRegistry {
489
508
  return { success: true, deviceId: normalizedDeviceId };
490
509
  }
491
510
 
492
- pause(userId, deviceId, paused = true) {
511
+ async pause(userId, deviceId, paused = true, options = {}) {
493
512
  const normalizedDeviceId = String(deviceId || '').trim();
494
513
  if (!normalizedDeviceId) {
495
514
  throw new DesktopCompanionUnavailableError();
@@ -500,27 +519,40 @@ class DesktopCompanionRegistry {
500
519
  if (!existing) {
501
520
  throw new DesktopCompanionUnavailableError();
502
521
  }
503
- this.db.prepare(
504
- `UPDATE desktop_companion_devices
505
- SET paused = ?, updated_at = datetime('now')
506
- WHERE user_id = ? AND device_id = ?`
507
- ).run(paused ? 1 : 0, userId, normalizedDeviceId);
508
522
  const connection = this.getConnection(userId, normalizedDeviceId);
509
- if (connection) {
510
- void connection.sendCommand('pauseControl', { paused }).catch(() => {});
523
+ if (!connection?.isOpen()) {
524
+ throw new DesktopCompanionUnavailableError();
525
+ }
526
+ const result = await connection.sendCommand(
527
+ DESKTOP_COMMANDS.PAUSE_CONTROL,
528
+ { paused },
529
+ options,
530
+ );
531
+ if (result?.success !== false) {
532
+ try {
533
+ this.db.prepare(
534
+ `UPDATE desktop_companion_devices
535
+ SET paused = ?, updated_at = datetime('now')
536
+ WHERE user_id = ? AND device_id = ?`
537
+ ).run(paused ? 1 : 0, userId, normalizedDeviceId);
538
+ } catch (error) {
539
+ console.warn('[DesktopCompanion] Failed to record pause state:', error?.message);
540
+ }
511
541
  }
512
542
  return {
513
- success: true,
543
+ ...result,
544
+ success: result?.success !== false,
514
545
  deviceId: normalizedDeviceId,
515
546
  paused,
516
547
  };
517
548
  }
518
549
 
519
550
  closeAll() {
520
- for (const userMap of this.connectionsByUser.values()) {
521
- for (const connection of userMap.values()) {
522
- connection.close('server shutdown');
523
- }
551
+ this.closed = true;
552
+ const connections = Array.from(this.connectionsByUser.values())
553
+ .flatMap((userMap) => Array.from(userMap.values()));
554
+ for (const connection of connections) {
555
+ connection.close('server shutdown');
524
556
  }
525
557
  this.connectionsByUser.clear();
526
558
  }
@@ -555,24 +587,37 @@ class DesktopCompanionConnection {
555
587
  this.lastPongAt = Date.now();
556
588
  this.lastPresenceTouchAt = 0;
557
589
  this.heartbeatTimer = null;
590
+ this.closed = false;
558
591
 
559
- ws.on('message', (data) => this._handleMessage(data));
592
+ ws.on('message', (data) => {
593
+ try {
594
+ this._handleMessage(data);
595
+ } catch (error) {
596
+ try { ws.terminate(); } catch {}
597
+ this._closePending(error);
598
+ }
599
+ });
560
600
  ws.on('pong', () => {
561
601
  this.lastPongAt = Date.now();
562
602
  this.touchPresence();
563
603
  });
564
604
  ws.on('close', () => this._closePending(new DesktopCompanionUnavailableError('Desktop companion disconnected.')));
565
- ws.on('error', (error) => this._closePending(error));
605
+ ws.on('error', (error) => {
606
+ try { ws.terminate(); } catch {}
607
+ this._closePending(error);
608
+ });
566
609
  this._startHeartbeat();
567
610
  }
568
611
 
569
612
  isOpen() {
570
- return this.ws && this.ws.readyState === 1;
613
+ return !this.closed && this.ws && this.ws.readyState === 1;
571
614
  }
572
615
 
573
616
  close(reason) {
617
+ const wasOpen = this.isOpen();
618
+ this.closed = true;
574
619
  try {
575
- if (this.isOpen()) {
620
+ if (wasOpen) {
576
621
  this.ws.close(1000, String(reason || 'closing').slice(0, 120));
577
622
  }
578
623
  } catch {}
@@ -602,19 +647,51 @@ class DesktopCompanionConnection {
602
647
  return Promise.reject(new DesktopCompanionUnavailableError());
603
648
  }
604
649
  const id = crypto.randomUUID();
605
- const timeoutMs = Number(options.timeoutMs || this.timeoutMs);
650
+ const requestedTimeout = Number(options.timeoutMs || this.timeoutMs);
651
+ const timeoutMs = Number.isFinite(requestedTimeout)
652
+ ? Math.min(30 * 60 * 1000, Math.max(100, requestedTimeout))
653
+ : DEFAULT_COMMAND_TIMEOUT_MS;
606
654
  const message = createDesktopCommandMessage(id, command, payload);
607
655
  return new Promise((resolve, reject) => {
608
- const timer = setTimeout(() => {
656
+ const signal = options.signal || null;
657
+ const sendCancellation = () => {
658
+ if (!this.isOpen() || command === DESKTOP_COMMANDS.CANCEL_COMMAND) return;
659
+ try {
660
+ this.ws.send(JSON.stringify(createDesktopCommandMessage(
661
+ crypto.randomUUID(),
662
+ DESKTOP_COMMANDS.CANCEL_COMMAND,
663
+ { commandId: id },
664
+ )));
665
+ } catch {}
666
+ };
667
+ const cleanup = () => {
668
+ clearTimeout(timer);
669
+ signal?.removeEventListener('abort', onAbort);
609
670
  this.pending.delete(id);
610
- reject(new Error(`Desktop companion command timed out: ${command}`));
671
+ };
672
+ const onAbort = () => {
673
+ cleanup();
674
+ sendCancellation();
675
+ reject(createAbortError(signal, `Desktop companion command aborted: ${command}`));
676
+ };
677
+ const timer = setTimeout(() => {
678
+ cleanup();
679
+ sendCancellation();
680
+ const error = new Error(`Desktop companion command timed out: ${command}`);
681
+ error.code = 'DESKTOP_COMPANION_COMMAND_TIMEOUT';
682
+ reject(error);
611
683
  }, timeoutMs);
612
- this.pending.set(id, { resolve, reject, timer, command });
684
+ timer.unref?.();
685
+ if (signal?.aborted) {
686
+ onAbort();
687
+ return;
688
+ }
689
+ signal?.addEventListener('abort', onAbort, { once: true });
690
+ this.pending.set(id, { resolve, reject, timer, command, signal, onAbort });
613
691
  try {
614
692
  this.ws.send(JSON.stringify(message));
615
693
  } catch (error) {
616
- clearTimeout(timer);
617
- this.pending.delete(id);
694
+ cleanup();
618
695
  reject(error);
619
696
  }
620
697
  });
@@ -636,10 +713,14 @@ class DesktopCompanionConnection {
636
713
 
637
714
  if (message.type === 'event') {
638
715
  if (message.event === 'statusChanged' || message.event === 'permissionsChanged') {
639
- this.registry.touchConnection(this.userId, this.deviceId, {
640
- ...message.payload,
641
- metadata: message.payload?.metadata,
642
- });
716
+ try {
717
+ this.registry.touchConnection(this.userId, this.deviceId, {
718
+ ...message.payload,
719
+ metadata: message.payload?.metadata,
720
+ });
721
+ } catch (error) {
722
+ console.warn('[DesktopCompanion] Failed to record device event:', error?.message);
723
+ }
643
724
  }
644
725
  return;
645
726
  }
@@ -648,6 +729,7 @@ class DesktopCompanionConnection {
648
729
  const pending = this.pending.get(message.id);
649
730
  if (!pending) return;
650
731
  clearTimeout(pending.timer);
732
+ pending.signal?.removeEventListener('abort', pending.onAbort);
651
733
  this.pending.delete(message.id);
652
734
  if (message.ok === false) {
653
735
  const error = new Error(String(message.error || `Desktop companion command failed: ${pending.command}`));
@@ -655,16 +737,18 @@ class DesktopCompanionConnection {
655
737
  pending.reject(error);
656
738
  return;
657
739
  }
658
- pending.resolve(message.payload || {});
740
+ pending.resolve(message.payload ?? {});
659
741
  }
660
742
 
661
743
  _closePending(error) {
744
+ this.closed = true;
662
745
  if (this.heartbeatTimer) {
663
746
  clearInterval(this.heartbeatTimer);
664
747
  this.heartbeatTimer = null;
665
748
  }
666
749
  for (const pending of this.pending.values()) {
667
750
  clearTimeout(pending.timer);
751
+ pending.signal?.removeEventListener('abort', pending.onAbort);
668
752
  pending.reject(error);
669
753
  }
670
754
  this.pending.clear();
@@ -702,5 +786,6 @@ class DesktopCompanionConnection {
702
786
  }
703
787
 
704
788
  module.exports = {
789
+ DesktopCompanionConnection,
705
790
  DesktopCompanionRegistry,
706
791
  };
@@ -158,25 +158,88 @@ function figmaUrl(path, query) {
158
158
  return url.toString();
159
159
  }
160
160
 
161
- async function figmaRequest(credentials, { method = 'GET', path, query, body }) {
162
- return fetchJson(
161
+ function expiresAtFromSeconds(expiresIn) {
162
+ return new Date(
163
+ Date.now() + Math.max(1, Number(expiresIn) || 3600) * 1000,
164
+ ).toISOString();
165
+ }
166
+
167
+ function tokenExpiresSoon(credentials) {
168
+ const expiresAt = Date.parse(String(credentials?.expires_at || ''));
169
+ return Number.isFinite(expiresAt) && expiresAt <= Date.now() + 60 * 1000;
170
+ }
171
+
172
+ async function refreshFigmaCredentials(credentials, signal) {
173
+ const refreshToken = String(credentials?.refresh_token || '').trim();
174
+ if (!refreshToken) {
175
+ throw new Error('Figma refresh token is missing. Reconnect this integration account.');
176
+ }
177
+ const config = resolveFigmaOAuthConfig();
178
+ const basic = Buffer.from(`${config.clientId}:${config.clientSecret}`).toString(
179
+ 'base64',
180
+ );
181
+ const token = await fetchJson(
182
+ 'https://api.figma.com/v1/oauth/token',
183
+ {
184
+ method: 'POST',
185
+ headers: { Authorization: `Basic ${basic}` },
186
+ form: {
187
+ grant_type: 'refresh_token',
188
+ refresh_token: refreshToken,
189
+ },
190
+ signal,
191
+ },
192
+ { serviceName: 'Figma token refresh' },
193
+ );
194
+ if (!String(token?.access_token || '').trim()) {
195
+ throw new Error('Figma token refresh did not return an access token.');
196
+ }
197
+ return {
198
+ ...credentials,
199
+ access_token: token.access_token,
200
+ refresh_token: token.refresh_token || refreshToken,
201
+ token_type: token.token_type || credentials.token_type || 'bearer',
202
+ expires_in: token.expires_in,
203
+ expires_at: expiresAtFromSeconds(token.expires_in),
204
+ };
205
+ }
206
+
207
+ async function figmaRequest(context, { method = 'GET', path, query, body }) {
208
+ const { signal } = context;
209
+ let credentials = context.credentials;
210
+ if (tokenExpiresSoon(credentials)) {
211
+ credentials = await refreshFigmaCredentials(credentials, signal);
212
+ context.updateCredentials(credentials);
213
+ }
214
+
215
+ const performRequest = (activeCredentials) => fetchJson(
163
216
  figmaUrl(path, query),
164
217
  {
165
218
  method: String(method || 'GET').toUpperCase(),
166
- headers: { Authorization: `Bearer ${credentials.access_token}` },
219
+ headers: { Authorization: `Bearer ${activeCredentials.access_token}` },
167
220
  ...(body === undefined ? {} : { json: body }),
221
+ signal,
168
222
  },
169
223
  { serviceName: 'Figma' },
170
224
  );
225
+
226
+ try {
227
+ return await performRequest(credentials);
228
+ } catch (error) {
229
+ if (error?.status !== 401 || !credentials.refresh_token) throw error;
230
+ credentials = await refreshFigmaCredentials(credentials, signal);
231
+ context.updateCredentials(credentials);
232
+ return performRequest(credentials);
233
+ }
171
234
  }
172
235
 
173
- async function executeFigmaTool(toolName, args, { credentials }) {
236
+ async function executeFigmaTool(toolName, args, context) {
174
237
  switch (toolName) {
175
238
  case 'figma_get_me':
176
- return { result: await figmaRequest(credentials, { path: '/v1/me' }) };
239
+ return { result: await figmaRequest(context, { path: '/v1/me' }) };
177
240
  case 'figma_get_file':
178
241
  return {
179
- result: await figmaRequest(credentials, {
242
+ result: await figmaRequest(context, {
180
243
  path: `/v1/files/${encodeURIComponent(requireText(args.file_key, 'file_key'))}`,
181
244
  query: {
182
245
  ids: args.ids || undefined,
@@ -186,14 +249,14 @@ async function executeFigmaTool(toolName, args, { credentials }) {
186
249
  };
187
250
  case 'figma_get_file_nodes':
188
251
  return {
189
- result: await figmaRequest(credentials, {
252
+ result: await figmaRequest(context, {
190
253
  path: `/v1/files/${encodeURIComponent(requireText(args.file_key, 'file_key'))}/nodes`,
191
254
  query: { ids: requireText(args.ids, 'ids') },
192
255
  }),
193
256
  };
194
257
  case 'figma_get_file_images':
195
258
  return {
196
- result: await figmaRequest(credentials, {
259
+ result: await figmaRequest(context, {
197
260
  path: `/v1/images/${encodeURIComponent(requireText(args.file_key, 'file_key'))}`,
198
261
  query: {
199
262
  ids: requireText(args.ids, 'ids'),
@@ -204,13 +267,13 @@ async function executeFigmaTool(toolName, args, { credentials }) {
204
267
  };
205
268
  case 'figma_get_comments':
206
269
  return {
207
- result: await figmaRequest(credentials, {
270
+ result: await figmaRequest(context, {
208
271
  path: `/v1/files/${encodeURIComponent(requireText(args.file_key, 'file_key'))}/comments`,
209
272
  }),
210
273
  };
211
274
  case 'figma_post_comment':
212
275
  return {
213
- result: await figmaRequest(credentials, {
276
+ result: await figmaRequest(context, {
214
277
  method: 'POST',
215
278
  path: `/v1/files/${encodeURIComponent(requireText(args.file_key, 'file_key'))}/comments`,
216
279
  body: {
@@ -221,7 +284,7 @@ async function executeFigmaTool(toolName, args, { credentials }) {
221
284
  };
222
285
  case 'figma_api_request':
223
286
  return {
224
- result: await figmaRequest(credentials, {
287
+ result: await figmaRequest(context, {
225
288
  method: args.method,
226
289
  path: requireText(args.path, 'path'),
227
290
  query: args.query,
@@ -263,7 +326,7 @@ function createFigmaProvider() {
263
326
  appId: app.id,
264
327
  };
265
328
  },
266
- async finishOAuth({ code, app }) {
329
+ async finishOAuth({ code, app, signal }) {
267
330
  const config = resolveFigmaOAuthConfig();
268
331
  const basic = Buffer.from(`${config.clientId}:${config.clientSecret}`).toString(
269
332
  'base64',
@@ -280,6 +343,7 @@ function createFigmaProvider() {
280
343
  code,
281
344
  grant_type: 'authorization_code',
282
345
  },
346
+ signal,
283
347
  },
284
348
  { serviceName: 'Figma' },
285
349
  );
@@ -290,6 +354,7 @@ function createFigmaProvider() {
290
354
  headers: {
291
355
  Authorization: `Bearer ${token.access_token}`,
292
356
  },
357
+ signal,
293
358
  },
294
359
  { serviceName: 'Figma' },
295
360
  );
@@ -307,6 +372,7 @@ function createFigmaProvider() {
307
372
  access_token: token.access_token,
308
373
  refresh_token: token.refresh_token,
309
374
  expires_in: token.expires_in,
375
+ expires_at: expiresAtFromSeconds(token.expires_in),
310
376
  token_type: token.token_type,
311
377
  scope: token.scope,
312
378
  },
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const crypto = require('crypto');
4
+ const { fetchResponseText } = require('../http');
4
5
 
5
6
  function base64UrlSha256(value) {
6
7
  return crypto
@@ -46,15 +47,19 @@ async function githubApiRequest(auth, options = {}) {
46
47
  headers['Content-Type'] = 'application/json';
47
48
  }
48
49
 
49
- const response = await fetch(url.toString(), {
50
- method,
51
- headers,
52
- body: body ? JSON.stringify(body) : undefined,
53
- });
50
+ const { response, text: rawBody } = await fetchResponseText(
51
+ url.toString(),
52
+ {
53
+ method,
54
+ headers,
55
+ body: body ? JSON.stringify(body) : undefined,
56
+ signal: options.signal || auth?.signal,
57
+ },
58
+ { serviceName: 'GitHub API' },
59
+ );
54
60
 
55
61
  let data = null;
56
62
  if (response.status !== 204 && response.status !== 205) {
57
- const rawBody = await response.text();
58
63
  if (rawBody.trim()) {
59
64
  try {
60
65
  data = JSON.parse(rawBody);