@michengai/dsh-im-connect 0.1.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/LICENSE +201 -0
- package/README.md +39 -0
- package/client.js +1479 -0
- package/cordis.patch.yml +4 -0
- package/lib/channels/dingtalk-card.d.ts +24 -0
- package/lib/channels/dingtalk-card.d.ts.map +1 -0
- package/lib/channels/dingtalk-card.js +182 -0
- package/lib/channels/dingtalk-card.js.map +1 -0
- package/lib/channels/dingtalk.d.ts +7 -0
- package/lib/channels/dingtalk.d.ts.map +1 -0
- package/lib/channels/dingtalk.js +107 -0
- package/lib/channels/dingtalk.js.map +1 -0
- package/lib/channels/factory.d.ts +4 -0
- package/lib/channels/factory.d.ts.map +1 -0
- package/lib/channels/factory.js +24 -0
- package/lib/channels/factory.js.map +1 -0
- package/lib/channels/feishu.d.ts +8 -0
- package/lib/channels/feishu.d.ts.map +1 -0
- package/lib/channels/feishu.js +73 -0
- package/lib/channels/feishu.js.map +1 -0
- package/lib/channels/meta.d.ts +20 -0
- package/lib/channels/meta.d.ts.map +1 -0
- package/lib/channels/meta.js +69 -0
- package/lib/channels/meta.js.map +1 -0
- package/lib/channels/qr/dingtalk.d.ts +12 -0
- package/lib/channels/qr/dingtalk.d.ts.map +1 -0
- package/lib/channels/qr/dingtalk.js +69 -0
- package/lib/channels/qr/dingtalk.js.map +1 -0
- package/lib/channels/qr/feishu.d.ts +14 -0
- package/lib/channels/qr/feishu.d.ts.map +1 -0
- package/lib/channels/qr/feishu.js +87 -0
- package/lib/channels/qr/feishu.js.map +1 -0
- package/lib/channels/qr/hub.d.ts +22 -0
- package/lib/channels/qr/hub.d.ts.map +1 -0
- package/lib/channels/qr/hub.js +193 -0
- package/lib/channels/qr/hub.js.map +1 -0
- package/lib/channels/qr/render.d.ts +3 -0
- package/lib/channels/qr/render.d.ts.map +1 -0
- package/lib/channels/qr/render.js +9 -0
- package/lib/channels/qr/render.js.map +1 -0
- package/lib/channels/qr/shared.d.ts +39 -0
- package/lib/channels/qr/shared.d.ts.map +1 -0
- package/lib/channels/qr/shared.js +51 -0
- package/lib/channels/qr/shared.js.map +1 -0
- package/lib/channels/qr/wecom.d.ts +10 -0
- package/lib/channels/qr/wecom.d.ts.map +1 -0
- package/lib/channels/qr/wecom.js +81 -0
- package/lib/channels/qr/wecom.js.map +1 -0
- package/lib/channels/qr/weixin.d.ts +10 -0
- package/lib/channels/qr/weixin.d.ts.map +1 -0
- package/lib/channels/qr/weixin.js +77 -0
- package/lib/channels/qr/weixin.js.map +1 -0
- package/lib/channels/telegram.d.ts +7 -0
- package/lib/channels/telegram.d.ts.map +1 -0
- package/lib/channels/telegram.js +133 -0
- package/lib/channels/telegram.js.map +1 -0
- package/lib/channels/wecom.d.ts +28 -0
- package/lib/channels/wecom.d.ts.map +1 -0
- package/lib/channels/wecom.js +168 -0
- package/lib/channels/wecom.js.map +1 -0
- package/lib/channels/weixin.d.ts +41 -0
- package/lib/channels/weixin.d.ts.map +1 -0
- package/lib/channels/weixin.js +678 -0
- package/lib/channels/weixin.js.map +1 -0
- package/lib/client.js +1479 -0
- package/lib/engine/access.d.ts +11 -0
- package/lib/engine/access.d.ts.map +1 -0
- package/lib/engine/access.js +11 -0
- package/lib/engine/access.js.map +1 -0
- package/lib/engine/agent-options.d.ts +25 -0
- package/lib/engine/agent-options.d.ts.map +1 -0
- package/lib/engine/agent-options.js +19 -0
- package/lib/engine/agent-options.js.map +1 -0
- package/lib/engine/approval.d.ts +9 -0
- package/lib/engine/approval.d.ts.map +1 -0
- package/lib/engine/approval.js +38 -0
- package/lib/engine/approval.js.map +1 -0
- package/lib/engine/assistant-settings.d.ts +17 -0
- package/lib/engine/assistant-settings.d.ts.map +1 -0
- package/lib/engine/assistant-settings.js +35 -0
- package/lib/engine/assistant-settings.js.map +1 -0
- package/lib/engine/credentials.d.ts +17 -0
- package/lib/engine/credentials.d.ts.map +1 -0
- package/lib/engine/credentials.js +51 -0
- package/lib/engine/credentials.js.map +1 -0
- package/lib/engine/gateway.d.ts +46 -0
- package/lib/engine/gateway.d.ts.map +1 -0
- package/lib/engine/gateway.js +333 -0
- package/lib/engine/gateway.js.map +1 -0
- package/lib/engine/json-state.d.ts +8 -0
- package/lib/engine/json-state.d.ts.map +1 -0
- package/lib/engine/json-state.js +24 -0
- package/lib/engine/json-state.js.map +1 -0
- package/lib/engine/merge.d.ts +21 -0
- package/lib/engine/merge.d.ts.map +1 -0
- package/lib/engine/merge.js +55 -0
- package/lib/engine/merge.js.map +1 -0
- package/lib/engine/router.d.ts +88 -0
- package/lib/engine/router.d.ts.map +1 -0
- package/lib/engine/router.js +309 -0
- package/lib/engine/router.js.map +1 -0
- package/lib/engine/seen-store.d.ts +12 -0
- package/lib/engine/seen-store.d.ts.map +1 -0
- package/lib/engine/seen-store.js +38 -0
- package/lib/engine/seen-store.js.map +1 -0
- package/lib/engine/session-id.d.ts +30 -0
- package/lib/engine/session-id.d.ts.map +1 -0
- package/lib/engine/session-id.js +53 -0
- package/lib/engine/session-id.js.map +1 -0
- package/lib/engine/session-store.d.ts +13 -0
- package/lib/engine/session-store.d.ts.map +1 -0
- package/lib/engine/session-store.js +38 -0
- package/lib/engine/session-store.js.map +1 -0
- package/lib/engine/split.d.ts +2 -0
- package/lib/engine/split.d.ts.map +1 -0
- package/lib/engine/split.js +41 -0
- package/lib/engine/split.js.map +1 -0
- package/lib/engine/types.d.ts +52 -0
- package/lib/engine/types.d.ts.map +1 -0
- package/lib/engine/types.js +2 -0
- package/lib/engine/types.js.map +1 -0
- package/lib/index.d.ts +22 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +53 -0
- package/lib/index.js.map +1 -0
- package/lib/manager.d.ts +103 -0
- package/lib/manager.d.ts.map +1 -0
- package/lib/manager.js +543 -0
- package/lib/manager.js.map +1 -0
- package/package.json +63 -0
- package/src/channels/dingtalk-card.ts +191 -0
- package/src/channels/dingtalk.ts +113 -0
- package/src/channels/factory.ts +32 -0
- package/src/channels/feishu.ts +77 -0
- package/src/channels/meta.ts +89 -0
- package/src/channels/qr/dingtalk.ts +71 -0
- package/src/channels/qr/feishu.ts +90 -0
- package/src/channels/qr/hub.ts +206 -0
- package/src/channels/qr/render.ts +7 -0
- package/src/channels/qr/shared.ts +80 -0
- package/src/channels/qr/wecom.ts +78 -0
- package/src/channels/qr/weixin.ts +78 -0
- package/src/channels/telegram.ts +145 -0
- package/src/channels/wecom.ts +182 -0
- package/src/channels/weixin.ts +712 -0
- package/src/engine/access.ts +17 -0
- package/src/engine/agent-options.ts +24 -0
- package/src/engine/approval.ts +45 -0
- package/src/engine/assistant-settings.ts +41 -0
- package/src/engine/credentials.ts +64 -0
- package/src/engine/gateway.ts +330 -0
- package/src/engine/json-state.ts +20 -0
- package/src/engine/merge.ts +60 -0
- package/src/engine/router.ts +333 -0
- package/src/engine/seen-store.ts +36 -0
- package/src/engine/session-id.ts +65 -0
- package/src/engine/session-store.ts +45 -0
- package/src/engine/split.ts +29 -0
- package/src/engine/types.ts +55 -0
- package/src/index.ts +81 -0
- package/src/manager.ts +571 -0
- package/src/optional-modules.d.ts +13 -0
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** 谁可以驱动本机助手。 */
|
|
2
|
+
export type AccessDecision = 'allow' | 'deny-dm' | 'deny-group-silent' | 'ignore'
|
|
3
|
+
|
|
4
|
+
export function decideAccess(input: {
|
|
5
|
+
allowAll: boolean
|
|
6
|
+
channelOpen: boolean
|
|
7
|
+
userAllowed: boolean
|
|
8
|
+
groupAllowed: boolean
|
|
9
|
+
kind?: 'dm' | 'group'
|
|
10
|
+
addressed?: boolean
|
|
11
|
+
}): AccessDecision {
|
|
12
|
+
const kind = input.kind === 'group' ? 'group' : 'dm'
|
|
13
|
+
if (kind === 'group' && input.addressed === false) return 'ignore'
|
|
14
|
+
if (input.allowAll || input.channelOpen || input.userAllowed) return 'allow'
|
|
15
|
+
if (kind === 'group' && input.groupAllowed) return 'allow'
|
|
16
|
+
return kind === 'group' ? 'deny-group-silent' : 'deny-dm'
|
|
17
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** 解析 IM 会话要用的模型,禁止把空字符串传给 agents.create。 */
|
|
2
|
+
export function resolveImAgentOptions(input: {
|
|
3
|
+
provider?: string
|
|
4
|
+
model?: string
|
|
5
|
+
fallback?: { provider?: string; model?: string }
|
|
6
|
+
}): { provider: string; model: string } {
|
|
7
|
+
const provider = input.provider?.trim() || input.fallback?.provider?.trim() || ''
|
|
8
|
+
const model = input.model?.trim() || input.fallback?.model?.trim() || ''
|
|
9
|
+
if (!provider || !model) {
|
|
10
|
+
throw new Error('请先在设置 → IM助理 页面选择模型。')
|
|
11
|
+
}
|
|
12
|
+
return { provider, model }
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** 用 ctx.get 读默认模型,避免未 inject 时直接访问属性抛错。 */
|
|
16
|
+
export function readHostDefaultModel(ctx: {
|
|
17
|
+
get?(name: string): { currentSelection?: () => { provider?: string; model?: string } } | undefined
|
|
18
|
+
}): { provider?: string; model?: string } | undefined {
|
|
19
|
+
try {
|
|
20
|
+
return ctx.get?.('agentDefaultModel')?.currentSelection?.()
|
|
21
|
+
} catch {
|
|
22
|
+
return undefined
|
|
23
|
+
}
|
|
24
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
export type ApprovalVerdict = 'allow' | 'reject' | undefined
|
|
2
|
+
|
|
3
|
+
interface Pending {
|
|
4
|
+
resolve: (value: ApprovalVerdict) => void
|
|
5
|
+
timer: NodeJS.Timeout
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export class ApprovalBroker {
|
|
9
|
+
private readonly pending = new Map<string, Pending>()
|
|
10
|
+
|
|
11
|
+
get size(): number {
|
|
12
|
+
return this.pending.size
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
wait(key: string, timeoutMs: number): Promise<ApprovalVerdict> {
|
|
16
|
+
if (this.pending.has(key)) return Promise.resolve(undefined)
|
|
17
|
+
return new Promise((resolve) => {
|
|
18
|
+
const settle = (value: ApprovalVerdict) => {
|
|
19
|
+
const entry = this.pending.get(key)
|
|
20
|
+
if (!entry) return
|
|
21
|
+
clearTimeout(entry.timer)
|
|
22
|
+
this.pending.delete(key)
|
|
23
|
+
resolve(value)
|
|
24
|
+
}
|
|
25
|
+
const timer = setTimeout(() => settle(undefined), timeoutMs)
|
|
26
|
+
timer.unref?.()
|
|
27
|
+
this.pending.set(key, { resolve: settle, timer })
|
|
28
|
+
})
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
answer(key: string, allow: boolean): boolean {
|
|
32
|
+
const entry = this.pending.get(key)
|
|
33
|
+
if (!entry) return false
|
|
34
|
+
entry.resolve(allow ? 'allow' : 'reject')
|
|
35
|
+
return true
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
dispose(): void {
|
|
39
|
+
for (const [key, entry] of this.pending) {
|
|
40
|
+
clearTimeout(entry.timer)
|
|
41
|
+
entry.resolve(undefined)
|
|
42
|
+
this.pending.delete(key)
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/** IM 助理页选择的模型。 */
|
|
2
|
+
export interface AssistantModel {
|
|
3
|
+
provider: string
|
|
4
|
+
model: string
|
|
5
|
+
reasoningEffort?: string
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export type PermissionPreset = 'read-only' | 'workspace-write' | 'full-access'
|
|
9
|
+
|
|
10
|
+
export function normalizeAssistantModel(input: { provider?: unknown; model?: unknown; reasoningEffort?: unknown }): AssistantModel | undefined {
|
|
11
|
+
const provider = typeof input.provider === 'string' ? input.provider.trim() : ''
|
|
12
|
+
const model = typeof input.model === 'string' ? input.model.trim() : ''
|
|
13
|
+
if (!provider || !model) return undefined
|
|
14
|
+
const reasoningEffort = normalizeEffort(input.reasoningEffort)
|
|
15
|
+
return reasoningEffort ? { provider, model, reasoningEffort } : { provider, model }
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function pickAssistantModel(...candidates: Array<AssistantModel | undefined>): AssistantModel | undefined {
|
|
19
|
+
for (const item of candidates) {
|
|
20
|
+
if (item?.provider && item.model) return item
|
|
21
|
+
}
|
|
22
|
+
return undefined
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function normalizeWorkspacePath(input: unknown): string | undefined {
|
|
26
|
+
if (typeof input !== 'string') return undefined
|
|
27
|
+
const cwd = input.trim()
|
|
28
|
+
return cwd === '' ? undefined : cwd
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function normalizePermission(input: unknown): PermissionPreset | undefined {
|
|
32
|
+
if (input === 'read-only' || input === 'workspace-write' || input === 'full-access') return input
|
|
33
|
+
return undefined
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function normalizeEffort(input: unknown): string | undefined {
|
|
37
|
+
if (typeof input !== 'string') return undefined
|
|
38
|
+
const effort = input.trim()
|
|
39
|
+
if (!effort || effort === 'none' || effort === 'default') return undefined
|
|
40
|
+
return effort
|
|
41
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
2
|
+
import { dirname } from 'node:path'
|
|
3
|
+
|
|
4
|
+
export interface CredentialService {
|
|
5
|
+
set(ref: string, value: string): Promise<unknown>
|
|
6
|
+
resolve(ref: string): Promise<{ value?: string } | string | undefined>
|
|
7
|
+
unset(ref: string): Promise<unknown>
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export interface CredentialVault {
|
|
11
|
+
set(ref: string, value: string): Promise<void>
|
|
12
|
+
resolve(ref: string): Promise<string | undefined>
|
|
13
|
+
unset(ref: string): Promise<void>
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function createFileVault(file: string): CredentialVault {
|
|
17
|
+
const read = (): Record<string, string> => {
|
|
18
|
+
try {
|
|
19
|
+
const parsed = JSON.parse(readFileSync(file, 'utf8')) as Record<string, string>
|
|
20
|
+
return parsed && typeof parsed === 'object' ? parsed : {}
|
|
21
|
+
} catch {
|
|
22
|
+
return {}
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
const write = (data: Record<string, string>) => {
|
|
26
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
27
|
+
writeFileSync(file, `${JSON.stringify(data, null, 2)}\n`, 'utf8')
|
|
28
|
+
}
|
|
29
|
+
return {
|
|
30
|
+
async set(ref, value) {
|
|
31
|
+
const data = read()
|
|
32
|
+
data[ref] = value
|
|
33
|
+
write(data)
|
|
34
|
+
},
|
|
35
|
+
async resolve(ref) { return read()[ref] },
|
|
36
|
+
async unset(ref) {
|
|
37
|
+
const data = read()
|
|
38
|
+
delete data[ref]
|
|
39
|
+
write(data)
|
|
40
|
+
},
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function createServiceVault(credentials: CredentialService): CredentialVault {
|
|
45
|
+
return {
|
|
46
|
+
async set(ref, value) { await credentials.set(ref, value) },
|
|
47
|
+
async resolve(ref) {
|
|
48
|
+
const result = await credentials.resolve(ref)
|
|
49
|
+
if (typeof result === 'string') return result
|
|
50
|
+
return result?.value
|
|
51
|
+
},
|
|
52
|
+
async unset(ref) { await credentials.unset(ref) },
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const REF_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/
|
|
57
|
+
|
|
58
|
+
/** DSH credentials 只接受 POSIX 标识符,不能带斜杠或连字符。 */
|
|
59
|
+
export function credentialRef(channelId: string, key: string): string {
|
|
60
|
+
const raw = `im_connect_${channelId}_${key}`.replace(/[^A-Za-z0-9_]/g, '_')
|
|
61
|
+
if (!REF_PATTERN.test(raw)) throw new TypeError(`非法凭据名 ${raw}`)
|
|
62
|
+
return raw
|
|
63
|
+
}
|
|
64
|
+
|
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
2
|
+
import { ApprovalBroker } from './approval.js'
|
|
3
|
+
import { SessionMerger } from './merge.js'
|
|
4
|
+
import { SessionRouter } from './router.js'
|
|
5
|
+
import { SeenStore } from './seen-store.js'
|
|
6
|
+
import { SessionMapStore } from './session-store.js'
|
|
7
|
+
import { isImSessionId, type ChannelId, type ChatKind } from './session-id.js'
|
|
8
|
+
import { decideAccess } from './access.js'
|
|
9
|
+
import { splitText } from './split.js'
|
|
10
|
+
import type { ChannelAdapter, EngineConfig, ImMessage, ReplyStream } from './types.js'
|
|
11
|
+
|
|
12
|
+
const HELP = [
|
|
13
|
+
'IM 助理已连接本机 DeepSeek Harness。',
|
|
14
|
+
'',
|
|
15
|
+
'直接发文字即可继续当前频道会话。',
|
|
16
|
+
'结尾 .. 表示还有后续,!! 表示立即提交。',
|
|
17
|
+
'/new 开启全新会话(只影响当前 IM 聊天,不影响网页任务)',
|
|
18
|
+
'/status 查看当前频道会话',
|
|
19
|
+
'/help 显示本帮助',
|
|
20
|
+
].join('\n')
|
|
21
|
+
|
|
22
|
+
export class ImEngine {
|
|
23
|
+
private readonly channels = new Map<string, ChannelAdapter>()
|
|
24
|
+
private readonly router: SessionRouter
|
|
25
|
+
private readonly broker = new ApprovalBroker()
|
|
26
|
+
private readonly merger: SessionMerger
|
|
27
|
+
private readonly extraAllow = new Map<string, Set<string>>()
|
|
28
|
+
private readonly extraGroups = new Map<string, Set<string>>()
|
|
29
|
+
private readonly openChannels = new Set<string>()
|
|
30
|
+
private readonly queues = new Map<string, Promise<void>>()
|
|
31
|
+
private readonly streams = new Map<string, ReplyStream>()
|
|
32
|
+
private readonly disposeEvents: Array<() => void> = []
|
|
33
|
+
|
|
34
|
+
constructor(
|
|
35
|
+
private readonly ctx: Context,
|
|
36
|
+
private readonly store: SessionMapStore,
|
|
37
|
+
private readonly seen: SeenStore,
|
|
38
|
+
private readonly config: EngineConfig,
|
|
39
|
+
private readonly log: (line: string) => void,
|
|
40
|
+
private readonly onUnauthorized?: (channelId: string, msg: ImMessage) => string,
|
|
41
|
+
) {
|
|
42
|
+
this.router = new SessionRouter(ctx, store, config, log)
|
|
43
|
+
this.merger = new SessionMerger((config.mergeTimeoutSecs || 5) * 1000, (key, text) => {
|
|
44
|
+
const sep = key.indexOf(':')
|
|
45
|
+
const channelId = key.slice(0, sep)
|
|
46
|
+
const rest = key.slice(sep + 1)
|
|
47
|
+
const channel = this.channels.get(channelId)
|
|
48
|
+
if (!channel) return
|
|
49
|
+
void this.inject(channel, { chatId: rest.split(':').slice(1).join(':') || rest, text, kind: rest.startsWith('group:') ? 'group' : 'dm' })
|
|
50
|
+
})
|
|
51
|
+
const on = (this.ctx as unknown as { on: (name: string, fn: (...args: unknown[]) => unknown, opts?: unknown) => () => void }).on
|
|
52
|
+
if (typeof on === 'function') {
|
|
53
|
+
this.disposeEvents.push(on('session/event', (...args: unknown[]) => {
|
|
54
|
+
void this.onSessionEvent(args[0] as { id?: string }, args[1] as { type?: string; data?: { message?: { content?: Array<{ type?: string; text?: string }> }; chunk?: { type?: string; text?: string } } })
|
|
55
|
+
}, { global: true }))
|
|
56
|
+
this.disposeEvents.push(on('approval/request', (...args: unknown[]) => {
|
|
57
|
+
const req = args[0] as { session?: { id?: string } }
|
|
58
|
+
const next = args[1] as () => Promise<unknown>
|
|
59
|
+
return this.onApproval(req, next)
|
|
60
|
+
}, { global: true }))
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
renameSession(sessionId: string, title: string): boolean {
|
|
65
|
+
return this.router.rename(sessionId, title)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async removeSession(sessionId: string): Promise<boolean> {
|
|
69
|
+
return this.router.remove(sessionId)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async ensureSession(sessionId: string): Promise<boolean> {
|
|
73
|
+
return this.router.ensure(sessionId)
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
setModel(provider: string, model: string, reasoningEffort?: string): void {
|
|
77
|
+
this.config.provider = provider
|
|
78
|
+
this.config.model = model
|
|
79
|
+
this.config.reasoningEffort = reasoningEffort
|
|
80
|
+
void this.router.disposeAll()
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
setCwd(cwd: string): void {
|
|
84
|
+
this.config.cwd = cwd
|
|
85
|
+
void this.router.disposeAll()
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
setPermission(permission: 'read-only' | 'workspace-write' | 'full-access'): void {
|
|
89
|
+
this.config.permissionPreset = permission
|
|
90
|
+
void this.router.disposeAll()
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
attachMappedSessions(): Promise<void> {
|
|
94
|
+
return this.router.attachMappedSessions()
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
register(channel: ChannelAdapter): void {
|
|
98
|
+
this.channels.set(channel.id, channel)
|
|
99
|
+
channel.setMessageHandler((msg) => this.enqueue(channel.id, msg))
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
unregister(channelId: string): void {
|
|
103
|
+
this.channels.delete(channelId)
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
addAllowed(channelId: string, userId: string): void {
|
|
107
|
+
let set = this.extraAllow.get(channelId)
|
|
108
|
+
if (!set) {
|
|
109
|
+
set = new Set()
|
|
110
|
+
this.extraAllow.set(channelId, set)
|
|
111
|
+
}
|
|
112
|
+
set.add(userId)
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
dispose(): void {
|
|
116
|
+
for (const off of this.disposeEvents) off()
|
|
117
|
+
this.broker.dispose()
|
|
118
|
+
this.merger.dispose()
|
|
119
|
+
void this.router.disposeAll()
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
private enqueue(channelId: string, msg: ImMessage): void {
|
|
123
|
+
const key = `${channelId}:${msg.chatId}`
|
|
124
|
+
const prev = this.queues.get(key) ?? Promise.resolve()
|
|
125
|
+
const current = prev.catch(() => undefined).then(() => this.handleInbound(channelId, msg))
|
|
126
|
+
this.queues.set(key, current)
|
|
127
|
+
void current.finally(() => {
|
|
128
|
+
if (this.queues.get(key) === current) this.queues.delete(key)
|
|
129
|
+
})
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
private async handleInbound(channelId: string, msg: ImMessage): Promise<void> {
|
|
133
|
+
const channel = this.channels.get(channelId)
|
|
134
|
+
if (!channel) return
|
|
135
|
+
try {
|
|
136
|
+
if (msg.messageId && this.seen.has(`${channelId}:${msg.messageId}`)) return
|
|
137
|
+
if (msg.messageId) this.seen.add(`${channelId}:${msg.messageId}`)
|
|
138
|
+
if (msg.kind === 'group' && msg.addressed === false) return
|
|
139
|
+
const text = msg.text.trim()
|
|
140
|
+
if (text.startsWith('/')) {
|
|
141
|
+
const reply = await this.handleCommand(channel, msg)
|
|
142
|
+
if (reply) await this.deliver(channel, msg.chatId, reply)
|
|
143
|
+
return
|
|
144
|
+
}
|
|
145
|
+
if (['批准', '同意', 'yes', 'y', 'allow'].includes(text.toLowerCase())) {
|
|
146
|
+
if (await this.answerApproval(channelId, msg, true)) return
|
|
147
|
+
}
|
|
148
|
+
if (['拒绝', 'no', 'n', 'reject', 'deny'].includes(text.toLowerCase())) {
|
|
149
|
+
if (await this.answerApproval(channelId, msg, false)) return
|
|
150
|
+
}
|
|
151
|
+
const local = channel.authorizes?.(msg.userId ?? '')
|
|
152
|
+
const decision = decideAccess({
|
|
153
|
+
allowAll: this.config.allowAllUsers,
|
|
154
|
+
channelOpen: this.openChannels.has(channelId),
|
|
155
|
+
userAllowed: local === true || (local !== false && this.userAllowed(channelId, msg.userId)),
|
|
156
|
+
groupAllowed: msg.kind === 'group' && this.groupAllowed(channelId, msg.chatId),
|
|
157
|
+
kind: msg.kind === 'group' ? 'group' : 'dm',
|
|
158
|
+
addressed: msg.addressed,
|
|
159
|
+
})
|
|
160
|
+
if (decision === 'ignore') return
|
|
161
|
+
if (decision === 'deny-group-silent') {
|
|
162
|
+
this.onUnauthorized?.(channelId, msg)
|
|
163
|
+
return
|
|
164
|
+
}
|
|
165
|
+
if (decision === 'deny-dm' || local === false) {
|
|
166
|
+
const hint = this.onUnauthorized?.(channelId, msg) ?? '未授权:请管理员在设置 → IM助理 中批准你的访问。'
|
|
167
|
+
await channel.send(msg.chatId, hint).catch(() => undefined)
|
|
168
|
+
return
|
|
169
|
+
}
|
|
170
|
+
if (msg.media && msg.media.length > 0) {
|
|
171
|
+
await this.inject(channel, msg)
|
|
172
|
+
return
|
|
173
|
+
}
|
|
174
|
+
if (!text) return
|
|
175
|
+
if (channel.skipMerge) {
|
|
176
|
+
await this.inject(channel, { ...msg, text })
|
|
177
|
+
return
|
|
178
|
+
}
|
|
179
|
+
const mergeKey = `${channelId}:${msg.kind === 'group' ? 'group' : 'dm'}:${msg.chatId}`
|
|
180
|
+
const merged = this.merger.ingest(mergeKey, text)
|
|
181
|
+
if (merged.kind === 'flushed' && merged.text) {
|
|
182
|
+
await this.inject(channel, { ...msg, text: merged.text })
|
|
183
|
+
}
|
|
184
|
+
} catch (error) {
|
|
185
|
+
this.log(`[${channelId}] 处理失败: ${error instanceof Error ? error.message : String(error)}`)
|
|
186
|
+
await channel.send(msg.chatId, `消息处理失败:${error instanceof Error ? error.message : String(error)}`).catch(() => undefined)
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
private async handleCommand(channel: ChannelAdapter, msg: ImMessage): Promise<string | undefined> {
|
|
191
|
+
const [raw] = msg.text.trim().split(/\s+/)
|
|
192
|
+
const cmd = raw?.toLowerCase()
|
|
193
|
+
const kind: ChatKind = msg.kind === 'group' ? 'group' : 'dm'
|
|
194
|
+
if (cmd === '/help') return HELP
|
|
195
|
+
if (cmd === '/status') {
|
|
196
|
+
const entry = this.router.get(channel.id as ChannelId, kind, msg.chatId)
|
|
197
|
+
return [
|
|
198
|
+
`渠道:${channel.label}(${channel.status()})`,
|
|
199
|
+
entry ? `频道会话:${entry.sessionId}` : '频道会话:(尚未创建)',
|
|
200
|
+
'此会话独立于网页「任务」列表。',
|
|
201
|
+
].join('\n')
|
|
202
|
+
}
|
|
203
|
+
if (cmd === '/new' || cmd === '/clear') {
|
|
204
|
+
const entry = await this.router.rotate(channel.id as ChannelId, kind, msg.chatId, msg.username ?? msg.chatId)
|
|
205
|
+
return `已开启新的频道会话:${entry.sessionId}`
|
|
206
|
+
}
|
|
207
|
+
return `未知命令 ${cmd}。发送 /help 查看帮助。`
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
private async inject(channel: ChannelAdapter, msg: ImMessage): Promise<void> {
|
|
211
|
+
const kind: ChatKind = msg.kind === 'group' ? 'group' : 'dm'
|
|
212
|
+
const title = (msg.username || msg.text || msg.chatId).slice(0, 40)
|
|
213
|
+
const binding = await this.router.getOrCreate(channel.id as ChannelId, kind, msg.chatId, title)
|
|
214
|
+
const content: Array<Record<string, unknown>> = []
|
|
215
|
+
if (msg.text.trim()) content.push({ type: 'text', text: msg.text.trim() })
|
|
216
|
+
for (const media of msg.media ?? []) {
|
|
217
|
+
if (media.kind === 'voice-text' && media.text) content.push({ type: 'text', text: `[语音] ${media.text}` })
|
|
218
|
+
else if (media.path) content.push({ type: 'text', text: `[附件 ${media.name ?? media.kind}] ${media.path}` })
|
|
219
|
+
}
|
|
220
|
+
if (content.length === 0) return
|
|
221
|
+
await channel.sendAction?.(msg.chatId, 'typing').catch(() => undefined)
|
|
222
|
+
this.router.followup(binding, {
|
|
223
|
+
id: crypto.randomUUID(),
|
|
224
|
+
role: 'user',
|
|
225
|
+
content,
|
|
226
|
+
source: { kind: 'user' },
|
|
227
|
+
})
|
|
228
|
+
this.log(`[${channel.id}] 已注入 ${binding.sessionId}`)
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
setAccessMode(channelId: string, mode: 'pair' | 'open'): void {
|
|
232
|
+
if (mode === 'open') this.openChannels.add(channelId)
|
|
233
|
+
else this.openChannels.delete(channelId)
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
private userAllowed(channelId: string, userId?: string): boolean {
|
|
237
|
+
if (!userId) return false
|
|
238
|
+
return this.extraAllow.get(channelId)?.has(userId) === true
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
private groupAllowed(channelId: string, chatId: string): boolean {
|
|
242
|
+
return this.extraGroups.get(channelId)?.has(chatId) === true
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
private async answerApproval(channelId: string, msg: ImMessage, allow: boolean): Promise<boolean> {
|
|
246
|
+
const binding = this.router.get(channelId as ChannelId, msg.kind === 'group' ? 'group' : 'dm', msg.chatId)
|
|
247
|
+
if (!binding) return false
|
|
248
|
+
const ok = this.broker.answer(binding.sessionId, allow)
|
|
249
|
+
if (ok) await this.channels.get(channelId)?.send(msg.chatId, allow ? '已批准。' : '已拒绝。')
|
|
250
|
+
return ok
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
private async onApproval(req: { session?: { id?: string } }, next: () => Promise<unknown>): Promise<unknown> {
|
|
254
|
+
const sessionId = req.session?.id ? String(req.session.id) : ''
|
|
255
|
+
if (!sessionId || !isImSessionId(sessionId)) return next()
|
|
256
|
+
const binding = this.router.bindingForSession(sessionId)
|
|
257
|
+
const channel = binding ? this.channels.get(binding.channelId) : undefined
|
|
258
|
+
if (!binding || !channel) return next()
|
|
259
|
+
await channel.send(binding.chatId, '需要批准才能继续。回复「批准」或「拒绝」。').catch(() => undefined)
|
|
260
|
+
const verdict = await this.broker.wait(sessionId, 120_000)
|
|
261
|
+
if (verdict === 'allow') return { behavior: 'allow' }
|
|
262
|
+
if (verdict === 'reject') return { behavior: 'reject' }
|
|
263
|
+
return next()
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
private async onSessionEvent(
|
|
267
|
+
session: { id?: string },
|
|
268
|
+
event: { type?: string; data?: { message?: { content?: Array<{ type?: string; text?: string }> }; chunk?: { type?: string; text?: string } } },
|
|
269
|
+
): Promise<void> {
|
|
270
|
+
const sessionId = session.id ? String(session.id) : ''
|
|
271
|
+
if (!isImSessionId(sessionId)) return
|
|
272
|
+
const binding = this.router.bindingForSession(sessionId)
|
|
273
|
+
const channel = binding ? this.channels.get(binding.channelId) : undefined
|
|
274
|
+
if (!binding || !channel) return
|
|
275
|
+
const streamKey = `${binding.channelId}:${binding.chatId}`
|
|
276
|
+
if (event.type === 'assistant/chunk' && event.data?.chunk?.text && channel.beginReply) {
|
|
277
|
+
let stream = this.streams.get(streamKey)
|
|
278
|
+
if (!stream) {
|
|
279
|
+
stream = await channel.beginReply(binding.chatId).catch(() => undefined)
|
|
280
|
+
if (stream) this.streams.set(streamKey, stream)
|
|
281
|
+
}
|
|
282
|
+
if (stream) await stream.update(event.data.chunk.text).catch(() => undefined)
|
|
283
|
+
return
|
|
284
|
+
}
|
|
285
|
+
if (event.type === 'turn/end') {
|
|
286
|
+
const reason = (event.data as { reason?: { kind?: string; error?: { message?: string } } } | undefined)?.reason
|
|
287
|
+
this.log(`[${channel.id}] 回合结束 ${sessionId}: ${reason?.kind ?? 'ok'}`)
|
|
288
|
+
if (reason?.kind === 'error') {
|
|
289
|
+
const detail = reason.error?.message || '模型调用失败'
|
|
290
|
+
this.log(`[${channel.id}] 回合失败 ${sessionId}: ${detail}`)
|
|
291
|
+
await this.deliver(channel, binding.chatId, `助手没有生成回复:${detail}`)
|
|
292
|
+
}
|
|
293
|
+
return
|
|
294
|
+
}
|
|
295
|
+
if (event.type === 'assistant/message') {
|
|
296
|
+
const text = (event.data?.message?.content ?? [])
|
|
297
|
+
.filter((block) => block.type === 'text' && block.text)
|
|
298
|
+
.map((block) => block.text ?? '')
|
|
299
|
+
.join('\n')
|
|
300
|
+
.trim()
|
|
301
|
+
const stream = this.streams.get(streamKey)
|
|
302
|
+
this.streams.delete(streamKey)
|
|
303
|
+
if (stream && text) {
|
|
304
|
+
await stream.finish(text).catch(() => this.deliver(channel, binding.chatId, text))
|
|
305
|
+
return
|
|
306
|
+
}
|
|
307
|
+
if (text) {
|
|
308
|
+
this.log(`[${channel.id}] 准备回复 ${sessionId},长度 ${text.length}`)
|
|
309
|
+
await this.deliver(channel, binding.chatId, text)
|
|
310
|
+
} else {
|
|
311
|
+
this.log(`[${channel.id}] 助手消息为空 ${sessionId}`)
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
private async deliver(channel: ChannelAdapter, chatId: string, text: string): Promise<void> {
|
|
317
|
+
for (const chunk of splitText(text, channel.maxMessageLength)) {
|
|
318
|
+
try {
|
|
319
|
+
await channel.send(chatId, chunk)
|
|
320
|
+
this.log(`[${channel.id}] 已投递 ${chatId},长度 ${chunk.length}`)
|
|
321
|
+
} catch (error) {
|
|
322
|
+
this.log(`[${channel.id}] 回复失败: ${error instanceof Error ? error.message : String(error)}`)
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
2
|
+
import { dirname } from 'node:path'
|
|
3
|
+
|
|
4
|
+
export class JsonStateFile<T extends object> {
|
|
5
|
+
constructor(private readonly file: string, private readonly fallback: T) {}
|
|
6
|
+
|
|
7
|
+
read(): T {
|
|
8
|
+
try {
|
|
9
|
+
const parsed = JSON.parse(readFileSync(this.file, 'utf8')) as T
|
|
10
|
+
return parsed && typeof parsed === 'object' ? parsed : structuredClone(this.fallback)
|
|
11
|
+
} catch {
|
|
12
|
+
return structuredClone(this.fallback)
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
write(value: T): void {
|
|
17
|
+
mkdirSync(dirname(this.file), { recursive: true })
|
|
18
|
+
writeFileSync(this.file, `${JSON.stringify(value, null, 2)}\n`, 'utf8')
|
|
19
|
+
}
|
|
20
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/** 手机多段输入合并:`..` 续写,`!!` 立即提交,裸文本进入超时窗口。 */
|
|
2
|
+
export type MergeKind = 'buffered' | 'flushed' | 'ignored'
|
|
3
|
+
|
|
4
|
+
export interface MergeResult {
|
|
5
|
+
kind: MergeKind
|
|
6
|
+
text?: string
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function stripControlSuffix(text: string): { text: string; control: 'continue' | 'commit' | 'none' } {
|
|
10
|
+
if (text.endsWith('!!')) return { text: text.slice(0, -2), control: 'commit' }
|
|
11
|
+
if (text.endsWith('..')) return { text: text.slice(0, -2), control: 'continue' }
|
|
12
|
+
return { text, control: 'none' }
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export class SessionMerger {
|
|
16
|
+
private readonly buffers = new Map<string, { text: string; timer: NodeJS.Timeout }>()
|
|
17
|
+
|
|
18
|
+
constructor(
|
|
19
|
+
private readonly mergeTimeoutMs: number,
|
|
20
|
+
private readonly onFlush: (key: string, text: string) => void,
|
|
21
|
+
) {}
|
|
22
|
+
|
|
23
|
+
ingest(key: string, raw: string): MergeResult {
|
|
24
|
+
const { text, control } = stripControlSuffix(raw)
|
|
25
|
+
if (text.trim() === '' && control === 'none') return { kind: 'ignored' }
|
|
26
|
+
const existing = this.buffers.get(key)
|
|
27
|
+
if (control === 'continue') {
|
|
28
|
+
this.setBuffer(key, existing ? `${existing.text}${text}` : text)
|
|
29
|
+
return { kind: 'buffered' }
|
|
30
|
+
}
|
|
31
|
+
if (existing) {
|
|
32
|
+
this.clear(key)
|
|
33
|
+
return { kind: 'flushed', text: `${existing.text}${text}` }
|
|
34
|
+
}
|
|
35
|
+
if (control === 'commit') return { kind: 'flushed', text }
|
|
36
|
+
this.setBuffer(key, text)
|
|
37
|
+
return { kind: 'buffered' }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
dispose(): void {
|
|
41
|
+
for (const key of [...this.buffers.keys()]) this.clear(key)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
private setBuffer(key: string, text: string): void {
|
|
45
|
+
this.clear(key)
|
|
46
|
+
const timer = setTimeout(() => {
|
|
47
|
+
this.clear(key)
|
|
48
|
+
this.onFlush(key, text)
|
|
49
|
+
}, this.mergeTimeoutMs)
|
|
50
|
+
timer.unref?.()
|
|
51
|
+
this.buffers.set(key, { text, timer })
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
private clear(key: string): void {
|
|
55
|
+
const entry = this.buffers.get(key)
|
|
56
|
+
if (!entry) return
|
|
57
|
+
clearTimeout(entry.timer)
|
|
58
|
+
this.buffers.delete(key)
|
|
59
|
+
}
|
|
60
|
+
}
|