@ruoy/dsh-session-bus 0.2.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/lib/core.mjs CHANGED
@@ -302,6 +302,483 @@ export function detectSupervisionSignals(events, cursor, options = {}) {
302
302
  }
303
303
  }
304
304
 
305
+ // ---- 派活台账(S1:sessions_create 的入库、状态机、回执)------------------
306
+ // 设计原则:状态推进是纯函数(advanceTask),宿主半边只负责喂事件与落盘。
307
+ // 这样状态机可以脱离 Cordis 单测——上一版「测试绿但代码坏」的教训。
308
+
309
+ /** 库文件结构版本:v1 → v2 加了 tasks/creates/settings;v2 → v3 加了 grants(权限授权台账)。 */
310
+ export const STORE_VERSION = 3
311
+
312
+ export const TASK_TERMINAL = new Set(['done', 'failed', 'canceled', 'timeout'])
313
+
314
+ /**
315
+ * 把磁盘上的库文件升级到当前结构。
316
+ * 结构不认识(比本程序新、或关键字段坏掉)时返回 null,调用方从空库开始——绝不写坏别人的文件。
317
+ */
318
+ export function migrateStore(raw) {
319
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return null
320
+ const version = Number(raw.version ?? 1)
321
+ if (!Number.isFinite(version) || version > STORE_VERSION) return null
322
+ if (!Array.isArray(raw.messages) || !Array.isArray(raw.audit)) return null
323
+ const store = { ...raw, version: STORE_VERSION }
324
+ if (!Array.isArray(store.supervisions)) store.supervisions = []
325
+ if (!Array.isArray(store.tasks)) store.tasks = []
326
+ if (!Array.isArray(store.creates)) store.creates = []
327
+ if (!Array.isArray(store.grants)) store.grants = []
328
+ if (store.titles === null || typeof store.titles !== 'object') store.titles = {}
329
+ if (store.settings === null || typeof store.settings !== 'object') store.settings = {}
330
+ return store
331
+ }
332
+
333
+ /** 本地时区「今天」的条数(每日上限用)。 */
334
+ export function dailyCount(records, now = Date.now()) {
335
+ const date = new Date(now)
336
+ const start = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime()
337
+ return (Array.isArray(records) ? records : []).filter((row) => Number(row?.ts) >= start).length
338
+ }
339
+
340
+ /** 每日上限的有效值:运行时覆盖 > 配置默认;上限本身也夹在 1..50,防止覆盖值写飞。 */
341
+ export function resolveDailyLimit(settings, fallback) {
342
+ const override = Number(settings?.createDailyLimit)
343
+ if (Number.isFinite(override) && override > 0) return Math.min(Math.max(Math.round(override), 1), 50)
344
+ const base = Number(fallback)
345
+ return Number.isFinite(base) && base > 0 ? Math.round(base) : 5
346
+ }
347
+
348
+ export const CREATE_LIMITS = {
349
+ promptMax: 8000,
350
+ titleMax: 120,
351
+ minBudgetMs: 60_000,
352
+ maxBudgetMs: 24 * 60 * 60 * 1000,
353
+ maxBudgetCalls: 500,
354
+ }
355
+
356
+ function normalizeBudget(input) {
357
+ if (input === undefined || input === null) return { value: undefined }
358
+ if (typeof input !== 'object' || Array.isArray(input)) return { error: 'budget 必须是对象 { maxMs?, maxCalls? }' }
359
+ const out = {}
360
+ if (input.maxMs !== undefined) {
361
+ const ms = Number(input.maxMs)
362
+ if (!Number.isFinite(ms) || ms <= 0) return { error: 'budget.maxMs 必须是正数(毫秒)' }
363
+ out.maxMs = Math.min(Math.max(Math.round(ms), CREATE_LIMITS.minBudgetMs), CREATE_LIMITS.maxBudgetMs)
364
+ }
365
+ if (input.maxCalls !== undefined) {
366
+ const calls = Number(input.maxCalls)
367
+ if (!Number.isFinite(calls) || calls <= 0) return { error: 'budget.maxCalls 必须是正整数' }
368
+ out.maxCalls = Math.min(Math.round(calls), CREATE_LIMITS.maxBudgetCalls)
369
+ }
370
+ return { value: Object.keys(out).length > 0 ? out : undefined }
371
+ }
372
+
373
+ function trimmedString(value) {
374
+ return typeof value === 'string' && value.trim() !== '' ? value.trim() : ''
375
+ }
376
+
377
+ /**
378
+ * sessions_create 的参数收敛。校验错误一律返回 { error },工具层原样回给模型。
379
+ * @param {object} args 工具参数
380
+ * @param {{ defaultCwd?: string }} context 发起会话的工作目录(不传 cwd 时继承)
381
+ */
382
+ export function normalizeCreateRequest(args, context = {}) {
383
+ const src = args !== null && typeof args === 'object' ? args : {}
384
+ const prompt = trimmedString(src.prompt)
385
+ if (!prompt) return { error: 'prompt 必填:新会话要立刻收到一条任务指令,空会话等于白开' }
386
+ if (prompt.length > CREATE_LIMITS.promptMax) return { error: `prompt 过长(上限 ${CREATE_LIMITS.promptMax} 字符)` }
387
+ const provider = trimmedString(src.provider)
388
+ const model = trimmedString(src.model)
389
+ const reasoningEffort = trimmedString(src.reasoningEffort)
390
+ if ((provider && !model) || (model && !provider)) return { error: 'provider 与 model 要成对给' }
391
+ if (reasoningEffort && !provider) return { error: 'reasoningEffort 要配合 provider + model 一起给(只给推理等级无法确定用哪个模型)' }
392
+ const budget = normalizeBudget(src.budget)
393
+ if (budget.error) return { error: budget.error }
394
+ return {
395
+ value: {
396
+ prompt,
397
+ title: trimmedString(src.title).slice(0, CREATE_LIMITS.titleMax),
398
+ cwd: trimmedString(src.cwd) || trimmedString(context.defaultCwd),
399
+ preset: trimmedString(src.preset),
400
+ provider,
401
+ model,
402
+ reasoningEffort,
403
+ reportTo: trimmedString(src.reportTo),
404
+ budget: budget.value,
405
+ },
406
+ }
407
+ }
408
+
409
+ /** 投给新会话的首条任务正文(明确来源,也明确它不等于用户的实时确认)。 */
410
+ export function taskPromptText({ taskId, senderLabel, senderId, prompt }) {
411
+ return [
412
+ `【会话总线·派活】任务 ${taskId} · 发起方「${senderLabel}」(${senderId})`,
413
+ '这不是用户在聊天窗口里直接对你说的,是本机另一个会话(代表用户)派给你的工作;需要用户本人拍板的事(花钱、对外发送、删除数据)先停下说明。',
414
+ '',
415
+ String(prompt ?? ''),
416
+ '',
417
+ '做完直接在回复里写清结果与产出(文件路径/命令/结论),结论会自动回报给发起会话。不要再往外派活。',
418
+ ].join('\n')
419
+ }
420
+
421
+ /**
422
+ * sessions_dispatch 的参数收敛(派给已有会话)。
423
+ * @returns {{ value?: object, error?: string }}
424
+ */
425
+ export function normalizeDispatchRequest(args) {
426
+ const src = args !== null && typeof args === 'object' ? args : {}
427
+ const to = trimmedString(src.to)
428
+ if (!to) return { error: 'to 必填:派给哪个会话(id 或唯一片段)' }
429
+ const prompt = trimmedString(src.prompt)
430
+ if (!prompt) return { error: 'prompt 必填:要它做什么(写清目标与验收标准)' }
431
+ if (prompt.length > CREATE_LIMITS.promptMax) return { error: `prompt 过长(上限 ${CREATE_LIMITS.promptMax} 字符)` }
432
+ const budget = normalizeBudget(src.budget)
433
+ if (budget.error) return { error: budget.error }
434
+ return {
435
+ value: {
436
+ to,
437
+ prompt,
438
+ title: trimmedString(src.title).slice(0, CREATE_LIMITS.titleMax),
439
+ budget: budget.value,
440
+ wake: src.wake !== false,
441
+ },
442
+ }
443
+ }
444
+
445
+ function lastAssistantText(events) {
446
+ let text = ''
447
+ for (const event of Array.isArray(events) ? events : []) {
448
+ if (event?.type !== 'assistant/message') continue
449
+ const value = textOfContent(event.data?.message?.content)
450
+ if (value.trim() !== '') text = value
451
+ }
452
+ return text
453
+ }
454
+
455
+ /** 派活文案里带任务号,用来在目标会话的事件流里认出「我们这条消息真的被消费了」。 */
456
+ function userTextOf(event) {
457
+ if (event?.type === 'user/message') return textOfContent(event.data?.message?.content)
458
+ // 目标空闲时投递的消息只以「收件箱插入」的形式出现在事件流里(不是 user/message),漏了这条会让任务永远停在 queued
459
+ if (event?.type === 'agent/inbox/spliced') {
460
+ const inserted = Array.isArray(event.data?.inserted) ? event.data.inserted : []
461
+ return inserted.map((message) => textOfContent(message?.content)).join('\n')
462
+ }
463
+ return ''
464
+ }
465
+
466
+ const DELIVERABLE_TOOL_RE = /write|edit|apply_patch|create|copy|move|rename/i
467
+
468
+ /**
469
+ * 从工具调用里捞出「产物」(写了/改了哪些文件)。
470
+ * 只认写入类工具 + 绝对路径,去重、限量——够用来在回报里说清「产出了什么」。
471
+ */
472
+ export function collectDeliverables(events, { limit = 20 } = {}) {
473
+ const seen = new Set()
474
+ const out = []
475
+ for (const event of Array.isArray(events) ? events : []) {
476
+ if (event?.type !== 'tool/call') continue
477
+ const name = String(event.data?.name ?? '')
478
+ if (!DELIVERABLE_TOOL_RE.test(name)) continue
479
+ const args = typeof event.data?.arguments === 'string' ? event.data.arguments : JSON.stringify(event.data?.arguments ?? '')
480
+ const raw = absolutePathIn(args)
481
+ if (!raw) continue
482
+ // 事件里的 args 通常是 JSON 字符串,反斜杠是双份的;归一成单份再记,方便直接复制使用
483
+ const path = raw.replace(/\\\\/g, '\\')
484
+ if (seen.has(path)) continue
485
+ seen.add(path)
486
+ out.push({ tool: name, path })
487
+ if (out.length >= limit) break
488
+ }
489
+ return out
490
+ }
491
+
492
+ /** 提示词的短指纹,用来判「同目标 + 同 prompt」的重复派活(FNV-1a,够用且无依赖)。 */
493
+ export function promptDigest(text) {
494
+ let hash = 0x811c9dc5
495
+ const value = String(text ?? '')
496
+ for (let i = 0; i < value.length; i += 1) {
497
+ hash ^= value.charCodeAt(i)
498
+ hash = Math.imul(hash, 0x01000193) >>> 0
499
+ }
500
+ return hash.toString(16).padStart(8, '0')
501
+ }
502
+
503
+ /**
504
+ * 派活任务的一步状态推进(纯函数,返回新记录,不改入参)。
505
+ * 「开始了」的判定不用 turn/start:用「目标会话里出现了带本任务号的那条用户消息」——
506
+ * 这样给一个正在忙的会话派活时,它当前那一轮的 turn/end 不会把我们的任务误判成完成。
507
+ * @param {object} task 台账里的任务
508
+ * @param {{ now?: number, live?: boolean, events?: Array, firstMessageTimeoutMs?: number, maxLifetimeMs?: number }} options
509
+ * @returns {{ task: object, changed: boolean, report: string|null }} report 非空 = 该回报给发起会话
510
+ */
511
+ export function advanceTask(task, options = {}) {
512
+ if (task === null || typeof task !== 'object') return { task, changed: false, report: null }
513
+ if (TASK_TERMINAL.has(task.status)) return { task, changed: false, report: null }
514
+ const now = Number(options.now) || Date.now()
515
+ const events = Array.isArray(options.events) ? options.events : []
516
+ const firstMessageTimeoutMs = positiveOr(options.firstMessageTimeoutMs, 5 * 60 * 1000)
517
+ const maxLifetimeMs = positiveOr(options.maxLifetimeMs, 6 * 60 * 60 * 1000)
518
+
519
+ const next = { ...task }
520
+ let changed = false
521
+ const cursorBase = Number.isInteger(next.cursor) && next.cursor >= 0 ? Math.min(next.cursor, events.length) : 0
522
+ // 我们那条消息在事件流里的位置:取**最后一次**出现(重发后旧的会留在前面)。
523
+ // 判「开始」和判「完成」都以它为界——只信游标会让「先被跳过、后补认出」的任务永远收不到 turn/end。
524
+ const ownIndex = events.findLastIndex((event) => userTextOf(event).includes(String(task.id ?? '')))
525
+ const ownSeen = next.started === true || ownIndex >= 0
526
+ const startIndex = ownSeen && ownIndex >= 0 ? Math.min(cursorBase, ownIndex) : cursorBase
527
+ const fresh = events.slice(startIndex)
528
+ if (events.length > cursorBase) {
529
+ next.cursor = events.length
530
+ next.eventCount = (next.eventCount ?? 0) + events.length - cursorBase
531
+ changed = true
532
+ } else if (startIndex !== cursorBase) {
533
+ next.cursor = events.length
534
+ changed = true
535
+ }
536
+
537
+ if (ownSeen && next.started !== true) {
538
+ next.started = true
539
+ next.startedAt = now
540
+ changed = true
541
+ }
542
+ if (next.started && next.status === 'queued') {
543
+ next.status = 'running'
544
+ changed = true
545
+ }
546
+
547
+ // 工具调用计数(预算用)与产物收集:只算「我们这条消息被消费之后」的活动
548
+ if (next.started && fresh.length > 0) {
549
+ const calls = fresh.filter((event) => event?.type === 'tool/call').length
550
+ if (calls > 0) {
551
+ next.calls = (next.calls ?? 0) + calls
552
+ changed = true
553
+ }
554
+ const found = collectDeliverables(fresh)
555
+ if (found.length > 0) {
556
+ const known = Array.isArray(next.deliverables) ? next.deliverables : []
557
+ const merged = [...known]
558
+ for (const item of found) {
559
+ if (!merged.some((row) => row.path === item.path)) merged.push(item)
560
+ }
561
+ if (merged.length !== known.length) {
562
+ next.deliverables = merged.slice(-40)
563
+ changed = true
564
+ }
565
+ }
566
+ }
567
+
568
+ if (next.started && fresh.some((event) => event?.type === 'turn/end')) {
569
+ next.status = 'done'
570
+ next.endedAt = now
571
+ const text = lastAssistantText(fresh)
572
+ if (text) next.lastText = clampText(text, 1200)
573
+ return { task: next, changed: true, report: taskReportText(next, now) }
574
+ }
575
+
576
+ const open = pendingApprovalsFromEvents(events)
577
+ if (open.length > 0) {
578
+ const seen = Array.isArray(next.notifiedApprovals) ? next.notifiedApprovals : []
579
+ const unseen = open.map((row) => row.id).filter((id) => !seen.includes(id))
580
+ const statusChanged = next.status !== 'waiting-approval'
581
+ if (statusChanged) next.status = 'waiting-approval'
582
+ if (unseen.length > 0) {
583
+ next.notifiedApprovals = [...seen, ...unseen].slice(-50)
584
+ next.waitingSince = next.waitingSince ?? now
585
+ return { task: next, changed: true, report: taskReportText(next, now) }
586
+ }
587
+ if (statusChanged) return { task: next, changed: true, report: null }
588
+ return { task: next, changed, report: null }
589
+ }
590
+ if (next.status === 'waiting-approval') {
591
+ next.status = 'running'
592
+ next.waitingSince = undefined
593
+ changed = true
594
+ }
595
+
596
+ if (!next.started && now - (next.createdAt ?? now) > firstMessageTimeoutMs) {
597
+ next.status = 'failed'
598
+ next.endedAt = now
599
+ next.reclaimable = true
600
+ next.note = `派出去 ${Math.round(firstMessageTimeoutMs / 60000)} 分钟还没被目标会话消费(消息没投进去),可以重发一次或干脆不管它`
601
+ return { task: next, changed: true, report: taskReportText(next, now) }
602
+ }
603
+
604
+ const maxCalls = Number(next.budget?.maxCalls)
605
+ if (Number.isFinite(maxCalls) && maxCalls > 0 && (next.calls ?? 0) > maxCalls) {
606
+ next.status = 'timeout'
607
+ next.endedAt = now
608
+ next.note = `工具调用 ${next.calls} 次,超过预算 ${maxCalls} 次(要不要停它用 sessions_tasks cancel)`
609
+ return { task: next, changed: true, report: taskReportText(next, now) }
610
+ }
611
+
612
+ const budgetMs = Number(next.budget?.maxMs)
613
+ if (Number.isFinite(budgetMs) && budgetMs > 0 && next.started && now - (next.startedAt ?? next.createdAt) > budgetMs) {
614
+ next.status = 'timeout'
615
+ next.endedAt = now
616
+ next.note = `超过预算 ${Math.round(budgetMs / 60000)} 分钟仍未结束`
617
+ return { task: next, changed: true, report: taskReportText(next, now) }
618
+ }
619
+
620
+ if (now - (next.createdAt ?? now) > maxLifetimeMs) {
621
+ next.status = 'timeout'
622
+ next.endedAt = now
623
+ next.note = `存活超过 ${Math.round(maxLifetimeMs / 3600000)} 小时仍未结束`
624
+ return { task: next, changed: true, report: taskReportText(next, now) }
625
+ }
626
+
627
+ return { task: next, changed, report: null }
628
+ }
629
+
630
+ /** 回执正文(发回发起会话;面板与 sessions_inbox 也能看到)。 */
631
+ export function taskReportText(task, now = Date.now()) {
632
+ const status = String(task?.status ?? '')
633
+ const label = {
634
+ done: '已完成',
635
+ failed: '失败(可回收)',
636
+ timeout: '超时',
637
+ canceled: '已取消',
638
+ 'waiting-approval': '卡在授权请求',
639
+ running: '进行中',
640
+ queued: '已建,等待开始',
641
+ }[status] ?? status
642
+ const minutes = Math.floor(Math.max(0, now - (task?.createdAt ?? now)) / 60000)
643
+ const lines = [`【派活回报】${task.id} · ${label} · 目标会话 ${String(task.targetSessionId ?? '').slice(0, 16)}(${minutes} 分钟)`]
644
+ if (task.title) lines.push(`任务:${task.title}`)
645
+ if (task.note) lines.push(`说明:${task.note}`)
646
+ if (task.lastText) lines.push(`它最后说:${clampText(task.lastText, 1200)}`)
647
+ const deliverables = Array.isArray(task.deliverables) ? task.deliverables : []
648
+ if (deliverables.length > 0) {
649
+ lines.push(`产出(${deliverables.length}):`)
650
+ for (const item of deliverables.slice(-10)) lines.push(`- ${item.path}${item.tool ? `(${item.tool})` : ''}`)
651
+ if (deliverables.length > 10) lines.push(`- …另有 ${deliverables.length - 10} 个没列`)
652
+ }
653
+ if (Number.isFinite(Number(task.calls)) && Number(task.calls) > 0) lines.push(`工具调用:${task.calls} 次`)
654
+ if (status === 'waiting-approval') lines.push('它停在授权请求上等人决定:可以到那个会话处理,或用跨会话审批。')
655
+ if (status === 'timeout' && !task.note) lines.push('要停它请用 sessions_tasks {action:"cancel"}。')
656
+ return lines.join('\n')
657
+ }
658
+
659
+ /** 一行摘要(工具返回用)。 */
660
+ export function taskSummary(task, now = Date.now()) {
661
+ const minutes = Math.floor(Math.max(0, now - (task?.createdAt ?? now)) / 60000)
662
+ const title = task?.title ? ` ${clampText(task.title, 40)}` : ''
663
+ return `${task.id}${title} [${task.status}] → ${String(task.targetSessionId ?? '').slice(0, 16)} · ${minutes}m`
664
+ }
665
+
666
+ // ---- 权限申请(S1-附加):三档,从最小到最大 -----------------------------
667
+ // L1 目录授权:registerWritableRoot(session, dir) + TTL(最小权限、可撤销)
668
+ // L2 审批开启:approval.setPolicy(agent, 'ask')(完全权限下仍可要确认)
669
+ // L3 对话式确认:只问不改,用于花钱/对外发送这类非权限动作
670
+ // 三档共用一条铁律:必须带 why,且**永远经宿主 approval.request 走真实审批**——插件不代批。
671
+ // 宿主没有「把沙箱模式改成 danger-full-access」的写入口,所以本插件不提供这一档,也不假装能提供。
672
+
673
+ export const PERMISSION_ACTIONS = ['list', 'policy', 'set-sandbox', 'set-preset', 'grant-dir', 'grant-ask', 'enforce-ask', 'revoke', 'confirm']
674
+
675
+ /** 沙箱模式的合法取值(宿主 SandboxMode)。 */
676
+ export const SANDBOX_MODES = ['workspace-write', 'danger-full-access']
677
+
678
+ export const GRANT_LIMITS = { minTtlMinutes: 1, maxTtlMinutes: 120, defaultTtlMinutes: 30 }
679
+
680
+ /** 绝对路径判定(Windows 盘符 / UNC / POSIX)。相对路径宿主会直接拒,这里先给可读的错。 */
681
+ export function isAbsoluteDir(value) {
682
+ const text = String(value ?? '').trim()
683
+ if (text === '') return false
684
+ return /^[A-Za-z]:[\\/]/.test(text) || text.startsWith('\\\\') || text.startsWith('/')
685
+ }
686
+
687
+ /**
688
+ * sessions_permission 的参数收敛。
689
+ * @param {object} args
690
+ * @returns {{ value?: object, error?: string }}
691
+ */
692
+ export function normalizePermissionRequest(args) {
693
+ const src = args !== null && typeof args === 'object' ? args : {}
694
+ const action = String(src.action ?? 'list').trim()
695
+ if (!PERMISSION_ACTIONS.includes(action)) {
696
+ return { error: `action 只能是 ${PERMISSION_ACTIONS.join(' / ')}` }
697
+ }
698
+ if (action === 'list') return { value: { action } }
699
+ // policy = 只读;enforce-ask = 收紧(把审批策略设回 ask),两者都不需要 why、也不弹审批
700
+ if (action === 'policy') return { value: { action, session: String(src.session ?? '').trim() } }
701
+ if (action === 'enforce-ask') {
702
+ return { value: { action, session: String(src.session ?? '').trim(), scope: src.scope === 'all' ? 'all' : 'self' } }
703
+ }
704
+ // set-preset:直接套一个权限预设(沙箱+审批一起切);放宽要用户点头
705
+ if (action === 'set-preset') {
706
+ const name = String(src.name ?? '').trim()
707
+ if (name === '') return { error: 'set-preset 需要 name(presets 列表里的键名)' }
708
+ return { value: { action, session: String(src.session ?? '').trim(), name, why: String(src.why ?? '').trim() } }
709
+ }
710
+ // set-sandbox:host 唯一写路径是给会话追加 sandbox/mode 事件;放宽到 danger-full-access 要用户点头
711
+ if (action === 'set-sandbox') {
712
+ const mode = String(src.mode ?? '').trim()
713
+ if (!SANDBOX_MODES.includes(mode)) return { error: `mode 只能是 ${SANDBOX_MODES.join(' / ')}` }
714
+ return {
715
+ value: {
716
+ action,
717
+ session: String(src.session ?? '').trim(),
718
+ mode,
719
+ why: String(src.why ?? '').trim(),
720
+ },
721
+ }
722
+ }
723
+
724
+ const why = String(src.why ?? '').trim()
725
+ if (why === '') return { error: 'why 必填:没有理由的权限申请不发给用户' }
726
+ if (why.length > 800) return { error: 'why 过长(上限 800 字)' }
727
+
728
+ if (action === 'confirm') {
729
+ return { value: { action, why, what: String(src.what ?? '').trim().slice(0, 800) } }
730
+ }
731
+ if (action === 'revoke') {
732
+ const grantId = String(src.id ?? src.grantId ?? '').trim()
733
+ if (grantId === '') return { error: 'revoke 需要 id(sessions_permission list 里的 grant id)' }
734
+ return { value: { action, why, grantId } }
735
+ }
736
+
737
+ const session = String(src.session ?? '').trim()
738
+ if (session === '') return { error: `${action} 需要 session(目标会话 id 或唯一片段)` }
739
+
740
+ if (action === 'grant-ask') return { value: { action, why, session } }
741
+
742
+ const dir = String(src.dir ?? '').trim()
743
+ if (dir === '') return { error: 'grant-dir 需要 dir(绝对路径)' }
744
+ if (!isAbsoluteDir(dir)) return { error: `dir 必须是绝对路径:${dir}` }
745
+ const rawTtl = Number(src.ttlMinutes ?? GRANT_LIMITS.defaultTtlMinutes)
746
+ if (!Number.isFinite(rawTtl) || rawTtl <= 0) return { error: 'ttlMinutes 必须是正数(分钟)' }
747
+ const ttlMinutes = Math.min(Math.max(Math.round(rawTtl), GRANT_LIMITS.minTtlMinutes), GRANT_LIMITS.maxTtlMinutes)
748
+ return { value: { action, why, session, dir, ttlMinutes } }
749
+ }
750
+
751
+ /** 每一档共用:只有 allowed-once 算批准;rejected / cancelled / unavailable 一律不算。 */
752
+ export function isApproved(outcome) {
753
+ return outcome === 'allowed-once'
754
+ }
755
+
756
+ /** 授权剩余毫秒;长期授权(grant-ask)返回 null。 */
757
+ export function grantRemainingMs(grant, now = Date.now()) {
758
+ const expiresAt = Number(grant?.expiresAt)
759
+ if (!Number.isFinite(expiresAt)) return null
760
+ return Math.max(0, expiresAt - now)
761
+ }
762
+
763
+ /** 这条授权现在还算不算数(状态 active 且没过期)。 */
764
+ export function isGrantActive(grant, now = Date.now()) {
765
+ if (grant?.status !== 'active') return false
766
+ const remaining = grantRemainingMs(grant, now)
767
+ return remaining === null || remaining > 0
768
+ }
769
+
770
+ /** 一行摘要(工具与面板共用)。 */
771
+ export function permissionGrantSummary(grant, now = Date.now()) {
772
+ const kind = grant?.kind === 'dir' ? '目录授权' : grant?.kind === 'ask' ? '审批确认' : String(grant?.kind ?? '')
773
+ const parts = [String(grant?.id ?? '?'), kind, `会话 ${String(grant?.sessionId ?? '').slice(0, 16)}`]
774
+ if (grant?.kind === 'dir' && grant.dir) parts.push(`目录 ${grant.dir}`)
775
+ if (grant?.kind === 'ask') parts.push(`策略 ${grant.policy}`)
776
+ const remaining = grantRemainingMs(grant, now)
777
+ parts.push(remaining === null ? '长期(手动撤销)' : `剩 ${Math.ceil(remaining / 60000)} 分钟`)
778
+ parts.push(String(grant?.status ?? 'unknown'))
779
+ return parts.join(' · ')
780
+ }
781
+
305
782
  /** 监督记录的摘要行(面板和工具返回共用)。 */
