dsh-duet 0.1.9 → 0.2.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.
Files changed (67) hide show
  1. package/README.md +19 -1
  2. package/assets/avatar/THREE-LICENSE.txt +21 -0
  3. package/assets/avatar/character.glb +0 -0
  4. package/assets/avatar/desktop/character.glb +0 -0
  5. package/assets/avatar/desktop/companion.mjs +18 -0
  6. package/assets/avatar/desktop/index.html +33 -0
  7. package/assets/avatar/desktop/manifest.json +10 -0
  8. package/assets/avatar/desktop/portrait.png +0 -0
  9. package/assets/avatar/desktop/renderer.mjs +4230 -0
  10. package/assets/avatar/portrait.png +0 -0
  11. package/assets/avatar/renderer.mjs +4230 -0
  12. package/desktop/bin/darwin-arm64/duet-avatar.app/Contents/Info.plist +36 -0
  13. package/desktop/bin/darwin-arm64/duet-avatar.app/Contents/MacOS/duet-avatar +0 -0
  14. package/desktop/bin/darwin-arm64/duet-avatar.app/Contents/Resources/duet companion.icns +0 -0
  15. package/desktop/bin/darwin-arm64/duet-avatar.app/Contents/_CodeSignature/CodeResources +128 -0
  16. package/desktop/bin/darwin-arm64/manifest.json +14 -0
  17. package/desktop/bin/win32-x64/duet-avatar.exe +0 -0
  18. package/desktop/bin/win32-x64/manifest.json +11 -0
  19. package/package.json +17 -5
  20. package/src/avatar/companion.html +33 -0
  21. package/src/avatar/companion.mjs +210 -0
  22. package/src/avatar/idle.mjs +9 -0
  23. package/src/avatar/lipsync.mjs +13 -0
  24. package/src/avatar/motion.mjs +93 -0
  25. package/src/avatar/renderer.mjs +90 -0
  26. package/src/avatar/surface.mjs +45 -0
  27. package/src/avatar/toolbar.mjs +49 -0
  28. package/src/client/audio.mjs +145 -10
  29. package/src/client/avatar-surfaces.mjs +83 -0
  30. package/src/client/avatar-tasks.mjs +68 -0
  31. package/src/client/avatar.mjs +218 -0
  32. package/src/client/browser.mjs +81 -33
  33. package/src/client/composer-bridge.mjs +5 -2
  34. package/src/client/composer.mjs +3 -3
  35. package/src/client/connection-hint.mjs +2 -1
  36. package/src/client/consent.mjs +3 -1
  37. package/src/client/controls-layout.mjs +21 -9
  38. package/src/client/entry.js +26 -3
  39. package/src/client/feedback.mjs +19 -4
  40. package/src/client/identity.mjs +2 -2
  41. package/src/client/input-effect.mjs +51 -0
  42. package/src/client/interactions.mjs +5 -1
  43. package/src/client/notice.mjs +1 -0
  44. package/src/client/rpc.mjs +23 -5
  45. package/src/client/settings.html +78 -4
  46. package/src/client/transport.mjs +2 -2
  47. package/src/client/tutorial-adapter.mjs +4 -4
  48. package/src/client/tutorial.mjs +5 -3
  49. package/src/host/assets.mjs +12 -0
  50. package/src/host/avatar-activity.mjs +24 -0
  51. package/src/host/avatar-assets.mjs +18 -0
  52. package/src/host/avatar.mjs +130 -0
  53. package/src/host/diagnostics.mjs +111 -7
  54. package/src/host/feedback-files.mjs +5 -1
  55. package/src/host/plugin.mjs +67 -4
  56. package/src/host/proxy.mjs +16 -6
  57. package/src/host/settings-migration.mjs +2 -1
  58. package/src/host/settings.mjs +19 -4
  59. package/src/host/stop-task.mjs +37 -0
  60. package/src/shared/avatar-activity.mjs +33 -0
  61. package/src/shared/avatar-menu-ui.mjs +85 -0
  62. package/src/shared/avatar-menu.mjs +83 -0
  63. package/src/shared/avatar-surface.mjs +24 -0
  64. package/src/shared/avatar-ui.mjs +91 -0
  65. package/src/shared/avatar.mjs +125 -0
  66. package/src/shared/nickname.mjs +13 -0
  67. package/src/shared/state.mjs +1 -1
