@vibedev-si/dsh-island 0.1.0 → 0.3.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/index.js CHANGED
@@ -5,7 +5,7 @@
5
5
  * 持有设置并下发给岛屿,把 VibeDev 的会话、审批和提问转给岛屿,以及给插件页提供同源路由。
6
6
  * 协议见仓库的 protocol/README.md。
7
7
  *
8
- * 岛屿只能由这里拉起:它没有托盘、没有自己的设置窗口,单独启动会直接退出。
8
+ * 岛屿只能由这里拉起:它没有托盘,单独启动会直接退出。
9
9
  *
10
10
  * 这里只做接线。能脱离宿主算出来的东西各在自己的模块里,并有单测:
11
11
  * sessions.js(会话列表与通知)、requests.js(审批与提问的文案)、translate.js、
@@ -13,12 +13,20 @@
13
13
  */
14
14
  import { existsSync, readFileSync } from 'node:fs'
15
15
  import { readFile, writeFile } from 'node:fs/promises'
16
- import { arch as osArch, release as osRelease } from 'node:os'
16
+ import { arch as osArch, homedir, release as osRelease } from 'node:os'
17
17
  import { createInterface } from 'node:readline'
18
18
  import { basename, dirname, join } from 'node:path'
19
19
  import { fileURLToPath } from 'node:url'
20
20
  import { LOG_FILE, createLog } from './log.js'
21
- import { defaultsKeepingPresets, loadSettings, normalize, saveSettings, settingsPath } from './settings.js'
21
+ import {
22
+ applyPatch,
23
+ defaultsKeepingPresets,
24
+ loadSettings,
25
+ nativeSettingsPatch,
26
+ normalize,
27
+ saveSettings,
28
+ settingsPath,
29
+ } from './settings.js'
22
30
  import { islandRoutes } from './routes.js'
23
31
  import { loadChangelog } from './changelog.js'
24
32
  import { createSessionBook, doneNotice, errorItem, islandSurface, sessionsForIsland } from './sessions.js'
@@ -27,16 +35,23 @@ import { closeMessage, createAttention, showMessage, withWaiting } from './atten
27
35
  import { ANONYMOUS_PROVIDERS, translateWith } from './translate.js'
28
36
  import { createPageEvents } from './events.js'
29
37
  import { createSelectionRelay } from './selection.js'
30
- import { createApprovalHolds, HAND_BACK_MS, isDangerous, isFullAccess } from './approvals.js'
38
+ import { createApprovalHolds, createForegroundRecheck, HAND_BACK_MS, isDangerous, isFullAccess } from './approvals.js'
39
+ import { createToolCallBook, structuredQuestions, validatedAnswers } from './approval-details.js'
31
40
  import { createOutbox, mediaTypeOf, promptText, sendRequest } from './outbox.js'
32
41
  import { createIslandItems } from './island-items.js'
33
42
  import { diagnosticsFileName, diagnosticsReport } from './diagnostics.js'
34
43
  import { wechatSummary } from './wechat.js'
35
44
  import { executableCandidates, missingExecutableMessage } from './executable.js'
45
+ import { devProgramDir, revealCommand, systemLabel } from './platform.js'
46
+ import { featuresOf } from './features.js'
36
47
  import { createContributions } from './contributions.js'
48
+ import { createDisplays } from './contributor-display.js'
49
+ import { createRecentBook } from './recent.js'
50
+ import { createOpeners } from './openers.js'
51
+ import { contributorEntry } from './contributor-entry.js'
52
+ import { createAccountUsagePoll, readAccountUsageRoute } from './usage-host.js'
37
53
 
38
54
  const PROTOCOL_VERSION = 1
39
- const APP_DIR_NAME = 'VibeDev'
40
55
  /** 崩溃后最多重启几次,以及这些重启要在多久之内。 */
41
56
  const MAX_RESTARTS = 3
42
57
  const RESTART_WINDOW_MS = 5 * 60_000
@@ -109,9 +124,9 @@ function islandExecutableCandidates(config) {
109
124
  return executableCandidates({
110
125
  configured: config?.executable,
111
126
  platform: process.platform,
127
+ arch: process.arch,
112
128
  pluginDir: PLUGIN_DIRECTORY,
113
- localAppData: process.env.LOCALAPPDATA ?? join(process.env.USERPROFILE ?? '', 'AppData', 'Local'),
114
- appDirName: APP_DIR_NAME,
129
+ devDir: devProgramDir({ platform: process.platform, env: process.env, home: homedir() }),
115
130
  })
116
131
  }
117
132
 
