dsh-collab-pair 1.3.0 → 1.4.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/README.md +42 -0
- package/client.js +728 -0
- package/cordis.patch.yml +1 -0
- package/index.js +348 -34
- package/package.json +11 -2
package/cordis.patch.yml
CHANGED
package/index.js
CHANGED
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
*
|
|
17
17
|
* @module @local/collab-pair
|
|
18
18
|
*/
|
|
19
|
-
import { randomUUID } from 'node:crypto'
|
|
19
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
20
20
|
import { hostname } from 'node:os'
|
|
21
21
|
|
|
22
22
|
export const inject = ['tools', 'systemPrompt', 'agents', 'sessions', 'commands']
|
|
@@ -41,7 +41,7 @@ const DONE = 'done'
|
|
|
41
41
|
const STOPPED = 'stopped'
|
|
42
42
|
const REPORTS = new Set(['done', 'partial', 'blocked'])
|
|
43
43
|
const PROMPT_TIMEOUT_MS = 180000
|
|
44
|
-
const ENGINE = 'collab-pair/1.
|
|
44
|
+
const ENGINE = 'collab-pair/1.4.0'
|
|
45
45
|
|
|
46
46
|
/** A recoverable failure whose message is meant for the model. */
|
|
47
47
|
class CollabError extends Error {}
|
|
@@ -71,6 +71,9 @@ function resolveConfig(raw) {
|
|
|
71
71
|
hubRoom: typeof value.hubRoom === 'string' && /^[A-Za-z0-9_-]{1,64}$/.test(value.hubRoom) ? value.hubRoom : 'default',
|
|
72
72
|
hubToken: typeof value.hubToken === 'string' ? value.hubToken.trim() : '',
|
|
73
73
|
deviceName: deviceText(value.deviceName),
|
|
74
|
+
relayMode: value.relayMode === 'off' || value.relayMode === 'hub' || value.relayMode === 'ntfy'
|
|
75
|
+
? value.relayMode
|
|
76
|
+
: (normalizeHubUrl(value.hubUrl) !== '' && typeof value.hubToken === 'string' && value.hubToken.trim() !== '' ? 'hub' : 'off'),
|
|
74
77
|
}
|
|
75
78
|
}
|
|
76
79
|
|
|
@@ -274,6 +277,7 @@ const LANGUAGES = {
|
|
|
274
277
|
'规则:',
|
|
275
278
|
'- 用 `collab_dispatch` 派发任务;有多个员工时用 `worker` 指定员工(sessionId 或标题),只有一个时可省略。',
|
|
276
279
|
'- 需要新的员工对话时用 `collab_worker_create`(可命名、设预设/模型,并自动关联)。',
|
|
280
|
+
'- 阶段队列:用 `collab_stage` 添加/查看;当前阶段验收通过后调用 `collab_stage({action:"complete"})`,会自动派发下一阶段。',
|
|
277
281
|
'- 需要调整某个员工的 agent 预设或模型时,用 `collab_configure`(worker 指定员工)。',
|
|
278
282
|
'- 收到以【协作回报】开头的消息后,继续派发,或对该员工调用 `collab_done`;`collab_status` 查看全部进度。',
|
|
279
283
|
'- 除非用户明确要求,不要自己执行员工的交付任务;你负责拆解、验收和决定下一步。',
|
|
@@ -413,6 +417,7 @@ const LANGUAGES = {
|
|
|
413
417
|
'Rules:',
|
|
414
418
|
'- Dispatch a round with `collab_dispatch`; when several workers exist, select one with `worker` (session id or title). With a single worker you may omit it.',
|
|
415
419
|
'- To start a new worker conversation use `collab_worker_create` (name, preset/model, linked automatically).',
|
|
420
|
+
'- Stage queue: manage it with `collab_stage`; when the current stage passes acceptance, call `collab_stage({action:"complete"})` to dispatch the next stage automatically.',
|
|
416
421
|
'- To change a worker\'s agent preset or model, use `collab_configure` (select the worker with `worker`).',
|
|
417
422
|
'- When a message starting with [Collaboration report] arrives, dispatch the next round or call `collab_done` for that worker; `collab_status` shows every worker.',
|
|
418
423
|
'- Unless the user explicitly asks, do not do the workers\' delivery work yourself; you break down, review, and decide.',
|
|
@@ -526,6 +531,8 @@ export function apply(ctx, rawConfig) {
|
|
|
526
531
|
let remoteCursor = 0
|
|
527
532
|
let remoteLastError = null
|
|
528
533
|
let remoteLastPollAt = 0
|
|
534
|
+
let remoteNtfyCursor = ''
|
|
535
|
+
const ntfyParts = new Map()
|
|
529
536
|
let remoteDomain = null
|
|
530
537
|
const remoteReady = openRemoteStorage()
|
|
531
538
|
|
|
@@ -634,6 +641,7 @@ export function apply(ctx, rawConfig) {
|
|
|
634
641
|
pending: normalizePending(value.pending),
|
|
635
642
|
lastReport: value.lastReport !== null && typeof value.lastReport === 'object' ? value.lastReport : null,
|
|
636
643
|
history: Array.isArray(value.history) ? value.history.slice(-cfg.maxHistory) : [],
|
|
644
|
+
stages: normalizeStages(value.stages),
|
|
637
645
|
nudges: Number.isSafeInteger(value.nudges) && value.nudges >= 0 ? value.nudges : 0,
|
|
638
646
|
...(typeof value.lastNudgeAt === 'number' ? { lastNudgeAt: value.lastNudgeAt } : {}),
|
|
639
647
|
...(value.remote !== null && typeof value.remote === 'object'
|
|
@@ -648,9 +656,31 @@ export function apply(ctx, rawConfig) {
|
|
|
648
656
|
}
|
|
649
657
|
}
|
|
650
658
|
|
|
659
|
+
/** Fill missing fields on a stored stage queue. */
|
|
660
|
+
function normalizeStages(value) {
|
|
661
|
+
if (!Array.isArray(value)) return []
|
|
662
|
+
const stages = []
|
|
663
|
+
for (const item of value.slice(0, 100)) {
|
|
664
|
+
if (item === null || typeof item !== 'object') continue
|
|
665
|
+
const prompt = typeof item.prompt === 'string' ? item.prompt.trim() : ''
|
|
666
|
+
if (prompt === '') continue
|
|
667
|
+
const status = item.status === 'active' || item.status === 'done' ? item.status : 'pending'
|
|
668
|
+
stages.push({
|
|
669
|
+
id: typeof item.id === 'string' ? item.id : `st-${randomUUID().slice(0, 8)}`,
|
|
670
|
+
title: typeof item.title === 'string' ? item.title : '',
|
|
671
|
+
prompt,
|
|
672
|
+
acceptance: typeof item.acceptance === 'string' ? item.acceptance : '',
|
|
673
|
+
status,
|
|
674
|
+
...(typeof item.startedAt === 'number' ? { startedAt: item.startedAt } : {}),
|
|
675
|
+
...(typeof item.completedAt === 'number' ? { completedAt: item.completedAt } : {}),
|
|
676
|
+
...(typeof item.summary === 'string' ? { summary: item.summary } : {}),
|
|
677
|
+
})
|
|
678
|
+
}
|
|
679
|
+
return stages
|
|
680
|
+
}
|
|
681
|
+
|
|
651
682
|
/** Fill missing fields on a stored pending round. */
|
|
652
|
-
function normalizePending(value) {
|
|
653
|
-
if (value === null || typeof value !== 'object') return null
|
|
683
|
+
function normalizePending(value) { if (value === null || typeof value !== 'object') return null
|
|
654
684
|
if (!Number.isSafeInteger(value.round) || value.round < 1) return null
|
|
655
685
|
if (typeof value.task !== 'string' || typeof value.requestId !== 'string') return null
|
|
656
686
|
return {
|
|
@@ -701,6 +731,7 @@ export function apply(ctx, rawConfig) {
|
|
|
701
731
|
for (const [key, value] of domain.table('aliases').entries()) adoptAlias(key, value)
|
|
702
732
|
for (const [key, value] of domain.table('state').entries()) {
|
|
703
733
|
if (key === 'cursor' && Number.isSafeInteger(value?.cursor) && value.cursor >= 0) remoteCursor = value.cursor
|
|
734
|
+
if (key === 'ntfy_cursor' && typeof value?.id === 'string') remoteNtfyCursor = value.id
|
|
704
735
|
}
|
|
705
736
|
remoteDomain = domain
|
|
706
737
|
remoteState = 'ready'
|
|
@@ -752,13 +783,37 @@ export function apply(ctx, rawConfig) {
|
|
|
752
783
|
if (domain === undefined) return
|
|
753
784
|
try {
|
|
754
785
|
await domain.table('state').put('cursor', { cursor: remoteCursor, updatedAt: Date.now() })
|
|
786
|
+
if (remoteNtfyCursor !== '') await domain.table('state').put('ntfy_cursor', { id: remoteNtfyCursor, updatedAt: Date.now() })
|
|
755
787
|
} catch (error) {
|
|
756
788
|
ctx.logger.warn(`collab-pair: saving the relay cursor failed: ${String(error)}`)
|
|
757
789
|
}
|
|
758
790
|
}
|
|
759
791
|
|
|
760
792
|
function hubConfigured() {
|
|
761
|
-
return cfg.hubUrl !== '' && cfg.hubToken !== ''
|
|
793
|
+
return cfg.relayMode === 'hub' && cfg.hubUrl !== '' && cfg.hubToken !== ''
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
function ntfyConfigured() {
|
|
797
|
+
return cfg.relayMode === 'ntfy' && cfg.hubToken !== '' && cfg.hubRoom !== ''
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
function relayConfigured() {
|
|
801
|
+
return hubConfigured() || ntfyConfigured()
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
/** Client-safe view of the relay configuration and its last poll. */
|
|
805
|
+
function relayStatus() {
|
|
806
|
+
return {
|
|
807
|
+
mode: cfg.relayMode,
|
|
808
|
+
device: cfg.deviceName,
|
|
809
|
+
room: cfg.hubRoom,
|
|
810
|
+
hubUrl: cfg.hubUrl,
|
|
811
|
+
hasToken: cfg.hubToken !== '',
|
|
812
|
+
connected: remoteLastPollAt > 0,
|
|
813
|
+
lastPollAt: remoteLastPollAt === 0 ? null : isoTime(remoteLastPollAt),
|
|
814
|
+
lastError: remoteLastError,
|
|
815
|
+
cursor: cfg.relayMode === 'ntfy' ? (remoteNtfyCursor || null) : remoteCursor,
|
|
816
|
+
}
|
|
762
817
|
}
|
|
763
818
|
|
|
764
819
|
/** One authenticated JSON request to the relay. */
|
|
@@ -785,40 +840,130 @@ export function apply(ctx, rawConfig) {
|
|
|
785
840
|
|
|
786
841
|
/** Queue one message for another device. */
|
|
787
842
|
async function sendRemote(to, type, payload) {
|
|
788
|
-
if (!
|
|
843
|
+
if (!relayConfigured()) {
|
|
844
|
+
throw new CollabError('跨设备中继未启用:请在设置页的「跨设备协作」里选择中继并保存。')
|
|
845
|
+
}
|
|
846
|
+
if (cfg.relayMode === 'ntfy') return ntfySend(to, type, payload)
|
|
789
847
|
return hubFetch('/v1/send', {
|
|
790
848
|
method: 'POST',
|
|
791
849
|
body: JSON.stringify({ room: cfg.hubRoom, from: cfg.deviceName, to, type, payload }),
|
|
792
850
|
})
|
|
793
851
|
}
|
|
794
852
|
|
|
795
|
-
/**
|
|
853
|
+
/** One long-poll round against the self-hosted hub. */
|
|
854
|
+
async function hubPollOnce() {
|
|
855
|
+
if (remoteCursor === 0) {
|
|
856
|
+
const head = await hubFetch(`/v1/head?room=${encodeURIComponent(cfg.hubRoom)}`)
|
|
857
|
+
remoteCursor = Number.isSafeInteger(head.cursor) ? head.cursor : 0
|
|
858
|
+
await saveRemoteCursor()
|
|
859
|
+
}
|
|
860
|
+
const query = `?room=${encodeURIComponent(cfg.hubRoom)}&device=${encodeURIComponent(cfg.deviceName)}&since=${remoteCursor}`
|
|
861
|
+
const result = await hubFetch(`/v1/poll${query}`)
|
|
862
|
+
remoteLastPollAt = Date.now()
|
|
863
|
+
remoteLastError = null
|
|
864
|
+
let advanced = false
|
|
865
|
+
for (const message of Array.isArray(result.messages) ? result.messages : []) {
|
|
866
|
+
if (!Number.isSafeInteger(message?.id) || message.id <= remoteCursor) continue
|
|
867
|
+
remoteCursor = message.id
|
|
868
|
+
advanced = true
|
|
869
|
+
try {
|
|
870
|
+
await handleRemoteMessage(message)
|
|
871
|
+
} catch (error) {
|
|
872
|
+
ctx.logger.warn(`collab-pair: handling relay message ${message.id} failed: ${String(error)}`)
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
if (advanced) await saveRemoteCursor()
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
/** Topic derived from room + token, so the free relay needs no account. */
|
|
879
|
+
function ntfyTopic() {
|
|
880
|
+
const digest = createHash('sha256').update(`${cfg.hubRoom}:${cfg.hubToken}`).digest('hex')
|
|
881
|
+
return `collab-${digest.slice(0, 32)}`
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
/** Publish one envelope through ntfy.sh, chunked under its 4 KB limit. */
|
|
885
|
+
async function ntfySend(to, type, payload) {
|
|
886
|
+
const envelope = { room: cfg.hubRoom, from: cfg.deviceName, to, type, payload, at: Date.now() }
|
|
887
|
+
const encoded = Buffer.from(JSON.stringify(envelope), 'utf8').toString('base64')
|
|
888
|
+
const id = randomUUID()
|
|
889
|
+
const size = 2400
|
|
890
|
+
const total = Math.max(1, Math.ceil(encoded.length / size))
|
|
891
|
+
for (let part = 1; part <= total; part += 1) {
|
|
892
|
+
const chunk = JSON.stringify({ v: 1, id, part, of: total, data: encoded.slice((part - 1) * size, part * size) })
|
|
893
|
+
const body = JSON.stringify({ topic: ntfyTopic(), message: chunk, priority: 3 })
|
|
894
|
+
const response = await fetch('https://ntfy.sh', {
|
|
895
|
+
method: 'POST',
|
|
896
|
+
headers: { 'content-type': 'application/json' },
|
|
897
|
+
body,
|
|
898
|
+
signal: AbortSignal.timeout(20000),
|
|
899
|
+
})
|
|
900
|
+
if (!response.ok) throw new Error(`ntfy 发布失败:HTTP ${response.status}`)
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
/** Reassemble a chunked ntfy message and route it. */
|
|
905
|
+
function ntfyIngest(message) {
|
|
906
|
+
let chunk
|
|
907
|
+
try {
|
|
908
|
+
chunk = JSON.parse(message)
|
|
909
|
+
} catch {
|
|
910
|
+
return
|
|
911
|
+
}
|
|
912
|
+
if (chunk === null || typeof chunk !== 'object' || chunk.v !== 1 || typeof chunk.id !== 'string' || !Number.isSafeInteger(chunk.part) || !Number.isSafeInteger(chunk.of)) return
|
|
913
|
+
const entry = ntfyParts.get(chunk.id) ?? { of: chunk.of, parts: new Map() }
|
|
914
|
+
entry.parts.set(chunk.part, typeof chunk.data === 'string' ? chunk.data : '')
|
|
915
|
+
ntfyParts.set(chunk.id, entry)
|
|
916
|
+
if (entry.parts.size < entry.of) return
|
|
917
|
+
ntfyParts.delete(chunk.id)
|
|
918
|
+
const joined = []
|
|
919
|
+
for (let part = 1; part <= entry.of; part += 1) joined.push(entry.parts.get(part) ?? '')
|
|
920
|
+
let envelope
|
|
921
|
+
try {
|
|
922
|
+
envelope = JSON.parse(Buffer.from(joined.join(''), 'base64').toString('utf8'))
|
|
923
|
+
} catch {
|
|
924
|
+
return
|
|
925
|
+
}
|
|
926
|
+
if (envelope === null || typeof envelope !== 'object') return
|
|
927
|
+
if (envelope.to !== cfg.deviceName && envelope.to !== '*') return
|
|
928
|
+
if (envelope.from === cfg.deviceName) return
|
|
929
|
+
void handleRemoteMessage(envelope).catch((error) => ctx.logger.warn(`collab-pair: handling an ntfy message failed: ${String(error)}`))
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
/** Poll the free ntfy relay once. */
|
|
933
|
+
async function ntfyPollOnce() {
|
|
934
|
+
const since = remoteNtfyCursor === '' ? '10m' : remoteNtfyCursor
|
|
935
|
+
const url = `https://ntfy.sh/${encodeURIComponent(ntfyTopic())}/json?poll=1&since=${encodeURIComponent(since)}`
|
|
936
|
+
const response = await fetch(url, { signal: AbortSignal.timeout(25000) })
|
|
937
|
+
if (!response.ok) throw new Error(`ntfy 轮询失败:HTTP ${response.status}`)
|
|
938
|
+
const text = await response.text()
|
|
939
|
+
remoteLastPollAt = Date.now()
|
|
940
|
+
remoteLastError = null
|
|
941
|
+
let advanced = false
|
|
942
|
+
for (const line of text.split('\n')) {
|
|
943
|
+
if (line.trim() === '') continue
|
|
944
|
+
let event
|
|
945
|
+
try {
|
|
946
|
+
event = JSON.parse(line)
|
|
947
|
+
} catch {
|
|
948
|
+
continue
|
|
949
|
+
}
|
|
950
|
+
if (event?.event !== 'message' || typeof event.message !== 'string') continue
|
|
951
|
+
if (typeof event.id === 'string') remoteNtfyCursor = event.id
|
|
952
|
+
advanced = true
|
|
953
|
+
ntfyIngest(event.message)
|
|
954
|
+
}
|
|
955
|
+
if (advanced) await saveRemoteCursor()
|
|
956
|
+
if (!advanced) await new Promise((resolve) => setTimeout(resolve, 2500))
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
/** Poll the configured relay and dispatch incoming envelopes. */
|
|
796
960
|
async function remoteLoop() {
|
|
797
|
-
if (!
|
|
798
|
-
ctx.logger.info(`collab-pair: relay
|
|
799
|
-
while (alive &&
|
|
961
|
+
if (!relayConfigured()) return
|
|
962
|
+
ctx.logger.info(`collab-pair: ${cfg.relayMode} relay for ${cfg.deviceName} on room ${cfg.hubRoom}`)
|
|
963
|
+
while (alive && relayConfigured()) {
|
|
800
964
|
try {
|
|
801
|
-
if (
|
|
802
|
-
|
|
803
|
-
remoteCursor = Number.isSafeInteger(head.cursor) ? head.cursor : 0
|
|
804
|
-
await saveRemoteCursor()
|
|
805
|
-
}
|
|
806
|
-
const query = `?room=${encodeURIComponent(cfg.hubRoom)}&device=${encodeURIComponent(cfg.deviceName)}&since=${remoteCursor}`
|
|
807
|
-
const result = await hubFetch(`/v1/poll${query}`)
|
|
808
|
-
remoteLastPollAt = Date.now()
|
|
809
|
-
remoteLastError = null
|
|
810
|
-
let advanced = false
|
|
811
|
-
for (const message of Array.isArray(result.messages) ? result.messages : []) {
|
|
812
|
-
if (!Number.isSafeInteger(message?.id) || message.id <= remoteCursor) continue
|
|
813
|
-
remoteCursor = message.id
|
|
814
|
-
advanced = true
|
|
815
|
-
try {
|
|
816
|
-
await handleRemoteMessage(message)
|
|
817
|
-
} catch (error) {
|
|
818
|
-
ctx.logger.warn(`collab-pair: handling relay message ${message.id} failed: ${String(error)}`)
|
|
819
|
-
}
|
|
820
|
-
}
|
|
821
|
-
if (advanced) await saveRemoteCursor()
|
|
965
|
+
if (cfg.relayMode === 'ntfy') await ntfyPollOnce()
|
|
966
|
+
else await hubPollOnce()
|
|
822
967
|
} catch (error) {
|
|
823
968
|
remoteLastError = String(error instanceof Error ? error.message : error)
|
|
824
969
|
ctx.logger.warn(`collab-pair: relay poll failed: ${remoteLastError}`)
|
|
@@ -1422,6 +1567,7 @@ export function apply(ctx, rawConfig) {
|
|
|
1422
1567
|
mode: link.mode,
|
|
1423
1568
|
project: link.project || '',
|
|
1424
1569
|
remote: link.remote ?? null,
|
|
1570
|
+
stages: link.stages ?? [],
|
|
1425
1571
|
workerLive: workerAgent !== undefined,
|
|
1426
1572
|
workerRunning: workerAgent !== undefined && workerAgent.status === 'running',
|
|
1427
1573
|
managerRunning: managerAgent !== undefined && managerAgent.status === 'running',
|
|
@@ -2043,7 +2189,7 @@ export function apply(ctx, rawConfig) {
|
|
|
2043
2189
|
},
|
|
2044
2190
|
async execute(args, exec) {
|
|
2045
2191
|
const agent = requireAgent(exec)
|
|
2046
|
-
if (!
|
|
2192
|
+
if (!relayConfigured()) throw new CollabError('跨设备中继未启用:请在设置页的「跨设备协作」里选择中继并保存。')
|
|
2047
2193
|
await remoteReady.catch(() => undefined)
|
|
2048
2194
|
const action = typeof args?.action === 'string' ? args.action : ''
|
|
2049
2195
|
if (action === 'alias') {
|
|
@@ -2255,6 +2401,7 @@ export function apply(ctx, rawConfig) {
|
|
|
2255
2401
|
mode: link.mode,
|
|
2256
2402
|
project: link.project || null,
|
|
2257
2403
|
remote: link.remote ?? null,
|
|
2404
|
+
stages: link.stages ?? [],
|
|
2258
2405
|
round: link.round,
|
|
2259
2406
|
pending: link.pending === null
|
|
2260
2407
|
? null
|
|
@@ -2426,6 +2573,129 @@ export function apply(ctx, rawConfig) {
|
|
|
2426
2573
|
when: ({ agent }) => managerLinks(agent.id).length > 0,
|
|
2427
2574
|
})
|
|
2428
2575
|
|
|
2576
|
+
toolExecutors.stage = register({
|
|
2577
|
+
name: 'collab_stage',
|
|
2578
|
+
description:
|
|
2579
|
+
'(项目经理)阶段队列:人可以先写好多个大阶段的提示词。action=add 添加阶段,list 查看,start 开始第一个待开始阶段,complete 完成当前阶段并自动派发下一阶段,remove 删除待开始阶段。',
|
|
2580
|
+
parameters: {
|
|
2581
|
+
type: 'object',
|
|
2582
|
+
properties: {
|
|
2583
|
+
action: { type: 'string', enum: ['add', 'list', 'start', 'complete', 'remove', 'clear'], description: '要执行的操作。' },
|
|
2584
|
+
worker: { type: 'string', description: '可选:目标员工(sessionId、标题或别名)。只有一个员工时可省略。' },
|
|
2585
|
+
prompt: { type: 'string', description: 'add:该阶段要派发的提示词/任务。' },
|
|
2586
|
+
acceptance: { type: 'string', description: 'add:该阶段的验收标准。' },
|
|
2587
|
+
title: { type: 'string', description: 'add:阶段标题,便于人查看。' },
|
|
2588
|
+
summary: { type: 'string', description: 'complete:本阶段总结(可选)。' },
|
|
2589
|
+
index: { type: 'number', description: 'remove:要删除的待开始阶段序号(从 1 开始)。' },
|
|
2590
|
+
},
|
|
2591
|
+
required: ['action'],
|
|
2592
|
+
},
|
|
2593
|
+
async execute(args, exec) {
|
|
2594
|
+
const agent = requireAgent(exec)
|
|
2595
|
+
const link = resolveManagedLink(agent.id, args?.worker)
|
|
2596
|
+
const action = typeof args?.action === 'string' ? args.action : ''
|
|
2597
|
+
if (!Array.isArray(link.stages)) link.stages = []
|
|
2598
|
+
const view = () => link.stages.map((stage, index) => ({
|
|
2599
|
+
index: index + 1,
|
|
2600
|
+
id: stage.id,
|
|
2601
|
+
title: stage.title || '',
|
|
2602
|
+
status: stage.status,
|
|
2603
|
+
acceptance: stage.acceptance || '',
|
|
2604
|
+
prompt: clip(stage.prompt, 400),
|
|
2605
|
+
}))
|
|
2606
|
+
if (action === 'add') {
|
|
2607
|
+
const prompt = typeof args?.prompt === 'string' ? args.prompt.trim() : ''
|
|
2608
|
+
if (prompt === '') throw new CollabError('prompt 不能为空。')
|
|
2609
|
+
const stage = {
|
|
2610
|
+
id: `st-${randomUUID().slice(0, 8)}`,
|
|
2611
|
+
title: typeof args?.title === 'string' ? args.title.trim() : '',
|
|
2612
|
+
prompt,
|
|
2613
|
+
acceptance: typeof args?.acceptance === 'string' ? args.acceptance.trim() : '',
|
|
2614
|
+
status: 'pending',
|
|
2615
|
+
}
|
|
2616
|
+
link.stages.push(stage)
|
|
2617
|
+
link.updatedAt = Date.now()
|
|
2618
|
+
await persist(link)
|
|
2619
|
+
return { ok: true, action: 'add', stage: view().find((row) => row.id === stage.id), stages: view() }
|
|
2620
|
+
}
|
|
2621
|
+
if (action === 'list') {
|
|
2622
|
+
return {
|
|
2623
|
+
ok: true,
|
|
2624
|
+
action: 'list',
|
|
2625
|
+
worker: link.worker,
|
|
2626
|
+
stages: view(),
|
|
2627
|
+
active: view().find((row) => row.status === 'active') ?? null,
|
|
2628
|
+
}
|
|
2629
|
+
}
|
|
2630
|
+
if (action === 'remove') {
|
|
2631
|
+
const index = clampInt(args?.index, 1, 100, 0)
|
|
2632
|
+
const stage = index > 0 ? link.stages[index - 1] : undefined
|
|
2633
|
+
if (stage === undefined) throw new CollabError('index 超出范围。')
|
|
2634
|
+
if (stage.status !== 'pending') throw new CollabError('只能删除尚未开始的阶段。')
|
|
2635
|
+
link.stages.splice(index - 1, 1)
|
|
2636
|
+
link.updatedAt = Date.now()
|
|
2637
|
+
await persist(link)
|
|
2638
|
+
return { ok: true, action: 'remove', stages: view() }
|
|
2639
|
+
}
|
|
2640
|
+
if (action === 'clear') {
|
|
2641
|
+
link.stages = link.stages.filter((stage) => stage.status === 'active')
|
|
2642
|
+
link.updatedAt = Date.now()
|
|
2643
|
+
await persist(link)
|
|
2644
|
+
return { ok: true, action: 'clear', stages: view() }
|
|
2645
|
+
}
|
|
2646
|
+
if (action === 'start' || action === 'complete') {
|
|
2647
|
+
if (link.pending !== null) {
|
|
2648
|
+
throw new CollabError(`仍在等待该员工第 ${link.pending.round} 轮回报,等回报后再推进阶段。`)
|
|
2649
|
+
}
|
|
2650
|
+
let next
|
|
2651
|
+
if (action === 'complete') {
|
|
2652
|
+
const active = link.stages.find((stage) => stage.status === 'active')
|
|
2653
|
+
if (active === undefined) throw new CollabError('当前没有进行中的阶段;用 action=start 开始第一个阶段。')
|
|
2654
|
+
active.status = 'done'
|
|
2655
|
+
active.completedAt = Date.now()
|
|
2656
|
+
active.summary = typeof args?.summary === 'string' ? clip(args.summary.trim(), 2000) : ''
|
|
2657
|
+
await persist(link)
|
|
2658
|
+
next = link.stages.find((stage) => stage.status === 'pending')
|
|
2659
|
+
if (next === undefined) {
|
|
2660
|
+
link.updatedAt = Date.now()
|
|
2661
|
+
await persist(link)
|
|
2662
|
+
return { ok: true, action: 'complete', done: true, next: null, stages: view(), message: '当前阶段已完成,队列里没有下一阶段。' }
|
|
2663
|
+
}
|
|
2664
|
+
} else {
|
|
2665
|
+
if (link.stages.some((stage) => stage.status === 'active')) {
|
|
2666
|
+
throw new CollabError('已有进行中的阶段;请先 complete 或等它结束。')
|
|
2667
|
+
}
|
|
2668
|
+
next = link.stages.find((stage) => stage.status === 'pending')
|
|
2669
|
+
if (next === undefined) throw new CollabError('队列里没有待开始的阶段。')
|
|
2670
|
+
}
|
|
2671
|
+
next.status = 'active'
|
|
2672
|
+
next.startedAt = Date.now()
|
|
2673
|
+
delete next.completedAt
|
|
2674
|
+
link.updatedAt = Date.now()
|
|
2675
|
+
await persist(link)
|
|
2676
|
+
try {
|
|
2677
|
+
const receipt = await dispatchRound(link, next.prompt, next.acceptance, exec.signal, false)
|
|
2678
|
+
return {
|
|
2679
|
+
ok: true,
|
|
2680
|
+
action,
|
|
2681
|
+
done: action === 'complete',
|
|
2682
|
+
stage: { id: next.id, title: next.title, index: link.stages.indexOf(next) + 1 },
|
|
2683
|
+
round: receipt.round,
|
|
2684
|
+
stages: view(),
|
|
2685
|
+
message: `已开始阶段「${next.title || next.id}」,第 ${receipt.round} 轮任务已派发。`,
|
|
2686
|
+
}
|
|
2687
|
+
} catch (error) {
|
|
2688
|
+
next.status = 'pending'
|
|
2689
|
+
delete next.startedAt
|
|
2690
|
+
await persist(link)
|
|
2691
|
+
throw error
|
|
2692
|
+
}
|
|
2693
|
+
}
|
|
2694
|
+
throw new CollabError('action 必须是 add | list | start | complete | remove | clear。')
|
|
2695
|
+
},
|
|
2696
|
+
when: ({ agent }) => managerHasWork(agent.id),
|
|
2697
|
+
})
|
|
2698
|
+
|
|
2429
2699
|
toolExecutors.done = register({
|
|
2430
2700
|
name: 'collab_done',
|
|
2431
2701
|
description:
|
|
@@ -2628,6 +2898,7 @@ export function apply(ctx, rawConfig) {
|
|
|
2628
2898
|
dispatch: 'dispatch',
|
|
2629
2899
|
configure: 'configure',
|
|
2630
2900
|
project: 'project',
|
|
2901
|
+
stage: 'stage',
|
|
2631
2902
|
remote: 'remote',
|
|
2632
2903
|
done: 'done',
|
|
2633
2904
|
unlink: 'unlink',
|
|
@@ -2635,9 +2906,9 @@ export function apply(ctx, rawConfig) {
|
|
|
2635
2906
|
}
|
|
2636
2907
|
ctx.commands.register({
|
|
2637
2908
|
name: 'collab',
|
|
2638
|
-
description: '
|
|
2909
|
+
description: '双对话协作:查看全部任务、关联员工、阶段队列、跨设备中继、设置项目名、配置预设与语言、派发任务、收尾或解除。',
|
|
2639
2910
|
input: {
|
|
2640
|
-
hint: 'tasks | status | link --peer <id|new> | create --name <名字> --
|
|
2911
|
+
hint: 'tasks | status | link --peer <id|new> | create --name <名字> | stage --action add --prompt ... | relay --action set --mode hub|ntfy | remote --action link --device <名> --worker <别名> | project --name <项目名> | dispatch --worker <id> --task ... | done --worker <id> --summary ...',
|
|
2641
2912
|
},
|
|
2642
2913
|
handler: async (invocation) => {
|
|
2643
2914
|
try {
|
|
@@ -2645,6 +2916,49 @@ export function apply(ctx, rawConfig) {
|
|
|
2645
2916
|
if (action === 'tasks' || action === 'board') {
|
|
2646
2917
|
return { kind: 'success', text: JSON.stringify(await tasksBoard()) }
|
|
2647
2918
|
}
|
|
2919
|
+
if (action === 'relay') {
|
|
2920
|
+
const sub = typeof args?.action === 'string' ? args.action : 'get'
|
|
2921
|
+
if (sub === 'get') return { kind: 'success', text: JSON.stringify(relayStatus()) }
|
|
2922
|
+
if (sub === 'test') {
|
|
2923
|
+
if (!relayConfigured()) return { kind: 'error', text: '中继未启用:先选择模式并保存。' }
|
|
2924
|
+
try {
|
|
2925
|
+
if (cfg.relayMode === 'hub') {
|
|
2926
|
+
await hubFetch(`/v1/head?room=${encodeURIComponent(cfg.hubRoom)}`)
|
|
2927
|
+
} else {
|
|
2928
|
+
const response = await fetch(`https://ntfy.sh/${encodeURIComponent(ntfyTopic())}/json?poll=1&since=10m`, { signal: AbortSignal.timeout(15000) })
|
|
2929
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}`)
|
|
2930
|
+
await response.text()
|
|
2931
|
+
}
|
|
2932
|
+
return { kind: 'success', text: JSON.stringify({ ok: true, mode: cfg.relayMode, device: cfg.deviceName, room: cfg.hubRoom }) }
|
|
2933
|
+
} catch (error) {
|
|
2934
|
+
return { kind: 'error', text: `连接测试失败:${error instanceof Error ? error.message : String(error)}` }
|
|
2935
|
+
}
|
|
2936
|
+
}
|
|
2937
|
+
if (sub === 'set') {
|
|
2938
|
+
const mode = args?.mode === 'hub' || args?.mode === 'ntfy' || args?.mode === 'off' ? args.mode : ''
|
|
2939
|
+
if (mode === '') return { kind: 'error', text: 'mode 必须是 hub / ntfy / off。' }
|
|
2940
|
+
const hubUrl = normalizeHubUrl(args?.hubUrl)
|
|
2941
|
+
const room = typeof args?.hubRoom === 'string' && /^[A-Za-z0-9_-]{1,64}$/.test(args.hubRoom) ? args.hubRoom : 'default'
|
|
2942
|
+
const providedToken = typeof args?.hubToken === 'string' ? args.hubToken.trim() : ''
|
|
2943
|
+
const token = providedToken === '' && args?.keepToken === true ? cfg.hubToken : providedToken
|
|
2944
|
+
const device = deviceText(args?.deviceName)
|
|
2945
|
+
if (mode === 'hub' && (hubUrl === '' || token === '')) return { kind: 'error', text: '自建 hub 需要 hubUrl 和 token。' }
|
|
2946
|
+
if (mode === 'ntfy' && (token.length < 16 || room === 'default')) return { kind: 'error', text: '免费中继需要至少 16 位的 token,以及一个非 default 的房间名。' }
|
|
2947
|
+
const entry = ctx.fiber?.entry
|
|
2948
|
+
const editor = ctx.get('configEditor')
|
|
2949
|
+
if (entry === undefined || editor === undefined) return { kind: 'error', text: '当前环境无法保存中继设置。' }
|
|
2950
|
+
await editor.edit(entry, (current) => ({
|
|
2951
|
+
...current,
|
|
2952
|
+
relayMode: mode,
|
|
2953
|
+
hubUrl,
|
|
2954
|
+
hubRoom: room,
|
|
2955
|
+
hubToken: token,
|
|
2956
|
+
deviceName: device,
|
|
2957
|
+
}))
|
|
2958
|
+
return { kind: 'success', text: JSON.stringify({ ok: true, mode, reload: true }) }
|
|
2959
|
+
}
|
|
2960
|
+
return { kind: 'error', text: 'action 必须是 get / set / test。' }
|
|
2961
|
+
}
|
|
2648
2962
|
if (action === 'language') {
|
|
2649
2963
|
const next = typeof args?.language === 'string' ? args.language : typeof args?.value === 'string' ? args.value : ''
|
|
2650
2964
|
if (next !== 'zh' && next !== 'en') return { kind: 'error', text: 'language must be zh or en' }
|
package/package.json
CHANGED
|
@@ -1,9 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-collab-pair",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "For large projects: link a project-manager conversation with local or remote workers across devices (temporary
|
|
3
|
+
"version": "1.4.0",
|
|
4
|
+
"description": "For large projects: link a project-manager conversation with local or remote workers across devices (temporary or permanent), dispatch each round from the manager, relay results automatically, pre-write a stage queue that advances when a stage completes, and manage it all from a visual Settings page and a conversation context menu. Includes a relay hub and a free ntfy.sh transport for cross-device runs.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
7
|
+
"author": "awa1231",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/awa1231/dsh-collab-pair.git"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/awa1231/dsh-collab-pair#readme",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/awa1231/dsh-collab-pair/issues"
|
|
15
|
+
},
|
|
7
16
|
"scripts": {
|
|
8
17
|
"prepack": "node ../sync.mjs"
|
|
9
18
|
},
|