@@ -0,0 +1,85 @@
1
+ import {avatarLocalState,avatarMenuAction,avatarMenuResult} from './avatar-menu.mjs'
2
+ import {sizeButton,nextAvatarSize} from './avatar-ui.mjs'
3
+ const labels={completed:'本轮已完成',failed:'执行失败',stopped:'已停止',approval:'等待授权',question:'等待回答',plan_review:'等待方案确认'}
4
+ const names={small:'紧凑',medium:'标准',large:'宽松'}
5
+ const paths={open:'M14 3h7v7m0-7L10 14M10 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-5',pending:'M8 4h8m-9 0H5v17h14V4h-2M8 3h8v4H8zM8 12h8m-8 4h5',bubble:'M5 4h14a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H9l-5 3v-3H3V6a2 2 0 0 1 2-2zM7 9h10m-10 4h6',tutorial:'m9 5 10 7-10 7z',settings:'M12 8a4 4 0 1 0 0 8 4 4 0 0 0 0-8M9 3h6l1 3 3 1 2 5-2 5-3 1-1 3H9l-1-3-3-1-2-5 2-5 3-1z',hide:'m4 4 16 16M9 5a11 11 0 0 1 12 7l-3 4M6 6a13 13 0 0 0-5 6s4 7 11 7l3-1M10 10a3 3 0 0 0 4 4',back:'m14 5-7 7 7 7'}
6
+ const icon=name=>{const s=document.createElementNS('http://www.w3.org/2000/svg','svg');s.setAttribute('viewBox','0 0 24 24');s.setAttribute('aria-hidden','true');s.innerHTML=`<path d="${paths[name]||paths.pending}"/>`;return s}
7
+ export function mountAvatarMenu({anchor,viewport=()=>[0,0,innerWidth,innerHeight],send,changed=()=>{}}){
8
+ let state={items:[],running:0,enabled:true,size:'large',bubble:'medium'},root,toast,badge,section='main',timer,dead=false,point,previous,toastId,ackTimer
9
+ const style=document.createElement('style');style.textContent=`
10
+ .duet-pet-menu{position:fixed;z-index:2147483601;box-sizing:border-box;width:264px;max-width:calc(100vw - 24px);padding:9px;border:1px solid #a7c5dc30;border-radius:18px;background:#142330f7;color:#eaf2f8;font:13px/1.5 Inter,"PingFang SC",sans-serif;box-shadow:0 16px 48px #0004,0 2px 8px #0002;backdrop-filter:blur(20px);pointer-events:auto;overflow:auto}
11
+ .duet-pet-menu button{position:relative;display:flex;align-items:center;justify-content:flex-start;gap:10px;box-sizing:border-box;width:100%;min-height:39px;margin:0;border:0;border-radius:10px;padding:8px 11px;background:transparent;color:inherit;text-align:left;font:inherit;cursor:pointer;height:auto;flex-shrink:0;letter-spacing:normal}
12
+ .duet-pet-menu button>[data-label]{min-width:0;flex:1;overflow-wrap:anywhere}
13
+ .duet-pet-menu button>svg,.duet-pet-menu [data-size-icon]{display:flex;align-items:center;justify-content:center;width:20px;height:20px;flex:0 0 20px}
14
+ [data-duet-notice-badge][hidden]{display:none!important}
15
+ .duet-pet-menu button:hover,.duet-pet-menu button:focus-visible{background:#b3daff16;outline:none}
16
+ .duet-pet-menu svg{width:20px;height:20px;fill:none;stroke:currentColor;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round;flex-shrink:0;color:#a7bdd0}
17
+ .duet-pet-menu [data-wordmark]{font:700 28px/1.1 Inter,"PingFang SC",sans-serif;letter-spacing:-1.1px;padding:11px 12px 15px}
18
+ .duet-pet-menu [data-wordmark] span{color:#ed9b35}.duet-pet-menu hr{border:0;border-top:1px solid #a7c5dc1c;margin:6px 9px}
19
+ .duet-pet-menu [data-value]{margin-left:auto;color:#9eb1c0;font-size:12px}.duet-pet-menu [data-switch]{position:relative;display:block;width:28px;height:16px;border-radius:10px;background:#53616e;flex-shrink:0;transition:background .15s}
20
+ .duet-pet-menu [data-switch]:after{content:'';position:absolute;top:2px;left:2px;width:12px;height:12px;border-radius:50%;background:white;transition:transform .15s}.duet-pet-menu [aria-checked=true] [data-switch]{background:#6eabc9}.duet-pet-menu [aria-checked=true] [data-switch]:after{transform:translateX(12px)}
21
+ .duet-pet-menu [data-bubble-preview]{margin:12px 9px;padding:12px 14px;border-radius:15px 15px 15px 4px;border:1px solid #8dc5ed45;background:#213b4c;white-space:pre-wrap;overflow:auto;line-height:1.7;scrollbar-width:thin}
22
+ .duet-pet-menu p{margin:10px 12px;color:#a7bdd0}.duet-pet-menu [data-notice-title]{padding:8px 11px;font-weight:600}
23
+ `;document.head.append(style)
24
+ const place=node=>{
25
+ const [x,y,w,h]=viewport();node.style.maxHeight=Math.max(40,h-24)+'px';node.style.maxWidth=Math.max(40,w-24)+'px'
26
+ const a=anchor().getBoundingClientRect(),b=node.getBoundingClientRect(),top=point?.y??(a.top-b.height-12>=y?a.top-b.height-12:a.bottom+12)
27
+ node.style.left=Math.max(x+12,Math.min(point?.x??a.left,x+w-b.width-12))+'px';node.style.top=Math.max(y+12,Math.min(top,y+h-b.height-12))+'px'
28
+ }
29
+ const close=()=>{root?.remove();root=null;point=null;if(previous?.isConnected)previous.focus({preventScroll:true});changed()}
30
+ const command=(action,value,id)=>send(avatarMenuAction({type:'menu_action',request_id:crypto.randomUUID(),action,value,id}))
31
+ const row=(label,action,iconName=action,id)=>{
32
+ const b=document.createElement('button');b.type='button';b.setAttribute('role','menuitem');b.dataset.menuAction=action
33
+ if(paths[iconName])b.append(icon(iconName));const t=document.createElement('span');t.dataset.label='';t.textContent=label;b.append(t)
34
+ b.onclick=()=>{if(['pending','bubble_panel','back'].includes(action)){section=action==='back'?'main':action;render();return}close();command(action,undefined,id)};return b
35
+ }
36
+ const countLabel=()=>{const n=state.items.filter(i=>i.pending||i.unread).length;return '待处理事项与通知'+(n?`(${n})`:'')}
37
+ const valueSpan=b=>{const v=document.createElement('span');v.dataset.value='';b.append(v);return v}
38
+ const refreshControls=()=>{
39
+ if(!root)return
40
+ const size=root.querySelector('[data-menu-action=size]');if(size){const glyph=size.querySelector('[data-size-icon]');sizeButton(glyph,state.size);size.querySelector('[data-value]').textContent={large:'大',medium:'中',small:'小'}[state.size];size.setAttribute('aria-label',glyph.getAttribute('aria-label'))}
41
+ const notify=root.querySelector('[data-menu-action=notifications]');notify?.setAttribute('aria-checked',String(state.enabled))
42
+ const bubble=root.querySelector('[data-menu-action=bubble]');if(bubble){bubble.querySelector('[data-value]').textContent=names[state.bubble];bubble.setAttribute('aria-label',`气泡大小:${names[state.bubble]},点击切换`)}
43
+ const preview=root.querySelector('[data-bubble-preview]');if(preview){preview.style.maxHeight={small:60,medium:110,large:180}[state.bubble]+'px';preview.dataset.size=state.bubble}
44
+ const pending=root.querySelector('[data-menu-action=pending] span');if(pending)pending.textContent=countLabel()
45
+ place(root);changed()
46
+ }
47
+ const render=()=>{
48
+ if(!root)return;root.replaceChildren()
49
+ const title=document.createElement('div');title.dataset.wordmark='';title.append('duet');const dot=document.createElement('span');dot.textContent='.';title.append(dot);root.append(title)
50
+ const divider=()=>root.append(document.createElement('hr'))
51
+ if(section==='main'){
52
+ root.append(row('打开 DSH','open_dsh','open'),row(countLabel(),'pending'))
53
+ const notify=row('任务通知','notifications','pending');notify.setAttribute('role','menuitemcheckbox');const toggle=document.createElement('span');toggle.dataset.switch='';notify.append(toggle);notify.onclick=()=>{state.enabled=!state.enabled;refreshControls();command('notifications',state.enabled)};root.append(notify);divider()
54
+ const size=row('形象大小','size'),glyph=document.createElement('span');glyph.dataset.sizeIcon='';size.prepend(glyph);valueSpan(size);size.onclick=()=>{state.size=nextAvatarSize(state.size);refreshControls();command('size',state.size)}
55
+ root.append(size,row('气泡大小','bubble_panel','bubble'));divider()
56
+ root.append(row('使用教学','tutorial'),row('duet 设置','settings'),row('隐藏形象','hide'))
57
+ }else if(section==='bubble_panel'){
58
+ const cycle=row('气泡大小','bubble','bubble');valueSpan(cycle);cycle.onclick=()=>{state.bubble={small:'medium',medium:'large',large:'small'}[state.bubble];refreshControls();command('bubble',state.bubble)};root.append(cycle)
59
+ const sample=document.createElement('div');sample.dataset.bubblePreview='';sample.setAttribute('aria-label','示例气泡');sample.textContent='好的,我来帮你。\n任务完成后,我会在这里告诉你结果。\n也可以随时打断我,继续聊聊你的新想法。\n这是一段较长的文字,你可以看看当前气泡能显示多少内容。';root.append(sample,row('返回','back'))
60
+ }else{
61
+ if(!state.available){const p=document.createElement('p');p.textContent='正在连接 DSH';root.append(p)}
62
+ if(!state.items.length){const p=document.createElement('p');p.textContent='暂时没有待处理事项或新通知';root.append(p)}
63
+ for(const item of state.items){const b=row(`${item.unread?'● ':''}${item.name||'未命名会话'} · ${labels[item.status]}`,'view','pending',item.id);b.title=item.summary;root.append(b)}root.append(row('返回','back'))
64
+ }
65
+ refreshControls();root.querySelector('button')?.focus({preventScroll:true})
66
+ }
67
+ const open=(event,tab='main')=>{
68
+ if(dead)return;event?.preventDefault();event?.stopPropagation();close();previous=document.activeElement;section=tab;point=event&&Number.isFinite(event.clientX)&&event.clientX>0?{x:event.clientX,y:event.clientY}:null
69
+ root=document.createElement('div');root.className='duet-pet-menu';root.dataset.duetContextMenu='';root.setAttribute('role','menu');root.setAttribute('aria-label','duet 形象菜单');document.body.append(root);render()
70
+ }
71
+ const outside=e=>{if(root&&!root.contains(e.target)){e.preventDefault();e.stopPropagation();close()}}
72
+ const keys=e=>{if(!root)return;if(e.key==='Escape'){e.preventDefault();e.stopImmediatePropagation();close();return}const buttons=[...root.querySelectorAll('button')],index=buttons.indexOf(document.activeElement);if(['ArrowDown','ArrowUp','Home','End','Tab'].includes(e.key)){e.preventDefault();buttons[e.key==='Home'?0:e.key==='End'?buttons.length-1:(index+(e.key==='ArrowUp'||e.key==='Tab'&&e.shiftKey?-1:1)+buttons.length)%buttons.length]?.focus()}}
73
+ const decorate=(node,label)=>{node.className='duet-pet-menu';node.setAttribute('aria-label',label)}
74
+ const update=value=>{
75
+ state=avatarLocalState(value);badge??=document.createElement('button');badge.type='button';badge.dataset.duetNoticeBadge='';badge.style.cssText='position:fixed;z-index:2147483600;border:0;border-radius:12px;background:#dcefff;color:#185a89;font:12px system-ui;padding:4px 7px;cursor:pointer;pointer-events:auto'
76
+ const count=state.items.filter(i=>i.pending||i.unread).length;badge.textContent=count?String(count):'';badge.setAttribute('aria-label',countLabel());badge.hidden=!count||!state.enabled;badge.onclick=e=>open(e,'pending');if(!badge.isConnected)document.body.append(badge)
77
+ const a=anchor().getBoundingClientRect(),[x,y,w,h]=viewport();badge.style.left=Math.max(x+12,Math.min((a.right??a.left+a.width)-24,x+w-36))+'px';badge.style.top=Math.max(y+12,Math.min(a.top,y+h-30))+'px'
78
+ if(toastId!==state.toast){clearTimeout(timer);clearTimeout(ackTimer);toast?.remove();toast=null;toastId=state.toast;const item=state.items.find(i=>i.id===state.toast);if(item){toast=document.createElement('section');toast.dataset.duetLocalNotice='';decorate(toast,'DSH 任务通知');const p=document.createElement('div');p.dataset.noticeTitle='';p.textContent=`${item.name||'未命名会话'} · ${labels[item.status]}`;toast.append(p,row(item.pending?'去处理':'查看','view','open',item.id),row('收起','dismiss','hide',item.id));document.body.append(toast);place(toast);if(!item.pending)timer=setTimeout(()=>{toast?.remove();toast=null;changed()},8000)}}
79
+ refreshControls();changed()
80
+ }
81
+ const result=value=>{const r=avatarMenuResult(value);if(!r.message)return;clearTimeout(ackTimer);toast?.remove();toast=document.createElement('section');decorate(toast,'操作提示');toast.textContent=r.message;document.body.append(toast);place(toast);changed();ackTimer=setTimeout(()=>{toast?.remove();toast=null;changed()},4000)}
82
+ const reposition=()=>{if(root)place(root);if(toast)place(toast)}
83
+ document.addEventListener('pointerdown',outside,true);document.addEventListener('keydown',keys,true);window.addEventListener('resize',reposition);window.addEventListener('blur',close)
84
+ return{open,close,update,result,get active(){return Boolean(root)},regions(){return[root,toast,badge].filter(n=>n?.isConnected&&!n.hidden).map(n=>{const r=n.getBoundingClientRect();return[r.x,r.y,r.width,r.height]})},dispose(){dead=true;close();style.remove();clearTimeout(timer);clearTimeout(ackTimer);toast?.remove();badge?.remove();document.removeEventListener('pointerdown',outside,true);document.removeEventListener('keydown',keys,true);window.removeEventListener('resize',reposition);window.removeEventListener('blur',close)}}
85
+ }
@@ -0,0 +1,83 @@
1
+ /** Local-only presentation protocol. No remote URLs, credentials or executable payloads. */
2
+ export const AVATAR_LOCAL_PROTOCOL='avatar_local_v1'
3
+ export const NOTICE_KEY='dsh.duet.avatar.notices.v1'
4
+ export const MENU_ACTIONS=['open_dsh','pending','settings','tutorial','hide','notifications','size','bubble','view','dismiss']
5
+ const sizes=['small','medium','large'], statuses=['completed','failed','stopped','approval','question','plan_review']
6
+ export function noticePreferences(storage=globalThis.localStorage){
7
+ try {const p=JSON.parse(storage.getItem(NOTICE_KEY));return {enabled:p?.enabled!==false,snoozeUntil:0,bubble:sizes.includes(p?.bubble)?p.bubble:'medium'}}
8
+ catch{return {enabled:true,snoozeUntil:0,bubble:'medium'}}
9
+ }
10
+ export function saveNoticePreferences(p,storage=globalThis.localStorage){
11
+ const clean={enabled:p.enabled!==false,snoozeUntil:Number.isFinite(p.snoozeUntil)?Math.max(0,p.snoozeUntil):0,bubble:sizes.includes(p.bubble)?p.bubble:'medium'}
12
+ storage.setItem(NOTICE_KEY,JSON.stringify(clean));return clean
13
+ }
14
+ const text=(v,n)=>typeof v==='string'?v.slice(0,n):''
15
+ export function avatarMenuAction(v){
16
+ if(v?.type!=='menu_action'||!MENU_ACTIONS.includes(v.action)||!/^[a-zA-Z0-9-]{1,64}$/.test(v.request_id||''))throw Error('invalid_avatar_menu_action')
17
+ const out={type:'menu_action',request_id:v.request_id,action:v.action}
18
+ if(['size','bubble'].includes(v.action)){if(!sizes.includes(v.value))throw Error('invalid_avatar_size');out.value=v.value}
19
+ if(['view','dismiss'].includes(v.action)){if(typeof v.id!=='string'||!v.id||v.id.length>512)throw Error('invalid_avatar_notice');out.id=v.id}
20
+ if(v.action==='notifications'){if(typeof v.value!=='boolean')throw Error('invalid_avatar_preference');out.value=v.value}
21
+ if(v.action==='snooze'){if(![0,30].includes(v.value))throw Error('invalid_avatar_snooze');out.value=v.value}
22
+ return out
23
+ }
24
+ export function avatarLocalState(v){
25
+ if(v?.type!=='local_state'||v.protocol!==AVATAR_LOCAL_PROTOCOL||!Number.isSafeInteger(v.revision)||v.revision<0||!Array.isArray(v.items)||v.items.length>32)throw Error('invalid_avatar_local_state')
26
+ const items=v.items.map(i=>{
27
+ if(!statuses.includes(i.status)||!i.id||typeof i.id!=='string'||i.id.length>512)throw Error('invalid_avatar_notice')
28
+ return {id:i.id,session_id:text(i.session_id,256),name:text(i.name,100),status:i.status,summary:text(i.summary,240),pending:i.pending===true,unread:i.unread===true}
29
+ })
30
+ while(JSON.stringify(items).length>12000)items.pop()
31
+ return {type:'local_state',protocol:AVATAR_LOCAL_PROTOCOL,revision:v.revision,items,
32
+ size:sizes.includes(v.size)?v.size:'large',bubble:sizes.includes(v.bubble)?v.bubble:'medium',enabled:v.enabled!==false,
33
+ snoozed:v.snoozed===true,running:Math.max(0,Math.min(10000,Number(v.running)||0)),available:v.available===true,
34
+ toast:items.some(i=>i.id===v.toast)?v.toast:null}
35
+ }
36
+ export function avatarMenuResult(v){
37
+ if(v?.type!=='menu_result'||!/^[a-zA-Z0-9-]{1,64}$/.test(v.request_id||''))throw Error('invalid_avatar_menu_result')
38
+ return {type:'menu_result',request_id:v.request_id,ok:v.ok===true,message:text(v.message,180)}
39
+ }
40
+ /** Incremental snapshots, scope fencing and stable IDs; never infer success from text. */
41
+ export class AvatarNotices {
42
+ constructor(){this.items=new Map();this.seen=new Set();this.dismissed=new Set();this.scope=null;this.epoch=null;this.revision=0;this.order=0;this.toast=null;this.toastAt=0;this.running=0}
43
+ update({scope,epoch,sessions=[],results=[],interactions=[]}){
44
+ if(scope!==this.scope||epoch!==this.epoch){this.items.clear();this.seen.clear();this.dismissed.clear();this.toast=null;this.scope=scope;this.epoch=epoch}
45
+ const allowed=new Map(sessions.filter(s=>!s.archived&&s.origin!=='subagent').map(s=>[s.session_id,s]))
46
+ this.running=[...allowed.values()].filter(s=>s.running===true).length
47
+ for(const [id,item]of this.items)if(!allowed.has(item.session_id))this.items.delete(id)
48
+ const pending=new Set()
49
+ for(const p of interactions){
50
+ if(!allowed.has(p.session_id)||!['approval','question','plan_review'].includes(p.kind)||!p.id)continue
51
+ const id='pending:'+p.id;pending.add(id)
52
+ const row=allowed.get(p.session_id),old=this.items.get(id)
53
+ const summary=p.kind==='approval'?p.reason:(p.questions?.[0]?.question||p.questions?.[0]?.text||'请到 DSH 查看并回答')
54
+ this.items.set(id,{id,order:old?.order??++this.order,session_id:p.session_id,name:row.label,status:p.kind,summary:typeof summary==='string'?summary.slice(0,240):'',pending:true,unread:old?.unread??true})
55
+ if(!old){this.toast=id;this.toastAt=Date.now()}
56
+ }
57
+ for(const[id,item]of this.items)if(item.pending&&!pending.has(id))this.items.delete(id)
58
+ for(const job of results){
59
+ if(!allowed.has(job.session_id)||!Number.isSafeInteger(job.completion_seq)||typeof job.id!=='string')continue
60
+ const id=`job:${epoch}:${job.id}:${job.completion_seq}`;if(this.seen.has(id))continue
61
+ this.seen.add(id)
62
+ const status=job.turn_end_reason==='aborted'?'stopped':job.status==='failed'?'failed':job.status==='succeeded'&&job.turn_end_reason==='completed'?'completed':null
63
+ if(!status)continue
64
+ const row=allowed.get(job.session_id)
65
+ this.items.set(id,{id,order:++this.order,session_id:job.session_id,name:row.label,status,summary:status==='failed'?text(job.error,240):'',pending:false,unread:true})
66
+ this.toast=id;this.toastAt=Date.now()
67
+ }
68
+ while(this.seen.size>1024)this.seen.delete(this.seen.values().next().value)
69
+ const rows=[...this.items.values()].sort((a,b)=>Number(b.pending)-Number(a.pending)||Number(b.unread)-Number(a.unread)||b.order-a.order)
70
+ this.items=new Map(rows.slice(0,32).map(i=>[i.id,i]))
71
+ if(!this.items.has(this.toast))this.toast=null
72
+ for(const id of this.dismissed)if(!this.items.has(id))this.dismissed.delete(id)
73
+ this.revision++
74
+ }
75
+ read(id){const item=this.items.get(id);if(item)item.unread=false;if(this.toast===id)this.toast=null;this.revision++}
76
+ dismiss(id){if(this.items.has(id))this.dismissed.add(id);if(this.toast===id)this.toast=null;this.revision++}
77
+ state(prefs,size,available=true){
78
+ const pending=[...this.items.values()].find(i=>i.pending&&i.unread&&!this.dismissed.has(i.id))
79
+ const toast=pending?.id??(Date.now()-this.toastAt<=8000?this.toast:null)
80
+ return avatarLocalState({type:'local_state',protocol:AVATAR_LOCAL_PROTOCOL,revision:this.revision,items:[...this.items.values()],
81
+ ...prefs,size,available,running:this.running,snoozed:prefs.snoozeUntil>Date.now(),toast:available&&prefs.enabled&&prefs.snoozeUntil<=Date.now()?toast:null})
82
+ }
83
+ }
@@ -0,0 +1,24 @@
1
+ /** Bounded presentation-only IPC: never transfer DOM, HTML, tickets or callbacks. */
2
+ export const AVATAR_UI_PROTOCOL = 2
3
+ export function avatarSurface(value) {
4
+ if(value?.type!=='surface')throw Error('invalid_surface')
5
+ if(value.panel===null)return {type:'surface',panel:null}
6
+ const p=value.panel
7
+ if(!p||!/^s\d+$/.test(p.id)||!Number.isSafeInteger(p.revision)||p.revision<1||!Array.isArray(p.nodes)||p.nodes.length>160)throw Error('invalid_surface')
8
+ let length=0
9
+ const nodes=p.nodes.map(n=>{
10
+ if(!n||!['text','heading','button','checkbox','break'].includes(n.kind)||typeof n.text!=='string'||n.text.length>4000)throw Error('invalid_surface')
11
+ length+=n.text.length;if(length>10000)throw Error('invalid_surface')
12
+ const node={kind:n.kind,text:n.text}
13
+ if(n.kind==='button'||n.kind==='checkbox') {
14
+ if(!/^a\d+$/.test(n.action))throw Error('invalid_surface')
15
+ Object.assign(node,{action:n.action,disabled:n.disabled===true,checked:n.checked===true,gesture:n.gesture===true,label:String(n.label||'').slice(0,100)})
16
+ }
17
+ return node
18
+ })
19
+ return {type:'surface',panel:{id:p.id,revision:p.revision,nodes,target:['online','tts_only'].includes(p.target)?p.target:null}}
20
+ }
21
+ export function avatarSurfaceAction(v) {
22
+ if(v?.type!=='surface_action'||!/^s\d+$/.test(v.id)||!/^a\d+$/.test(v.action)||!Number.isSafeInteger(v.revision)||v.revision<1)throw Error('invalid_surface_action')
23
+ return {type:'surface_action',id:v.id,revision:v.revision,action:v.action,checked:v.checked===true}
24
+ }
@@ -0,0 +1,91 @@
1
+ import {avatarSize,AVATAR_SIZES} from './avatar.mjs'
2
+ const sizes=Object.keys(AVATAR_SIZES),names={large:'大(100%)',medium:'中(75%)',small:'小(50%)'}
3
+ export const nextAvatarSize=value=>sizes[(sizes.indexOf(avatarSize(value))+1)%sizes.length]
4
+ export function sizeButton(button,value,{label=false}={}) {
5
+ const size=avatarSize(value),title=`形象大小:${names[size]},点击切换为${names[nextAvatarSize(size)]}`
6
+ button.type='button';button.dataset.size=size;button.setAttribute('aria-label',title);button.title=title
7
+ const squares=sizes.filter(s=>s!==size).concat(size).map(s=>{
8
+ const side={large:18,medium:12,small:6}[s]
9
+ return `<rect data-size-square="${s}" x="3" y="${21-side}" width="${side}" height="${side}" stroke-width="${s===size?'2.8':'1'}"/>`
10
+ }).join('')
11
+ button.innerHTML=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true">${squares}</svg>${label?`<span>${names[size]}</span>`:''}`
12
+ }
13
+
14
+ /** Same local confirmation in settings, web and the native companion. */
15
+ export function avatarCloseConfirmation({onChange=()=>{},floating=false,origin='page',anchor=()=>null,viewport=()=>[0,0,innerWidth,innerHeight]}={}) {
16
+ let pending=null,resolve,node,previous,dead=false
17
+ const position=()=>{
18
+ if(!floating||!node)return
19
+ const r=anchor()?.getBoundingClientRect();if(!r)return
20
+ const b=node.getBoundingClientRect()
21
+ const [x,y,w,h]=viewport()
22
+ const top=r.top-b.height-16>=y+12?r.top-b.height-16:r.bottom+12
23
+ node.style.left=Math.max(x+12,Math.min(r.left+r.width/2-b.width/2,x+w-b.width-12))+'px'
24
+ node.style.top=Math.max(y+12,Math.min(top,y+h-b.height-12))+'px'
25
+ node.style.bottom='auto'
26
+ }
27
+ const finish=accepted=>{
28
+ if(!pending)return
29
+ const done=resolve;pending=null;resolve=null
30
+ document.removeEventListener('keydown',keys,true);window.removeEventListener('resize',position);node?.remove();node=null
31
+ if(previous?.isConnected)previous.focus({preventScroll:true})
32
+ onChange();done(accepted)
33
+ }
34
+ const keys=e=>{
35
+ if(e.key==='Escape'){e.preventDefault();e.stopImmediatePropagation();finish(false)}
36
+ else if(e.key==='Tab'&&!floating){
37
+ e.preventDefault();const buttons=[...node.querySelectorAll('button')],index=buttons.indexOf(document.activeElement)
38
+ buttons[(index+(e.shiftKey?-1:1)+buttons.length)%buttons.length].focus()
39
+ }
40
+ }
41
+ return {
42
+ ask(){
43
+ if(dead)return Promise.resolve(false)
44
+ if(pending)return pending
45
+ previous=document.activeElement
46
+ pending=new Promise(r=>resolve=r)
47
+ node=document.createElement('div');node.dataset.avatarCloseOverlay=''
48
+ node.style.cssText='position:fixed;inset:0;z-index:2147483600;display:flex;align-items:center;justify-content:center;padding:12px;box-sizing:border-box;background:#0003;pointer-events:auto'
49
+ if(floating){node.dataset.duetAvatarSurface='110';node.dataset.duetSurfaceOrigin=origin;node.style.cssText='position:fixed;left:12px;bottom:100px;width:260px;max-width:calc(100vw - 24px);z-index:2147483600;pointer-events:auto'}
50
+ const panel=document.createElement('div');panel.dataset.avatarCloseConfirm=''
51
+ panel.setAttribute('role','alertdialog');panel.setAttribute('aria-modal',String(!floating));panel.setAttribute('aria-label','隐藏拟人角色?')
52
+ panel.style.cssText='box-sizing:border-box;width:260px;max-width:100%;padding:16px;border:1px solid #8dc5ed55;border-radius:16px;background:#142638;color:#e9f4ff;font:13px/1.6 system-ui;box-shadow:0 8px 28px #0005'
53
+ const title=document.createElement('div');title.textContent='隐藏拟人角色?';title.style.cssText='font-size:14px;font-weight:600;margin-bottom:14px'
54
+ const row=document.createElement('div');row.style.cssText='display:flex;justify-content:flex-end;gap:8px'
55
+ for(const [text,accept] of [['取消',false],['隐藏拟人角色',true]]){
56
+ const button=document.createElement('button');button.type='button';button.textContent=text;button.dataset.avatarCloseChoice=accept?'confirm':'cancel'
57
+ button.style.cssText=`font:13px system-ui;display:block;width:auto;min-width:56px;min-height:32px;padding:6px 10px;border:0;border-radius:8px;cursor:pointer;background:${accept?'#dcefff':'#294154'};color:${accept?'#185a89':'#e9f4ff'}`
58
+ button.onclick=()=>finish(accept);row.append(button)
59
+ }
60
+ panel.append(title,row);node.append(panel);document.body.append(node)
61
+ document.addEventListener('keydown',keys,true);window.addEventListener('resize',position);position();row.firstChild.focus();onChange()
62
+ return pending
63
+ },
64
+ cancel(){finish(false)},
65
+ dispose(){dead=true;finish(false)},
66
+ get element(){return node},
67
+ }
68
+ }
69
+
70
+ /** The real playback-page click stays here; native projection cannot grant activation. */
71
+ export function audioUnlockPanel({onEnable,onCancel}) {
72
+ const panel=document.createElement('section')
73
+ panel.dataset.duetAvatarSurface='95';panel.dataset.duetSurfaceOrigin='avatar';panel.dataset.duetAudioUnlock=''
74
+ panel.setAttribute('role','region');panel.setAttribute('aria-label','启用 duet 声音')
75
+ panel.style.cssText='position:fixed;z-index:100030;right:12px;bottom:88px;box-sizing:border-box;width:320px;max-width:calc(100vw - 24px);max-height:calc(100vh - 100px);overflow:auto;padding:22px;border-radius:20px;background:linear-gradient(145deg,#20364b,#142333);color:#edf6ff;border:1px solid #8dc5ed55;font:14px/1.65 system-ui,sans-serif;box-shadow:0 16px 48px #07152240;isolation:isolate;text-align:left'
76
+ const style=document.createElement('style')
77
+ style.textContent='[data-duet-audio-unlock] button:hover{filter:brightness(1.12)}[data-duet-audio-unlock] button:focus-visible{outline:2px solid #a4dcff;outline-offset:3px}[data-duet-audio-unlock] button:active{transform:translateY(1px)}'
78
+ const brand=document.createElement('div');brand.setAttribute('aria-hidden','true');brand.textContent='duet';brand.style.cssText='font:750 25px/1.2 system-ui;letter-spacing:-1px;margin:0 0 17px;color:#edf6ff'
79
+ const dot=document.createElement('span');dot.textContent='.';dot.style.color='#ed9b35';brand.append(dot)
80
+ const title=document.createElement('h3');title.textContent='音频播放权限';title.style.cssText='font:650 18px/1.4 system-ui;margin:0 0 8px;color:#edf6ff'
81
+ const text=document.createElement('p');text.textContent='点击启动音频播放权限。';text.style.cssText='font:14px/1.75 system-ui;margin:0;color:#bdcedf;white-space:normal;overflow-wrap:anywhere'
82
+ const actions=document.createElement('div');actions.style.cssText='display:flex;flex-wrap:wrap;justify-content:flex-end;gap:10px;margin-top:22px'
83
+ for(const [label,primary,callback] of [['暂不开启',false,onCancel],['启动音频播放',true,onEnable]]){
84
+ const button=document.createElement('button');button.type='button';button.textContent=label
85
+ button.style.cssText='appearance:none;box-sizing:border-box;display:inline-flex;align-items:center;justify-content:center;min-height:40px;padding:9px 16px;border-radius:11px;font:600 14px/1.4 system-ui;cursor:pointer;white-space:nowrap;'+(primary?'background:#dcefff;color:#185a89;border:1px solid #dcefff;box-shadow:0 3px 10px #0002':'background:#ffffff08;color:#c2d3e3;border:1px solid #8dc5ed40')
86
+ if(primary)button.dataset.duetUserGesture=''
87
+ button.onclick=callback;actions.append(button)
88
+ }
89
+ panel.append(style,brand,title,text,actions)
90
+ return panel
91
+ }
@@ -0,0 +1,125 @@
1
+ /** Local presentation only: never forwarded to the voice service. */
2
+ export const AVATAR_KEY = 'dsh.duet.avatar.v1'
3
+ export const AVATAR_SIZES = Object.freeze({large:1,medium:.75,small:.5})
4
+ export const avatarSize = value => Object.hasOwn(AVATAR_SIZES,value) ? value : 'large'
5
+ export const avatarScale = value => AVATAR_SIZES[avatarSize(value)]
6
+ export const AVATAR_DEFAULTS = Object.freeze({ enabled: true, webOnly: false, size:'large' })
7
+
8
+ // A suspended event loop cannot exchange heartbeats. Give it a fresh grace
9
+ // period on resume, while still expiring a silent peer during normal ticks.
10
+ export class AvatarHeartbeat {
11
+ constructor(interval=15000,now=Date.now(),timeout=60000){this.interval=interval;this.timeout=timeout;this.last=this.tick=now}
12
+ touch(now=Date.now()){this.last=now}
13
+ expired(now=Date.now()){
14
+ if(now-this.tick>this.interval*2||now<this.tick)this.last=now
15
+ this.tick=now
16
+ return now-this.last>this.timeout
17
+ }
18
+ }
19
+
20
+ export const AVATAR_PRESENTATION_LABELS=Object.freeze({
21
+ off:'当前显示:已关闭',desktop:'当前显示:桌面浮动窗口',
22
+ connecting:'当前显示:正在启动桌面窗口',recovering:'当前显示:桌面连接恢复中',
23
+ other:'当前显示:由另一个 DSH 页面管理桌面窗口',web:'当前显示:网页内',
24
+ fallback:'当前显示:网页内(桌面组件暂不可用)',unavailable:'当前显示:形象加载失败',
25
+ })
26
+
27
+ // TTS text is a cumulative prefix, not word timestamps. Bind its new suffix to
28
+ // the PCM chunk's playback interval; never use ahead-of-audio LLM text deltas.
29
+ export function captionCue(response, event) {
30
+ const text = typeof event.text === 'string' ? event.text.slice(0, 4000) : ''
31
+ const previous = response.captionSource || ''
32
+ const sameSegment = response.captionSegment === event.segment_id
33
+ const add = !text ? '' : sameSegment && text.startsWith(previous) ? text.slice(previous.length)
34
+ : sameSegment && previous.startsWith(text) ? '' : text
35
+ const cue = { from: response.captionText || '', add }
36
+ response.captionText = (cue.from + add).slice(-240)
37
+ if (text) { response.captionSource = text; response.captionSegment = event.segment_id }
38
+ return cue
39
+ }
40
+ export function captionAt(cue, fraction) {
41
+ if (!cue) return ''
42
+ const chars = Array.from(cue.add)
43
+ return (cue.from + chars.slice(0, Math.floor(chars.length * Math.max(0, Math.min(1, fraction)))).join('')).slice(-240)
44
+ }
45
+
46
+ /** Sample-clock subtitles. Late/duplicate metadata cannot rewind visible text. */
47
+ export class AudioCaptionTimeline {
48
+ constructor() { this.responses = new Map() }
49
+ ingestDelta(key, event, present) {
50
+ if (!Number.isSafeInteger(event.audio_sample_end) || event.audio_sample_end < 0) return
51
+ const state = this.responses.get(key) || {cues:[],shownEnd:-1,text:'',receivedText:'',lastReceivedEnd:-1,seen:new Set()}
52
+ state.seen ??= new Set()
53
+ if (event.audio_sample_end < (state.lastReceivedEnd ?? -1) ||
54
+ (event.event_id && state.seen.has(event.event_id))) return
55
+ const delta = event.type === 'response.output_text.delta' ? event.delta : ''
56
+ if (typeof delta !== 'string' || delta.length > 8000 || state.cues.length >= 1024) return
57
+ state.receivedText = ((state.receivedText || '') + delta).slice(0,8000)
58
+ state.lastReceivedEnd = event.audio_sample_end
59
+ if(event.event_id)state.seen.add(event.event_id)
60
+ while(state.seen.size>2048)state.seen.delete(state.seen.values().next().value)
61
+ const {full_text, text, ...safe} = event
62
+ state.cues.push({sample_end:event.audio_sample_end,text_prefix:state.receivedText,event:safe,present})
63
+ this.responses.set(key,state)
64
+ while(this.responses.size>16)this.responses.delete(this.responses.keys().next().value)
65
+ }
66
+ ingest(key, cues) {
67
+ if (!Array.isArray(cues)) return
68
+ const state = this.responses.get(key) || { cues: [], shownEnd: -1, text: '' }
69
+ for (const cue of cues.slice(0, 128)) {
70
+ if (!Number.isSafeInteger(cue?.sample_end) || cue.sample_end < 0 ||
71
+ typeof cue.text_prefix !== 'string' || cue.text_prefix.length > 8000 ||
72
+ cue.sample_end <= state.shownEnd) continue
73
+ if (!state.cues.some(c => c.sample_end === cue.sample_end)) state.cues.push(cue)
74
+ }
75
+ state.cues.sort((a,b)=>a.sample_end-b.sample_end)
76
+ // Bound future metadata without discarding the nearest playback markers.
77
+ state.cues = state.cues.slice(0,1024)
78
+ this.responses.set(key,state)
79
+ while (this.responses.size > 16) this.responses.delete(this.responses.keys().next().value)
80
+ }
81
+ text(key, playedSamples) {
82
+ const state = this.responses.get(key)
83
+ if (!state) return null
84
+ while (state.cues.length && state.cues[0].sample_end <= playedSamples) {
85
+ const cue = state.cues.shift()
86
+ if (cue.sample_end >= state.shownEnd && cue.text_prefix.startsWith(state.text)) {
87
+ state.shownEnd = cue.sample_end; state.text = cue.text_prefix
88
+ cue.present?.(cue.event)
89
+ }
90
+ }
91
+ return state.text.slice(-240)
92
+ }
93
+ clear() { this.responses.clear() }
94
+ discardPending(key) { const state=this.responses.get(key);if(state)state.cues=[] }
95
+ }
96
+ export function avatarPreferences(storage = globalThis.localStorage) {
97
+ try {
98
+ const value = JSON.parse(storage.getItem(AVATAR_KEY))
99
+ return { enabled: value?.enabled !== false, webOnly: value?.webOnly === true, size:avatarSize(value?.size) }
100
+ } catch { return { ...AVATAR_DEFAULTS } }
101
+ }
102
+ export function saveAvatarPreferences(value, storage = globalThis.localStorage) {
103
+ const clean = { enabled: value.enabled === true, webOnly: value.webOnly === true, size:avatarSize(value.size) }
104
+ storage.setItem(AVATAR_KEY, JSON.stringify(clean))
105
+ return clean
106
+ }
107
+ export function expressionFor(text, random = Math.random) {
108
+ if (/(哈哈|呵呵|笑死|好笑|开心)/u.test(text)) return 'laugh'
109
+ if (/(不行|不是|不能|不要|不对|不可以|没有|拒绝|^不[,。!!\s]*$)/u.test(text)) return 'shake'
110
+ if (/(好的|好嘞|收到|可以|明白|没问题|对的|是的|完成了|^好[,。!!\s]*$)/u.test(text)) return 'nod'
111
+ return ['glance_left', 'glance_right', 'tilt'][Math.min(2, Math.floor(random() * 3))]
112
+ }
113
+ export function avatarFrame(value) {
114
+ if (!value || !['off', 'online', 'tts_only'].includes(value.mode)) throw Error('invalid_avatar_frame')
115
+ if (!Number.isFinite(value.rms) || value.rms < 0 || value.rms > 1) throw Error('invalid_avatar_frame')
116
+ return { type: 'frame', mode: value.mode, ready: value.ready === true, rms: value.rms, size:avatarSize(value.size),
117
+ viseme: ['A','I','U','E','O'].includes(value.viseme) ? value.viseme : 'A',
118
+ text: typeof value.text === 'string' ? value.text.slice(-240) : '',
119
+ utterance: typeof value.utterance === 'string' ? value.utterance.slice(0, 100) : '' }
120
+ }
121
+
122
+ export function avatarInputEffect(value) {
123
+ if(value?.type!=='input_effect'||typeof value.text!=='string'||!value.text||value.text.length>600)throw Error('invalid_avatar_input_effect')
124
+ return {type:'input_effect',text:value.text}
125
+ }
@@ -0,0 +1,13 @@
1
+ /** Assistant nickname validation, shared by settings and voice actions. */
2
+ export const NICKNAME_LIMIT = '昵称最多5个汉字或2个英文单词;中英混用最多5个字符'
3
+ export function normalizeNickname(value) {
4
+ if (typeof value !== 'string') throw new Error(NICKNAME_LIMIT)
5
+ const name = value.trim()
6
+ const chinese = /^\p{Script=Han}{1,5}$/u.test(name)
7
+ const english = /^[A-Za-z]+(?:['-][A-Za-z]+)*(?: [A-Za-z]+(?:['-][A-Za-z]+)*)?$/.test(name)
8
+ const mixed = /\p{Script=Han}/u.test(name) && /[A-Za-z]/.test(name)
9
+ && /^[\p{Script=Han}A-Za-z]+(?:[ '-][\p{Script=Han}A-Za-z]+)*$/u.test(name)
10
+ && Array.from(name).length <= 5
11
+ if (!chinese && !english && !mixed) throw new Error(NICKNAME_LIMIT)
12
+ return name
13
+ }
@@ -1,5 +1,5 @@
1
1
  /** Desired voice mode is independent of a temporarily suspended connection. */
2
- export const PLUGIN_VERSION = '0.1.9'
2
+ export const PLUGIN_VERSION = '0.2.0'
3
3
  export const IDLE_RELEASE_MS = 60_000
4
4
 
5
5
  const safeVersion = value => typeof value === 'string' && value.length <= 32 && /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(value) ? value : ''