@@ -191,6 +206,20 @@ export function apply(ctx, config) {
191
206
  let selectionSeen = false
192
207
  /** 岛上正在等用户决定的审批(在小岛上直接批准)。 */
193
208
  const holds = createApprovalHolds({ setTimer: later, clearTimer: cancel })
209
+ const toolCalls = createToolCallBook()
210
+ let managedRevision = 0
211
+ let nextManagedCard = 1
212
+ let managedTransportClosed = false
213
+ const managedHolds = createApprovalHolds({
214
+ setTimer: later,
215
+ clearTimer: cancel,
216
+ onPendingChange: createForegroundRecheck({
217
+ setTimer: later,
218
+ clearTimer: cancel,
219
+ check: managedForegroundSafe,
220
+ onUnsafe: () => handBackManaged(),
221
+ }),
222
+ })
194
223
  /** 发送到会话:等页面来取的内容,以及每个页面动作是发给哪条会话的。 */
195
224
  const outbox = createOutbox()
196
225
  const sendsBySeq = new Map()
@@ -224,11 +253,17 @@ export function apply(ctx, config) {
224
253
  */
225
254
  const contributionAllowed = (plugin) =>
226
255
  settings.contrib?.enabled !== false && !(settings.contrib?.blocked ?? []).includes(plugin)
256
+ /** 每个插件在小岛上的名字和图标(插件自己报的,或者认得的 VibeDev 插件的默认值)。 */
257
+ const displays = createDisplays()
258
+ const displayOf = (plugin) => displays.of(plugin)
259
+ /** 通知上的「查看」:岛上点了之后调回插件。 */
260
+ const openers = createOpeners({ log })
227
261
  const islandItems = createIslandItems({
228
262
  send: (method, params) => {
229
263
  if (ready) notify(method, params)
230
264
  },
231
265
  allowed: contributionAllowed,
266
+ displayOf,
232
267
  setTimer: later,
233
268
  clearTimer: cancel,
234
269
  log,
@@ -243,19 +278,35 @@ export function apply(ctx, config) {
243
278
  cancel,
244
279
  log,
245
280
  allowed: contributionAllowed,
281
+ displayOf,
282
+ })
283
+ /** 别的插件的「最近生成」(`contributor(名字).recent`)。 */
284
+ const recentBook = createRecentBook({
285
+ send: (method, params) => {
286
+ if (!ready) return false
287
+ notify(method, params)
288
+ return true
289
+ },
290
+ displayOf,
291
+ allowed: contributionAllowed,
292
+ log,
246
293
  })
247
- /** 放过东西的插件(两本账合起来),设置页上每个一行开关。 */
294
+ /** 放过东西的插件(几本账合起来),设置页上每个一行开关。 */
248
295
  const contributorSummary = () => {
249
296
  const merged = new Map()
250
- for (const item of [...islandItems.summary(), ...pluginTasks.summary()]) {
297
+ for (const item of [...islandItems.summary(), ...pluginTasks.summary(), ...recentBook.summary()]) {
251
298
  const known = merged.get(item.name)
252
299
  merged.set(item.name, { name: item.name, items: (known?.items ?? 0) + item.items })
253
300
  }
254
301
  return Array.from(merged.values()).map((item) => ({ ...item, blocked: !contributionAllowed(item.name) }))
255
302
  }
256
303
 
304
+ const nativeSettingsAvailable = () => handle !== undefined && ready && islandCapabilities.includes('native-settings')
305
+
257
306
  const status = () => ({
258
307
  running: handle !== undefined && ready,
308
+ nativeSettings: nativeSettingsAvailable(),
309
+ nativeSettingsExpected: process.platform === 'win32' && process.arch === 'x64',
259
310
  configured: executable !== undefined,
260
311
  executable,
261
312
  version: islandVersion,
@@ -266,6 +317,9 @@ export function apply(ctx, config) {
266
317
  lastExit,
267
318
  lastError,
268
319
  settingsPath: settingsPath(),
320
+ // 这个系统上的小岛有哪些要靠系统接口的功能:插件页不显示没有的设置。
321
+ platform: process.platform,
322
+ features: featuresOf({ reported: islandFeatures, platform: process.platform }),
269
323
  shortcuts: shortcutStatus,
270
324
  qq: qqStatus,
271
325
  // 微信:原始状态之外附上给页面直接显示的几句话。
@@ -304,6 +358,20 @@ export function apply(ctx, config) {
304
358
  const replyTo = (id, result) => send({ id, result })
305
359
  const failRequest = (id, code, message) => send({ id, error: { code, message } })
306
360
 
361
+ let usageConnection
362
+ const usagePoll = createAccountUsagePoll({
363
+ read: (...args) => (usageConnection === undefined ? undefined : readAccountUsageRoute(usageConnection, ...args)),
364
+ publish: (snapshot) => {
365
+ if (ready && !managedTransportClosed) notify('usage/snapshot', snapshot)
366
+ },
367
+ later,
368
+ cancel,
369
+ })
370
+ const reconcileUsagePoll = () =>
371
+ usagePoll.setEnabled(
372
+ usageConnection !== undefined && ready && !managedTransportClosed && islandCapabilities.includes('account-usage'),
373
+ )
374
+
307
375
  /** 向岛屿发一条请求。成功时得到它的结果;失败或超时得到 `{ error: { message } }`。 */
308
376
  const request = (method, params, timeoutMs = REQUEST_TIMEOUT_MS) =>
309
377
  new Promise((resolve) => {
@@ -335,6 +403,8 @@ export function apply(ctx, config) {
335
403
  const attention = createAttention()
336
404
  /** 岛屿握手时报的能力。旧版岛屿没有 `attention`,只认审批卡片。 */
337
405
  let islandCapabilities = Array.of()
406
+ /** 握手时岛屿报的「这个系统上有的功能」(features.js);旧版岛屿不报,是 undefined。 */
407
+ let islandFeatures
338
408
  /** 已经异步查过标题的会话,每个只查一次。 */
339
409
  const titleLookups = new Set()
340
410
  /** 已经放到岛上的任务行:id -> 上次发出去的内容。 */
@@ -403,6 +473,8 @@ export function apply(ctx, config) {
403
473
 
404
474
  /** 岛屿认不认识「等你处理」的列表;旧版只认审批卡片。 */
405
475
  const attentionCapable = () => islandCapabilities.includes('attention')
476
+ const managedApprovalEngine = () => islandCapabilities.includes('approval-details')
477
+ const managedQuestionEngine = () => islandCapabilities.includes('question-answers')
406
478
  const selectionCapable = () => islandCapabilities.includes('selection')
407
479
 
408
480
  /** 在岛上挂一条「等你处理」,并让会话页把那条会话归到「等你处理」里。 */
@@ -460,8 +532,21 @@ export function apply(ctx, config) {
460
532
  }
461
533
 
462
534
  const save = async (next) => {
463
- settings = normalize(next)
464
- saveSettings(settings)
535
+ const previous = settings
536
+ const saved = normalize(next)
537
+ saveSettings(saved)
538
+ settings = saved
539
+ if (
540
+ (previous.sessions.approveOnIsland && !settings.sessions.approveOnIsland) ||
541
+ (previous.sessions.decideOnIsland && !settings.sessions.decideOnIsland) ||
542
+ (previous.sessions.notifyOnQuestion && !settings.sessions.notifyOnQuestion)
543
+ ) {
544
+ managedRevision += 1
545
+ managedHolds.releaseWhere(({ kind }) => !managedActionEnabled(kind), 'timeout')
546
+ for (const item of attention.list()) {
547
+ if (item.id.startsWith('managed-') && !managedReminderEnabled(item.kind)) closeAttention(item.id)
548
+ }
549
+ }
465
550
  pushSettings()
466
551
 
467
552
  // 「显示会话状态」「显示运行中的任务」可能刚被打开或关掉:马上按新的设置重发。
@@ -469,6 +554,7 @@ export function apply(ctx, config) {
469
554
  // 刚被关掉的插件(或者整个入口关了):它们放在岛上的东西撤下来。
470
555
  for (const { name } of islandItems.summary()) if (!contributionAllowed(name)) islandItems.clear(name)
471
556
  pluginTasks.refresh()
557
+ recentBook.refresh()
472
558
  // 深浅的设置可能刚改了。
473
559
  pushTheme()
474
560
  log('settings saved')
@@ -531,6 +617,29 @@ export function apply(ctx, config) {
531
617
 
532
618
  /** 岛屿发来的请求(要回复的)。 */
533
619
  const handleRequest = (id, method, params) => {
620
+ if (
621
+ method === 'settings/change' &&
622
+ ready &&
623
+ !managedTransportClosed &&
624
+ (nativeSettingsAvailable() || managedApprovalEngine() || managedQuestionEngine())
625
+ ) {
626
+ const patch = nativeSettingsPatch(params)
627
+ if (patch === undefined) {
628
+ failRequest(id, -32602, 'Invalid native settings patch')
629
+ return
630
+ }
631
+ const current = handle
632
+ void save(applyPatch(settings, patch)).then(
633
+ (saved) => {
634
+ if (handle === current) replyTo(id, saved)
635
+ },
636
+ () => {
637
+ log('saving native approval settings failed')
638
+ if (handle === current) failRequest(id, -32603, 'Could not save native approval settings')
639
+ },
640
+ )
641
+ return
642
+ }
534
643
  // 岛屿要用 VibeDev 的翻译通道。失败时明确报错,让岛屿退回本地密钥。
535
644
  if (method === 'translate') {
536
645
  // 不把用户的文字写进日志,只记长度。
@@ -550,6 +659,8 @@ export function apply(ctx, config) {
550
659
  }
551
660
 
552
661
  const onReady = (params) => {
662
+ const current = handle
663
+ if (current === undefined) return
553
664
  ready = true
554
665
  startedAt = new Date().toISOString()
555
666
  islandVersion = params?.version
@@ -558,6 +669,7 @@ export function apply(ctx, config) {
558
669
  // hostExecutable:岛屿据此认出 VibeDev 的窗口,点「去处理」时把它带到前台。
559
670
  void request('initialize', { protocol: PROTOCOL_VERSION, settings, hostExecutable: process.execPath }).then(
560
671
  (result) => {
672
+ if (handle !== current) return
561
673
  log(`initialize answered: ${JSON.stringify(result)}`)
562
674
  if (result?.error !== undefined) {
563
675
  lastError = String(result.error?.message ?? result.error)
@@ -571,11 +683,14 @@ export function apply(ctx, config) {
571
683
  return
572
684
  }
573
685
  islandCapabilities = Array.isArray(result?.capabilities) ? result.capabilities : Array.of()
686
+ islandFeatures = Array.isArray(result?.features) ? result.features : undefined
687
+ reconcileUsagePoll()
574
688
  // 岛屿是新起来的,它那边什么都没有:把还在等的事重新挂上去。
575
689
  for (const item of attention.visible()) notify(...showMessage(item, attentionCapable()))
576
690
  // 别的插件放的东西:新起来的岛屿上还没有。
577
691
  islandItems.replay()
578
692
  pluginTasks.islandStarted()
693
+ recentBook.islandStarted()
579
694
  sentScheme = undefined
580
695
  pushTheme()
581
696
  // 岛屿刚连上:页面里还选着的文字再给它一次,不用等用户重新选。
@@ -608,7 +723,8 @@ export function apply(ctx, config) {
608
723
  break
609
724
  }
610
725
  closeAttentionFor(sessionId, ['error'])
611
- // 这条会话在岛上等着的审批:用户要去 VibeDev 处理了,交给 VibeDev 的界面。
726
+ handBackManaged('open')
727
+ // 这条会话在旧岛屿上等着的审批也交给 VibeDev 的界面。
612
728
  const handed = holds.decideForSession(sessionId, 'open')
613
729
  if (handed > 0) log(`handed ${handed} approval(s) of ${sessionId} back to VibeDev`)
614
730
  const seq = pageEvents.publish('open-session', { sessionId })
@@ -617,16 +733,19 @@ export function apply(ctx, config) {
617
733
  }
618
734
  // 岛屿页头的齿轮:让开着的页面切到插件页,小岛的设置都在那里。
619
735
  case 'settings/open': {
736
+ handBackManaged('open')
620
737
  const seq = pageEvents.publish('open-settings', Object.freeze({ panel: 'plugins' }))
621
738
  log(`settings open requested (event ${seq}, ${pageEvents.waiting} page(s) were listening)`)
622
739
  break
623
740
  }
624
- // 岛上的一条「等你处理」被点了。是否放行、怎么回答仍在 VibeDev 里决定。
625
741
  case 'attention/decide':
626
742
  case 'approval/decide': {
627
- log(`island attention: ${JSON.stringify(params)}`)
628
743
  const item = attention.get(params?.id)
629
744
  if (item === undefined) break
745
+ if (managedHolds.has(item.id)) {
746
+ if (method === 'attention/decide') void decideManaged(item, params)
747
+ break
748
+ }
630
749
  const decision = params?.decision
631
750
  // 岛上扣着的审批:用户在岛上允许或拒绝了,或者要回 VibeDev 处理。
632
751
  if ((decision === 'allow' || decision === 'deny' || decision === 'open') && holds.decide(item.id, decision))
@@ -666,6 +785,12 @@ export function apply(ctx, config) {
666
785
  )
667
786
  break
668
787
  }
788
+ // 岛上点了一条最近生成,或者通知上的「查看」:把 VibeDev 带到前台由岛屿自己做,这里调回放它的插件。
789
+ case 'contrib/open': {
790
+ const id = typeof params?.id === 'string' ? params.id : ''
791
+ if (!recentBook.open(id) && !openers.run(id)) log(`contrib/open: nothing to open for ${JSON.stringify(id)}`)
792
+ break
793
+ }
669
794
  case 'state/error':
670
795
  lastError = JSON.stringify(params)
671
796
  log(`island reported an error: ${lastError}`)
@@ -683,10 +808,11 @@ export function apply(ctx, config) {
683
808
  let message
684
809
  try {
685
810
  message = JSON.parse(line)
686
- } catch (error) {
687
- log(`dropped a malformed line: ${error}`)
811
+ } catch {
812
+ log('dropped a malformed protocol line')
688
813
  return
689
814
  }
815
+ if (message === null || typeof message !== 'object' || Array.isArray(message)) return
690
816
  if (message.id !== undefined && message.method === undefined) {
691
817
  const resolve = pendingReplies.get(message.id)
692
818
  if (resolve === undefined) return
@@ -703,12 +829,16 @@ export function apply(ctx, config) {
703
829
 
704
830
  const onExit = (outcome) => {
705
831
  ready = false
832
+ reconcileUsagePoll()
706
833
  handle = undefined
707
834
  lastExit = outcome
708
835
  // 下一个岛屿可能是另一个版本:握手之前按最保守的方式发。
709
836
  islandCapabilities = Array.of()
837
+ islandFeatures = undefined
710
838
  for (const resolve of pendingReplies.values()) resolve({ error: { message: 'island exited' } })
711
839
  pendingReplies.clear()
840
+ managedTransportClosed = true
841
+ handBackManaged()
712
842
  // 岛上扣着的审批没人能在岛上答了:马上交回 VibeDev,别让它等满 60 秒。
713
843
  holds.releaseAll('timeout')
714
844
  log(`island exited: ${JSON.stringify(outcome)}`)
@@ -760,7 +890,20 @@ export function apply(ctx, config) {
760
890
  lastError = undefined
761
891
  log(`island spawned: ${executable}`)
762
892
 
763
- if (handle.stdout) createInterface({ input: handle.stdout, crlfDelay: Infinity }).on('line', handleLine)
893
+ if (handle.stdout) {
894
+ const current = handle
895
+ managedTransportClosed = false
896
+ createInterface({ input: current.stdout, crlfDelay: Infinity })
897
+ .on('line', (line) => {
898
+ if (handle === current) handleLine(line)
899
+ })
900
+ .once('close', () => {
901
+ if (handle !== current) return
902
+ managedTransportClosed = true
903
+ reconcileUsagePoll()
904
+ handBackManaged()
905
+ })
906
+ }
764
907
  // 标准错误也按行读:按块记的话,一行会被拆开,几行又会粘在一起。
765
908
  if (handle.stderr) {
766
909
  createInterface({ input: handle.stderr, crlfDelay: Infinity }).on('line', (line) => log(`island stderr: ${line}`))
@@ -771,6 +914,8 @@ export function apply(ctx, config) {
771
914
  /** 先请岛屿自己退出,宽限期到了才强制结束。返回时它已经不在了(或已经下了强制结束的命令)。 */
772
915
  const stopIsland = async () => {
773
916
  desiredRunning = false
917
+ usagePoll.setEnabled(false)
918
+ handBackManaged()
774
919
  if (restartTimer !== undefined) cancel(restartTimer)
775
920
  restartTimer = undefined
776
921
  const current = handle
@@ -793,6 +938,18 @@ export function apply(ctx, config) {
793
938
  }
794
939
  }
795
940
 
941
+ /** 在文件管理器里选中一个文件(Windows 资源管理器 / macOS 访达)。 */
942
+ const reveal = async (path) => {
943
+ const { program, args } = revealCommand(process.platform, path)
944
+ const resolved = await ctx.subprocess.resolveExecutable(program, undefined, disposal.signal)
945
+ ctx.subprocess.spawn({
946
+ argv: [resolved, ...args],
947
+ cwd: dirname(path),
948
+ stdio: { stdin: 'ignore', stdout: { maxBytes: 1024 }, stderr: { maxBytes: 1024 } },
949
+ graceMs: 1000,
950
+ })
951
+ }
952
+
796
953
  const control = async (action, payload) => {
797
954
  log(`control: ${action}`)
798
955
  // 录制快捷键期间挂起截图热键:否则按下新组合就真的去截图了。
@@ -800,6 +957,12 @@ export function apply(ctx, config) {
800
957
  notify('shortcuts/suspend', { suspended: payload?.suspended === true })
801
958
  return
802
959
  }
960
+ if (action === 'open-native-settings') {
961
+ if (!nativeSettingsAvailable()) throw new Error('原生设置窗口当前不可用')
962
+ const result = await request('island/open-settings', null)
963
+ if (result !== null) throw new Error(String(result?.error?.message ?? '岛屿未确认打开设置窗口'))
964
+ return
965
+ }
803
966
  // QQ 通知权限:申请(弹 Windows 授权)或打开系统设置;稍后刷新状态。
804
967
  if (action === 'qq-request-access' || action === 'qq-open-settings') {
805
968
  if (!ready) throw new Error('岛屿没有运行')
@@ -818,24 +981,18 @@ export function apply(ctx, config) {
818
981
  log('settings reset to defaults')
819
982
  return
820
983
  }
821
- // 在资源管理器里选中日志文件。
822
984
  // 设置页上的「试听」:按现在选的提示音和音量响一下。
823
985
  if (action === 'sound-test') {
824
986
  if (!ready) throw new Error('岛屿没有运行')
825
987
  notify('sound/test', { sound: settings.sessions?.sound, volume: settings.sessions?.soundVolume })
826
988
  return
827
989
  }
990
+ // 在文件管理器里选中日志文件。
828
991
  if (action === 'open-logs') {
829
- const explorer = await ctx.subprocess.resolveExecutable('explorer.exe', undefined, disposal.signal)
830
- ctx.subprocess.spawn({
831
- argv: [explorer, `/select,${LOG_FILE}`],
832
- cwd: dirname(LOG_FILE),
833
- stdio: { stdin: 'ignore', stdout: { maxBytes: 1024 }, stderr: { maxBytes: 1024 } },
834
- graceMs: 1000,
835
- })
992
+ await reveal(LOG_FILE)
836
993
  return
837
994
  }
838
- // 导出诊断信息:写一份文本放在日志旁边,在资源管理器里选中它。
995
+ // 导出诊断信息:写一份文本放在日志旁边,在文件管理器里选中它。
839
996
  if (action === 'export-diagnostics') {
840
997
  await refreshDiagnostics().catch(() => undefined)
841
998
  const logText = await readFile(LOG_FILE, 'utf8').catch(() => '')
@@ -843,19 +1000,13 @@ export function apply(ctx, config) {
843
1000
  status: status(),
844
1001
  settings,
845
1002
  logText,
846
- system: { os: `Windows ${osRelease()}`, arch: osArch(), node: process.version },
1003
+ system: { os: systemLabel(process.platform, osRelease()), arch: osArch(), node: process.version },
847
1004
  })
848
1005
  const path = join(dirname(LOG_FILE), diagnosticsFileName())
849
1006
  await writeFile(path, report, 'utf8')
850
1007
  diagnosticsPath = path
851
1008
  log(`diagnostics exported: ${path}`)
852
- const explorer = await ctx.subprocess.resolveExecutable('explorer.exe', undefined, disposal.signal)
853
- ctx.subprocess.spawn({
854
- argv: [explorer, `/select,${path}`],
855
- cwd: dirname(path),
856
- stdio: { stdin: 'ignore', stdout: { maxBytes: 1024 }, stderr: { maxBytes: 1024 } },
857
- graceMs: 1000,
858
- })
1009
+ await reveal(path)
859
1010
  return { path }
860
1011
  }
861
1012
  // 打开翻译窗口:和按翻译快捷键一样,只是不会把已经开着的窗口关掉。
@@ -1008,6 +1159,8 @@ export function apply(ctx, config) {
1008
1159
  followed.delete(plugin)
1009
1160
  islandItems.clear(plugin)
1010
1161
  pluginTasks.contributor(plugin).clear()
1162
+ recentBook.clear(plugin)
1163
+ openers.clear(plugin)
1011
1164
  })
1012
1165
  followed.add(plugin)
1013
1166
  } catch (error) {
@@ -1026,11 +1179,13 @@ export function apply(ctx, config) {
1026
1179
  ctx,
1027
1180
  [Symbol.for('cordis.tracker')]: { associate: 'island', property: 'ctx' },
1028
1181
  /**
1029
- * 后台任务的入口:报上名字,拿到 `task(id, { title, subtitle?, progress? })`,返回的句柄有
1030
- * `update` / `finish` / `remove`;`clear()` 撤下自己的全部(规则见 contributions.js)。
1182
+ * 一个插件的入口:报上名字(和可选的 `{ title, icon }`:小岛上怎么称呼它),拿到后台任务
1183
+ * `task(id, { title, subtitle?, progress? })`(返回 `update` / `finish` / `remove`)、最近生成
1184
+ * `recent(id, { title, subtitle?, media?, thumbnail?, at?, open? })` / `forget(id)`、通知
1185
+ * `notify({ title, body?, open? })`,以及撤下自己全部任务和最近生成的 `clear()`(规则见 contributor-entry.js)。
1031
1186
  * 认得出调用方时用它的包名,报的名字只在认不出时用:一个插件不能冒用别人的名字绕过开关。
1032
1187
  */
1033
- contributor(owner) {
1188
+ contributor(owner, display) {
1034
1189
  const tracked = trackedCaller(this?.ctx)
1035
1190
  const name = tracked === 'unknown' ? owner : tracked
1036
1191
  if (tracked !== 'unknown') follow(this.ctx, name)
@@ -1038,7 +1193,12 @@ export function apply(ctx, config) {
1038
1193
  contributorsSeen.add(name)
1039
1194
  log(`contrib: ${String(name)} can now put background tasks on the island (it called itself "${String(owner)}")`)
1040
1195
  }
1041
- return pluginTasks.contributor(name)
1196
+ if (typeof name === 'string' && displays.declare(name, display)) {
1197
+ log(`contrib: ${name} is shown as ${JSON.stringify(displays.of(name))}`)
1198
+ pluginTasks.refresh()
1199
+ recentBook.refresh()
1200
+ }
1201
+ return contributorEntry(name, { tasks: pluginTasks, recent: recentBook, items: islandItems, openers })
1042
1202
  },
1043
1203
  /** 一条状态:`{ id, title, detail? }`。返回收下了没有。 */
1044
1204
  status(input) {
@@ -1070,6 +1230,15 @@ export function apply(ctx, config) {
1070
1230
  }
1071
1231
  // 插件页的同源路由;连接层已做认证,路由不需要自己校验令牌。
1072
1232
  ctx.inject(['connection'], (scoped) => {
1233
+ scoped.effect(() => {
1234
+ const connection = scoped.connection
1235
+ usageConnection = connection
1236
+ reconcileUsagePoll()
1237
+ return () => {
1238
+ if (usageConnection === connection) usageConnection = undefined
1239
+ reconcileUsagePoll()
1240
+ }
1241
+ }, 'dsh-island: VibeDev account poll')
1073
1242
  const pageRoutes = islandRoutes({
1074
1243
  status: statusForPage,
1075
1244
  settings: () => settings,
@@ -1141,6 +1310,9 @@ export function apply(ctx, config) {
1141
1310
 
1142
1311
  ctx.on('api-session/removed', (sessionId) => {
1143
1312
  titleLookups.delete(sessionId)
1313
+ toolCalls.forget(sessionId)
1314
+ managedRevision += 1
1315
+ managedHolds.decideForSession(sessionId, 'timeout')
1144
1316
  closeAttentionFor(sessionId)
1145
1317
  if (book.remove(sessionId)) schedulePush()
1146
1318
  })
@@ -1166,7 +1338,140 @@ export function apply(ctx, config) {
1166
1338
  return !where.front && !(where.quiet && settings.behavior?.quietInFullscreen !== false)
1167
1339
  }
1168
1340
 
1341
+ function handBackManaged(decision = 'timeout') {
1342
+ managedRevision += 1
1343
+ managedHolds.releaseAll(decision)
1344
+ }
1345
+
1346
+ function managedReminderEnabled(kind) {
1347
+ return kind === 'approval'
1348
+ ? settings.sessions?.approveOnIsland !== false
1349
+ : settings.sessions?.notifyOnQuestion !== false
1350
+ }
1351
+
1352
+ function managedActionEnabled(kind) {
1353
+ if (!ready || !desiredRunning || managedTransportClosed || disposal.signal.aborted || !attentionCapable())
1354
+ return false
1355
+ if (
1356
+ !managedReminderEnabled(kind) ||
1357
+ settings.sessions?.approveOnIsland === false ||
1358
+ settings.sessions?.decideOnIsland === false
1359
+ )
1360
+ return false
1361
+ return kind === 'approval'
1362
+ ? managedApprovalEngine() && islandCapabilities.includes('approve')
1363
+ : managedQuestionEngine()
1364
+ }
1365
+
1366
+ async function managedForegroundSafe() {
1367
+ if (handle === undefined || managedTransportClosed) return false
1368
+ const current = handle
1369
+ // Do not let one outstanding probe overlap the next 500 ms recheck.
1370
+ const where = await request('host/foreground', null, 400)
1371
+ return (
1372
+ handle === current &&
1373
+ !managedTransportClosed &&
1374
+ where?.front === false &&
1375
+ where?.quiet === false &&
1376
+ where.error === undefined
1377
+ )
1378
+ }
1379
+
1380
+ async function decideManaged(item, params) {
1381
+ const { decision } = params
1382
+ if (decision === 'open' || decision === 'dismiss') {
1383
+ managedHolds.decide(item.id, decision)
1384
+ return
1385
+ }
1386
+ const result =
1387
+ item.kind === 'approval'
1388
+ ? decision === 'allow' || decision === 'deny'
1389
+ ? decision
1390
+ : undefined
1391
+ : decision === 'answer'
1392
+ ? validatedAnswers(item.questions, params.answers)
1393
+ : undefined
1394
+ if (result === undefined) return
1395
+ if (Date.now() >= item.expiresAt || !managedActionEnabled(item.kind) || !(await managedForegroundSafe())) {
1396
+ managedHolds.decide(item.id, 'timeout')
1397
+ return
1398
+ }
1399
+ if (Date.now() >= item.expiresAt || !managedActionEnabled(item.kind)) {
1400
+ managedHolds.decide(item.id, 'timeout')
1401
+ return
1402
+ }
1403
+ managedHolds.decide(item.id, result)
1404
+ }
1405
+
1406
+ async function holdManaged(item, payload, signal) {
1407
+ if (!managedActionEnabled(item.kind) || signal?.aborted === true) return undefined
1408
+ const revision = managedRevision
1409
+ if (
1410
+ !(await managedForegroundSafe()) ||
1411
+ revision !== managedRevision ||
1412
+ signal?.aborted === true ||
1413
+ !managedActionEnabled(item.kind)
1414
+ )
1415
+ return undefined
1416
+ const timeoutMs = (settings.sessions?.approvalTimeoutSeconds ?? HAND_BACK_MS / 1000) * 1000
1417
+ const response = managedHolds.wait(item.id, { sessionId: item.sessionId, kind: item.kind, signal, timeoutMs })
1418
+ showAttention({ ...item, ...payload, decidable: true, expiresAt: Date.now() + timeoutMs })
1419
+ try {
1420
+ return await response
1421
+ } finally {
1422
+ closeAttention(item.id)
1423
+ }
1424
+ }
1425
+
1426
+ async function managedInteraction(shown, payload, signal, next) {
1427
+ const item = { ...shown, id: `managed-${nextManagedCard++}` }
1428
+ let outcome
1429
+ try {
1430
+ if (payload !== undefined) outcome = await holdManaged(item, payload, signal)
1431
+ } catch {
1432
+ log('could not hold the interaction on the island')
1433
+ }
1434
+ if (signal?.aborted === true) return next()
1435
+ if (outcome === 'allow') return 'allowed-once'
1436
+ if (outcome === 'deny') return 'rejected'
1437
+ if (outcome?.answers !== undefined) return outcome
1438
+
1439
+ if (managedReminderEnabled(item.kind)) {
1440
+ if (outcome === 'dismiss') {
1441
+ attention.add({ ...item, dismissed: true })
1442
+ schedulePush()
1443
+ } else {
1444
+ showAttention(item)
1445
+ }
1446
+ }
1447
+ try {
1448
+ return await next()
1449
+ } finally {
1450
+ closeAttention(item.id)
1451
+ }
1452
+ }
1453
+
1454
+ const workingDirectoryOf = (session) => {
1455
+ const workingDirectory = ctx.get('workingDirectory')
1456
+ return typeof workingDirectory?.get === 'function' ? workingDirectory.get(session) : session.header?.cwd
1457
+ }
1458
+
1459
+ ctx.on('session/event', (session, event) => toolCalls.observe(session, event), { global: true })
1460
+
1461
+ // 审批与提问是瀑布事件。没有确认过的岛上答复时,继续由 VibeDev 的答复者决定。
1169
1462
  ctx.on('approval/request', async (event, next) => {
1463
+ log(`approval request: ${event?.toolName ?? '?'}`)
1464
+ if (managedApprovalEngine()) {
1465
+ if (!managedReminderEnabled('approval') || event?.signal?.aborted === true) return next()
1466
+ const shown = describeApproval(event)
1467
+ let payload
1468
+ try {
1469
+ payload = toolCalls.details(event, workingDirectoryOf)
1470
+ } catch {
1471
+ // 工作目录服务不可用:仍由 VibeDev 完成审批。
1472
+ }
1473
+ return managedInteraction(shown, payload, event?.signal, next)
1474
+ }
1170
1475
  let shown
1171
1476
  try {
1172
1477
  if (settings.sessions?.approveOnIsland !== false) shown = describeApproval(event)
@@ -1210,9 +1515,17 @@ export function apply(ctx, config) {
1210
1515
  // 不管在哪里处理掉的,岛上的那一条都该撤下:留着一条过期的会误导人。
1211
1516
  closeAttention(shown.id)
1212
1517
  }
1213
- })
1518
+ }, { prepend: true })
1214
1519
 
1215
1520
  ctx.on('user-questions/request', async (event, next) => {
1521
+ if (managedQuestionEngine()) {
1522
+ if (event?.signal?.aborted === true || settings.sessions?.notifyOnQuestion === false) return next()
1523
+ if (isApprovalQuestion(event) && attention.waitingOf(event?.agent?.id) === 'approval') return next()
1524
+ const shown = describeQuestion(event)
1525
+ if (!managedReminderEnabled(shown.kind)) return next()
1526
+ const questions = structuredQuestions(event)
1527
+ return managedInteraction(shown, questions === undefined ? undefined : { questions }, event?.signal, next)
1528
+ }
1216
1529
  let shown
1217
1530
  try {
1218
1531
  // 审批有时也走提问通道。岛上已经有这条会话的审批时,不再为同一件事另挂一条。
@@ -1242,6 +1555,8 @@ export function apply(ctx, config) {
1242
1555
  log('plugin disposing; stopping the island')
1243
1556
  // 岛上扣着的审批交回 VibeDev,插件停了它们也不会卡住。
1244
1557
  holds.releaseAll('timeout')
1558
+ handBackManaged()
1559
+ toolCalls.clear()
1245
1560
  islandItems.dispose()
1246
1561
  await stopIsland().catch((error) => log(`stopping the island failed: ${error}`))
1247
1562
  disposal.abort()