306
783
  export function supervisionSummary(record, now) {
307
784
  const elapsedMs = Math.max(0, (now ?? Date.now()) - record.startedAt)
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@ruoy/dsh-session-bus",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "private": false,
5
5
  "type": "module",
6
- "description": "会话互通:让同一 profile 内的会话互相查看、互相发消息、并监督目标是否跑偏。默认只排队不唤醒,监督默认只汇报不打断。Session bus for DeepSeek Harness: read other sessions, message them (queued or waking), and supervise them with report/steer/guard modes.",
6
+ "description": "会话互通:让同一 profile 内的会话互相查看、互相发消息、并监督目标是否跑偏;也能原生新建会话派活并自动回报(默认关闭、有每日上限)。Session bus for DeepSeek Harness: read other sessions, message them (queued or waking), supervise them with report/steer/guard, and create + dispatch to new sessions.",
7
7
  "keywords": [
8
8
  "dsh",
9
9
  "dsh-plugin",
@@ -26,7 +26,9 @@
26
26
  "main": "./index.js",
27
27
  "exports": {
28
28
  ".": "./index.js",
29
- "./client": "./panel.js",
29
+ "./client": {
30
+ "default": "./panel.js"
31
+ },
30
32
  "./package.json": "./package.json"
31
33
  },
32
34
  "files": [
@@ -48,14 +50,18 @@
48
50
  "test": "node test/core.test.mjs"
49
51
  },
50
52
  "dsh": {
53
+ "engines": {
54
+ "dsh": ">=0.2.2-rc.5"
55
+ },
51
56
  "bundle": {
52
57
  "patch": "./cordis.patch.yml"
53
58
  },
54
59
  "client": {
55
60
  "platform": "web",
56
- "immediately": true,
57
61
  "inject": [
58
- "@deepseek-ai/dsh-client-ui-sidebar-right"
62
+ "@deepseek-ai/dsh-client-locale",
63
+ "@deepseek-ai/dsh-client-ui-renderer",
64
+ "@deepseek-ai/dsh-client-ui-layout"
59
65
  ]
60
66
  }
61
67
  }