@soffits/dsh-channel-core 0.1.0 → 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.
- package/CHANGELOG.md +8 -0
- package/README.md +5 -0
- package/index.js +33 -0
- package/package.json +4 -2
- package/src/config.js +18 -0
- package/src/sessions.js +372 -0
- package/src/spool.js +175 -0
- package/src/subagents.js +540 -0
- package/testing.js +132 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.2.0
|
|
4
|
+
|
|
5
|
+
- Session helpers both bridges used in their own copies: resolving and creating sessions, claiming a new one so the Web UI does not reuse it, workspaces, unarchiving, admitting a prompt once per request id (with sender, envelope and time zone), clearing a chat's pending prompts, recording a note without a turn, reading recent answers and titles, and the access-mode fallback.
|
|
6
|
+
- The file spool for requests from outside the Host, with the directory passed by the bridge. A spool stopped while it was starting no longer keeps polling, and a request's claim is removed before its result shows, so a stop in between can never send it twice.
|
|
7
|
+
- The subagent status card (`createAgentBoards`) and the `/agents` text (`subagentsText`), from the Telegram bridge.
|
|
8
|
+
- `@soffits/dsh-channel-core/testing`: fakes of DSH's pre-step gate, title service and model selection for bridge tests.
|
|
9
|
+
- `readLive` for settings that may be live references.
|
|
10
|
+
|
|
3
11
|
## 0.1.0
|
|
4
12
|
|
|
5
13
|
- First release: the final answer of a turn and the silent marker, session model selection from the Web catalog, voice transcription, and the sender principal and envelope recorded on prompts, taken from dsh-telegram-bot and dsh-matrix-bot so both use one copy.
|
package/README.md
CHANGED
|
@@ -6,6 +6,11 @@ Shared building blocks for [DeepSeek Harness](https://github.com/deepseek-ai/dee
|
|
|
6
6
|
- **Silent marker** (`SILENT_REPLY`, `cutSilent`): an answer ending in `[SILENT]` posts nothing more; while streaming, a trailing part that may still become the marker is held back.
|
|
7
7
|
- **Session models** (`sessionModelOf`, `selectSessionModel`, `createModelCatalog`, `modelName`, `effortChoices`, `effortName`, `pickedSelection`, `isGoneModel`, `sameSelection`, `defaultModelOf`, `findModel`): read and switch one session's model with the same catalog and rules as the Web model picker, without changing the default for new sessions.
|
|
8
8
|
- **Voice** (`transcribe`, `transcriptNote`, `pcmToWave`, `runProgram`): transcribe a recording with DSH speech-to-text (through ffmpeg) or a configured command, and the note the agent reads next to it.
|
|
9
|
+
- **Sessions** (`resolveAgent`, `createSession`, `claimSession`, `attachToWorkspace`, `unarchive`, `admitPrompt`, `hasRequest`, `removePending`, `hasPendingInput`, `recordMessage`, `recentAssistantTexts`, `storedTitle`, `listWorkspaces`, `sessionsInWorkspace`, `appendAccessMode`): find, create and prompt a chat's session through the Web UI's own session controller, with the agent registry as the fallback; a new session is never left blank for the Web UI's New conversation to take; prompts are admitted once per request id; notes go into a session without starting a turn.
|
|
10
|
+
- **Spool** (`enqueue`, `waitForResult`, `withdraw`, `createSpool`): a file queue in a directory the bridge picks, so a command line or a scheduled job can hand requests to the running bridge without a token or a network route to the Host.
|
|
11
|
+
- **Subagents** (`createAgentBoards`, `subagentsText`, `subagentLabel`, `boardText`, `agentsListText`, `collectSubagents`, `childState`, `reportOf`, `formatElapsed`): one status card per chat for the subagents a session starts, edited as they start and finish (kept at the bottom on networks whose message ids grow), and the `/agents` list read from DSH's durable catalogs.
|
|
12
|
+
- **Testing** (`@soffits/dsh-channel-core/testing`: `followupThroughGate`, `makeTitleService`, `makeAgentModel`): fakes of DSH behaviour for a bridge's own test Host.
|
|
13
|
+
- **Config** (`readLive`): read a plugin setting that may be a live reference.
|
|
9
14
|
- **Sender** (`sendPrincipal`, `withMetadata`, `createPrincipalTagger`, `senderSession`, `nonEmpty`): who sent a prompt as `source.principal`, and when and in reply to what as `source.envelope`, recorded on the message itself and never in its text. Network-specific principals (a Telegram user, a Matrix user) stay in each bridge and use the same fields.
|
|
10
15
|
|
|
11
16
|
It is a plain library, not a DSH plugin: bridges list it as a dependency. Used by [dsh-telegram-bot](https://github.com/soffits/dsh-telegram-bot) and [dsh-matrix-bot](https://github.com/soffits/dsh-matrix-bot).
|
package/index.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
export { readLive } from './src/config.js'
|
|
1
2
|
export { SILENT_REPLY, answerSegments, cutSilent, isInterjection, messageAnswer, turnAnswer } from './src/answer.js'
|
|
2
3
|
export {
|
|
3
4
|
createModelCatalog,
|
|
@@ -14,3 +15,35 @@ export {
|
|
|
14
15
|
} from './src/models.js'
|
|
15
16
|
export { MAX_PENDING_PRINCIPALS, createPrincipalTagger, nonEmpty, sendPrincipal, senderSession, withMetadata } from './src/principal.js'
|
|
16
17
|
export { pcmToWave, runProgram, transcribe, transcriptNote } from './src/voice.js'
|
|
18
|
+
export {
|
|
19
|
+
admitPrompt,
|
|
20
|
+
appendAccessMode,
|
|
21
|
+
attachToWorkspace,
|
|
22
|
+
claimSession,
|
|
23
|
+
controllerOf,
|
|
24
|
+
createSession,
|
|
25
|
+
hasPendingInput,
|
|
26
|
+
hasRequest,
|
|
27
|
+
hasSystemHead,
|
|
28
|
+
inInbox,
|
|
29
|
+
listWorkspaces,
|
|
30
|
+
recentAssistantTexts,
|
|
31
|
+
recordMessage,
|
|
32
|
+
removePending,
|
|
33
|
+
resolveAgent,
|
|
34
|
+
sessionsInWorkspace,
|
|
35
|
+
storedTitle,
|
|
36
|
+
unarchive,
|
|
37
|
+
} from './src/sessions.js'
|
|
38
|
+
export { createSpool, enqueue, waitForResult, withdraw } from './src/spool.js'
|
|
39
|
+
export {
|
|
40
|
+
agentsListText,
|
|
41
|
+
boardText,
|
|
42
|
+
childState,
|
|
43
|
+
collectSubagents,
|
|
44
|
+
createAgentBoards,
|
|
45
|
+
formatElapsed,
|
|
46
|
+
reportOf,
|
|
47
|
+
subagentLabel,
|
|
48
|
+
subagentsText,
|
|
49
|
+
} from './src/subagents.js'
|
package/package.json
CHANGED
|
@@ -1,15 +1,17 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@soffits/dsh-channel-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Shared core for DeepSeek Harness chat bridges: the final answer of a turn and the silent marker, session model selection from the Web catalog, voice transcription, and the sender principal recorded on prompts.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./index.js",
|
|
7
7
|
"exports": {
|
|
8
8
|
".": "./index.js",
|
|
9
|
+
"./testing": "./testing.js",
|
|
9
10
|
"./package.json": "./package.json"
|
|
10
11
|
},
|
|
11
12
|
"files": [
|
|
12
13
|
"index.js",
|
|
14
|
+
"testing.js",
|
|
13
15
|
"src/*.js",
|
|
14
16
|
"README.md",
|
|
15
17
|
"CHANGELOG.md",
|
|
@@ -20,7 +22,7 @@
|
|
|
20
22
|
},
|
|
21
23
|
"scripts": {
|
|
22
24
|
"test": "node --test \"test/*.test.js\"",
|
|
23
|
-
"check": "for f in index.js src/*.js test/*.js; do node --check \"$f\" || exit 1; done"
|
|
25
|
+
"check": "for f in index.js testing.js src/*.js test/*.js; do node --check \"$f\" || exit 1; done"
|
|
24
26
|
},
|
|
25
27
|
"keywords": [
|
|
26
28
|
"dsh",
|
package/src/config.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read a plugin config field that may be a plain value or a live reference
|
|
3
|
+
* (an object with `get`, as DSH passes volatile settings and credentials).
|
|
4
|
+
* @param value - config field.
|
|
5
|
+
* @param fallback - value used when the field is absent or cannot be read.
|
|
6
|
+
* @returns the current value.
|
|
7
|
+
*/
|
|
8
|
+
export function readLive(value, fallback) {
|
|
9
|
+
if (value !== null && typeof value === 'object' && typeof value.get === 'function') {
|
|
10
|
+
try {
|
|
11
|
+
const current = value.get()
|
|
12
|
+
return current === undefined ? fallback : current
|
|
13
|
+
} catch {
|
|
14
|
+
return fallback
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
return value === undefined || value === null ? fallback : value
|
|
18
|
+
}
|
package/src/sessions.js
ADDED
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The DSH side of a chat: finding, creating and prompting sessions through
|
|
3
|
+
* the Host services the Web UI uses (`sessionController`), with the raw agent
|
|
4
|
+
* registry as the headless fallback, and reading what a session said.
|
|
5
|
+
*/
|
|
6
|
+
import { randomUUID } from 'node:crypto'
|
|
7
|
+
|
|
8
|
+
/** @returns the Web session controller, when this deployment mounts it. */
|
|
9
|
+
export function controllerOf(ctx) {
|
|
10
|
+
const controller = ctx.get('sessionController')
|
|
11
|
+
return typeof controller?.create === 'function' && typeof controller?.resolveAgent === 'function' ? controller : undefined
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* The live agent of a session, resuming it when needed.
|
|
16
|
+
* @param ctx - Host context.
|
|
17
|
+
* @param sessionId - session id.
|
|
18
|
+
* @param resumeOptions - extra options for the agent registry's `resume`
|
|
19
|
+
* (`agentOptions`, `setup`), used only without a session controller.
|
|
20
|
+
* @returns the agent; throws when the session cannot be resumed.
|
|
21
|
+
*/
|
|
22
|
+
export async function resolveAgent(ctx, sessionId, resumeOptions = {}) {
|
|
23
|
+
const agents = ctx.get('agents')
|
|
24
|
+
const live = agents?.get(sessionId)
|
|
25
|
+
if (live !== undefined) return live
|
|
26
|
+
const controller = controllerOf(ctx)
|
|
27
|
+
if (controller !== undefined) {
|
|
28
|
+
const found = await controller.resolveAgent(sessionId)
|
|
29
|
+
if (found?.error !== undefined) throw found.error
|
|
30
|
+
const agent = found?.agent ?? agents?.get(sessionId)
|
|
31
|
+
if (agent === undefined) throw new Error(`session ${sessionId} has no live agent`)
|
|
32
|
+
return agent
|
|
33
|
+
}
|
|
34
|
+
if (agents === undefined) throw new Error('dsh-agent is not mounted in this profile')
|
|
35
|
+
const resumed = await agents.resume({ resumeSessionId: sessionId, ...resumeOptions })
|
|
36
|
+
if (resumed?.agent === undefined) throw new Error(`session ${sessionId} could not be resumed`)
|
|
37
|
+
return resumed.agent
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Create a session the way the Web UI composes one (preset, default model,
|
|
42
|
+
* model-switch notices), falling back to the agent registry.
|
|
43
|
+
* @param ctx - Host context.
|
|
44
|
+
* @param options - `{ cwd, preset, setup, agentOptions, warn }`; `setup` and
|
|
45
|
+
* `agentOptions` go to the registry's `create` on the fallback path only.
|
|
46
|
+
* @returns the new session's agent.
|
|
47
|
+
*/
|
|
48
|
+
export async function createSession(ctx, { cwd, preset, setup, agentOptions, warn }) {
|
|
49
|
+
const controller = controllerOf(ctx)
|
|
50
|
+
if (controller !== undefined) {
|
|
51
|
+
try {
|
|
52
|
+
const created = await controller.create({ cwd, ...(preset ? { agentPreset: preset } : {}) })
|
|
53
|
+
return await resolveAgent(ctx, created.sessionId)
|
|
54
|
+
} catch (error) {
|
|
55
|
+
warn(`sessionController create failed, using the agent registry: ${error?.message ?? error}`)
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
const agents = ctx.get('agents')
|
|
59
|
+
if (agents === undefined) throw new Error('dsh-agent is not mounted in this profile')
|
|
60
|
+
const meta = { cwd, ...(preset && ctx.get('agentPresets') !== undefined ? { agentPreset: preset } : {}) }
|
|
61
|
+
const created = await agents.create({
|
|
62
|
+
sessionId: `session-${randomUUID()}`,
|
|
63
|
+
meta,
|
|
64
|
+
...(agentOptions === undefined ? {} : { agentOptions }),
|
|
65
|
+
...(setup === undefined ? {} : { setup }),
|
|
66
|
+
})
|
|
67
|
+
return created.agent
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* End a new session's blank state with an empty turn that never reaches a
|
|
72
|
+
* model. DSH hands a blank session (one that never started a turn) to the
|
|
73
|
+
* next New conversation in the Web UI, and only `turn/start` ends that state.
|
|
74
|
+
* The marker message is rejected at `agent/pre-step`, the gate DSH uses for
|
|
75
|
+
* archived sessions, so the turn ends as blocked and the marker is never
|
|
76
|
+
* recorded. Call it before the session is bound to a chat, so no mirror shows
|
|
77
|
+
* this turn.
|
|
78
|
+
* @param agent - the new session's agent.
|
|
79
|
+
* @param marker - `{ text, rpcPrefix }`: the marker's text and request id prefix.
|
|
80
|
+
* @param waitMs - longest wait for the empty turn to end.
|
|
81
|
+
* @returns false when this agent cannot run the empty turn.
|
|
82
|
+
*/
|
|
83
|
+
export async function claimSession(agent, { text, rpcPrefix }, waitMs = 10_000) {
|
|
84
|
+
if (typeof agent?.followup !== 'function' || typeof agent?.ctx?.on !== 'function') return false
|
|
85
|
+
const id = randomUUID()
|
|
86
|
+
const dispose = agent.ctx.on('agent/pre-step', (payload, next) => {
|
|
87
|
+
const messages = Array.isArray(payload?.messages) ? payload.messages : []
|
|
88
|
+
if (messages.length > 0 && messages.every((message) => message?.id === id)) return Promise.resolve({ kind: 'reject' })
|
|
89
|
+
return next()
|
|
90
|
+
})
|
|
91
|
+
agent.followup({ id, role: 'user', content: [{ type: 'text', text }], source: { kind: 'user', rpcId: `${rpcPrefix}:${id}` } })
|
|
92
|
+
// The gate stays until the turn is over, so the marker can never reach a model.
|
|
93
|
+
const idle = typeof agent.whenIdle === 'function' ? agent.whenIdle() : Promise.resolve()
|
|
94
|
+
void idle.catch(() => undefined).finally(() => { if (typeof dispose === 'function') dispose() })
|
|
95
|
+
let timer
|
|
96
|
+
await Promise.race([
|
|
97
|
+
idle.catch(() => undefined),
|
|
98
|
+
new Promise((resolveWait) => { timer = setTimeout(resolveWait, waitMs) }),
|
|
99
|
+
])
|
|
100
|
+
clearTimeout(timer)
|
|
101
|
+
return true
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Attach a session to the workspace of its directory, creating the workspace
|
|
106
|
+
* when needed, so it shows up in the Web UI sidebar.
|
|
107
|
+
* @param ctx - Host context.
|
|
108
|
+
* @param sessionId - session id.
|
|
109
|
+
* @param cwd - session directory.
|
|
110
|
+
* @param warn - logger.
|
|
111
|
+
*/
|
|
112
|
+
export async function attachToWorkspace(ctx, sessionId, cwd, warn) {
|
|
113
|
+
const registry = ctx.get('workspaceRegistry')
|
|
114
|
+
if (registry === undefined) return
|
|
115
|
+
try {
|
|
116
|
+
let workspace = registry.list().find((entry) => entry.path === cwd)
|
|
117
|
+
if (workspace === undefined) workspace = await registry.create(cwd)
|
|
118
|
+
await workspace.attachSession(sessionId)
|
|
119
|
+
} catch (error) {
|
|
120
|
+
warn(`workspace attach failed for ${sessionId}: ${error?.message ?? error}`)
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Bring an archived session back before a chat message starts a turn in it:
|
|
126
|
+
* DSH admits prompts into archived sessions but rejects every model step.
|
|
127
|
+
* @param ctx - Host context.
|
|
128
|
+
* @param sessionId - session id.
|
|
129
|
+
* @returns `unarchived`, `unsupported` (archived, and this DSH cannot bring it
|
|
130
|
+
* back), or undefined when the session is not archived.
|
|
131
|
+
*/
|
|
132
|
+
export async function unarchive(ctx, sessionId) {
|
|
133
|
+
const registry = ctx.get('workspaceRegistry')
|
|
134
|
+
if (registry?.archivedSessionIds?.includes(sessionId) !== true) return undefined
|
|
135
|
+
if (typeof registry.unarchiveSession !== 'function') return 'unsupported'
|
|
136
|
+
await registry.unarchiveSession(sessionId)
|
|
137
|
+
return 'unarchived'
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const requestMatcher = (requestId) => (message) => message?.source?.kind === 'user' && message.source.rpcId === requestId
|
|
141
|
+
|
|
142
|
+
/** @returns whether a message the agent has not taken yet carries this request id. */
|
|
143
|
+
export function inInbox(agent, requestId) {
|
|
144
|
+
const matches = requestMatcher(requestId)
|
|
145
|
+
const inbox = agent?.inbox
|
|
146
|
+
return inbox?.nextTurn?.some?.(matches) === true || inbox?.nextStep?.some?.(matches) === true
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** @returns whether a pending or recorded message carries this request id. */
|
|
150
|
+
export function hasRequest(agent, requestId) {
|
|
151
|
+
if (inInbox(agent, requestId)) return true
|
|
152
|
+
const matches = requestMatcher(requestId)
|
|
153
|
+
const events = typeof agent?.session?.snapshotEvents === 'function' ? agent.session.snapshotEvents() : []
|
|
154
|
+
return events.some((event) => event?.type === 'user/message' && matches(event.data))
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Hand one prompt to a session. Text goes through the session controller's
|
|
159
|
+
* `prompt`, the Web UI's own path; prompts with stored attachments go to the
|
|
160
|
+
* agent's `steer` (into the running turn) or `followup` (queued), the methods
|
|
161
|
+
* that path calls. A request id already admitted is skipped, so a message
|
|
162
|
+
* handled twice (a redelivery, a restart between admission and marking it
|
|
163
|
+
* seen) reaches the agent once. In steer mode DSH keeps a running turn going
|
|
164
|
+
* while its next-step inbox holds input and opens a new turn for input left
|
|
165
|
+
* after `turn/end`, so a steered prompt is never dropped.
|
|
166
|
+
* @param ctx - Host context.
|
|
167
|
+
* @param agent - the session's agent.
|
|
168
|
+
* @param prompt - `{ requestId, text, attachments, mode, principal, envelope,
|
|
169
|
+
* clientTimeZone }`; `mode` is `queue` or `steer`; `principal` and
|
|
170
|
+
* `envelope` go on the message's source (the controller builds its own
|
|
171
|
+
* message, so the tagger records them at its step); `clientTimeZone` is
|
|
172
|
+
* DSH's field for the zone of the person behind a prompt.
|
|
173
|
+
* @param signal - request lifetime.
|
|
174
|
+
* @param tagger - a `createPrincipalTagger` that records the metadata on the
|
|
175
|
+
* controller's message.
|
|
176
|
+
* @returns `admitted`, `known` (already admitted), `empty`, or `unsupported`
|
|
177
|
+
* when the agent offers no way in.
|
|
178
|
+
*/
|
|
179
|
+
export async function admitPrompt(ctx, agent, { requestId, text, attachments = [], mode, principal, envelope, clientTimeZone }, signal, tagger) {
|
|
180
|
+
if (hasRequest(agent, requestId)) return 'known'
|
|
181
|
+
const content = [...(text.trim().length === 0 ? [] : [{ type: 'text', text }]), ...attachments]
|
|
182
|
+
if (content.length === 0) return 'empty'
|
|
183
|
+
const zone = clientTimeZone === undefined ? {} : { clientTimeZone }
|
|
184
|
+
const controller = ctx.get('sessionController')
|
|
185
|
+
if (attachments.length === 0 && typeof controller?.prompt === 'function') {
|
|
186
|
+
tagger?.remember(requestId, { principal, envelope })
|
|
187
|
+
await controller.prompt({ sessionId: agent.session?.id ?? agent.id, requestId, mode, content, ...zone }, signal)
|
|
188
|
+
return 'admitted'
|
|
189
|
+
}
|
|
190
|
+
const steer = mode === 'steer'
|
|
191
|
+
const enter = steer ? agent?.steer : agent?.followup
|
|
192
|
+
if (typeof enter !== 'function' && typeof agent?.send !== 'function') return 'unsupported'
|
|
193
|
+
tagger?.remember(requestId, { principal, envelope })
|
|
194
|
+
const message = {
|
|
195
|
+
id: randomUUID(),
|
|
196
|
+
role: 'user',
|
|
197
|
+
content,
|
|
198
|
+
source: { kind: 'user', rpcId: requestId, ...zone, ...(principal === undefined ? {} : { principal }), ...(envelope === undefined ? {} : { envelope }) },
|
|
199
|
+
}
|
|
200
|
+
if (typeof enter === 'function') enter.call(agent, message)
|
|
201
|
+
else agent.send(message, steer ? 'next-step' : 'next-turn', true)
|
|
202
|
+
return 'admitted'
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Remove prompts the agent has not taken yet, from both inboxes.
|
|
207
|
+
* @param agent - the session's agent.
|
|
208
|
+
* @param ours - test on a prompt's request id, so only the chat's own go.
|
|
209
|
+
* @returns how many were removed.
|
|
210
|
+
*/
|
|
211
|
+
export function removePending(agent, ours) {
|
|
212
|
+
const inbox = agent?.inbox
|
|
213
|
+
if (typeof inbox?.remove !== 'function') return 0
|
|
214
|
+
const matches = (message) => message?.source?.kind === 'user' && typeof message.source.rpcId === 'string' && ours(message.source.rpcId)
|
|
215
|
+
const pending = [...(inbox.nextStep ?? []), ...(inbox.nextTurn ?? [])].filter(matches)
|
|
216
|
+
for (const message of pending) inbox.remove(message.id)
|
|
217
|
+
return pending.length
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Whether the agent still holds input it has not taken; DSH starts another
|
|
222
|
+
* turn for it right after the current one ends.
|
|
223
|
+
*/
|
|
224
|
+
export function hasPendingInput(agent) {
|
|
225
|
+
const inbox = agent?.inbox
|
|
226
|
+
if (inbox === undefined) return false
|
|
227
|
+
if (typeof inbox.hasPending === 'boolean') return inbox.hasPending
|
|
228
|
+
return (inbox.nextStep?.length ?? 0) > 0 || (inbox.nextTurn?.length ?? 0) > 0
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
const SURFACE_TYPES = new Set(['system/message', 'user/message', 'developer/message', 'assistant/message', 'tool/result'])
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Whether a session's first surface node is its system message. DSH's log
|
|
235
|
+
* format rejects a log whose first system message comes after another surface
|
|
236
|
+
* message, so only then may a message be appended outside a step.
|
|
237
|
+
* @param session - DSH session.
|
|
238
|
+
* @returns false when the head cannot be read, so callers queue instead.
|
|
239
|
+
*/
|
|
240
|
+
export function hasSystemHead(session) {
|
|
241
|
+
try {
|
|
242
|
+
const nodes = session.surface?.nodes
|
|
243
|
+
if (nodes !== undefined) {
|
|
244
|
+
if (nodes.length === 0) return false
|
|
245
|
+
const event = typeof session.eventAt === 'function'
|
|
246
|
+
? session.eventAt(nodes[0])
|
|
247
|
+
: session.snapshotEvents?.().find((item) => item.seq === nodes[0])
|
|
248
|
+
return event?.type === 'system/message'
|
|
249
|
+
}
|
|
250
|
+
const events = typeof session.snapshotEvents === 'function' ? session.snapshotEvents() : session.events
|
|
251
|
+
if (!Array.isArray(events)) return false
|
|
252
|
+
return events.find((event) => SURFACE_TYPES.has(event.type))?.type === 'system/message'
|
|
253
|
+
} catch {
|
|
254
|
+
return false
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Put a message into a session without starting a turn: appended now to an
|
|
260
|
+
* idle session whose surface starts with its system message, otherwise queued
|
|
261
|
+
* for its next step. Either way the Web UI shows it and the model reads it at
|
|
262
|
+
* its next step.
|
|
263
|
+
* @param agent - the session's agent.
|
|
264
|
+
* @param message - a user-role message (`{ id, role, content, source }`).
|
|
265
|
+
*/
|
|
266
|
+
export function recordMessage(agent, message) {
|
|
267
|
+
if (agent.status === 'idle' && typeof agent.session?.append === 'function' && hasSystemHead(agent.session)) {
|
|
268
|
+
agent.session.append('user/message', message, { surfaceOp: 'append' })
|
|
269
|
+
} else if (typeof agent.inject === 'function') {
|
|
270
|
+
agent.inject(message)
|
|
271
|
+
} else if (typeof agent.send === 'function') {
|
|
272
|
+
agent.send(message, 'next-step', false)
|
|
273
|
+
} else {
|
|
274
|
+
throw new Error('The session cannot record messages.')
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* A session's title as DSH stores it.
|
|
280
|
+
* @param ctx - Host context.
|
|
281
|
+
* @param sessionId - session id.
|
|
282
|
+
* @returns the title, or undefined while the session has none.
|
|
283
|
+
*/
|
|
284
|
+
export async function storedTitle(ctx, sessionId) {
|
|
285
|
+
try {
|
|
286
|
+
const snapshot = await ctx.get('sessionQuery')?.readTitleSnapshot(sessionId)
|
|
287
|
+
const title = snapshot?.title?.title
|
|
288
|
+
return typeof title === 'string' && title.trim().length > 0 ? title.trim() : undefined
|
|
289
|
+
} catch {
|
|
290
|
+
return undefined
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* The latest assistant texts of a session, newest first.
|
|
296
|
+
* @param ctx - Host context.
|
|
297
|
+
* @param sessionId - session id.
|
|
298
|
+
* @param limit - most texts.
|
|
299
|
+
* @returns the texts; empty when the session cannot be read.
|
|
300
|
+
*/
|
|
301
|
+
export async function recentAssistantTexts(ctx, sessionId, limit) {
|
|
302
|
+
const texts = []
|
|
303
|
+
try {
|
|
304
|
+
const surface = await ctx.get('sessionQuery')?.readSurface(sessionId)
|
|
305
|
+
const events = surface?.events ?? []
|
|
306
|
+
for (let index = events.length - 1; index >= 0 && texts.length < limit; index -= 1) {
|
|
307
|
+
const event = events[index]
|
|
308
|
+
if (event?.type !== 'assistant/message') continue
|
|
309
|
+
const message = event.data?.message ?? event.data
|
|
310
|
+
const content = Array.isArray(message?.content) ? message.content : []
|
|
311
|
+
const text = content.filter((block) => block?.type === 'text').map((block) => block.text).join('\n').trim()
|
|
312
|
+
if (text.length > 0) texts.push(text)
|
|
313
|
+
}
|
|
314
|
+
} catch {
|
|
315
|
+
// An empty result is reported by the caller.
|
|
316
|
+
}
|
|
317
|
+
return texts
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/** @returns the registered workspaces, or an empty list. */
|
|
321
|
+
export function listWorkspaces(ctx) {
|
|
322
|
+
try {
|
|
323
|
+
return ctx.get('workspaceRegistry')?.list() ?? []
|
|
324
|
+
} catch {
|
|
325
|
+
return []
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* Recent ordinary sessions (not archived, not subagents), newest first.
|
|
331
|
+
* @param ctx - Host context.
|
|
332
|
+
* @param workspace - workspace record, or undefined for every workspace.
|
|
333
|
+
* @param limit - most sessions.
|
|
334
|
+
* @param signal - request lifetime.
|
|
335
|
+
*/
|
|
336
|
+
export async function sessionsInWorkspace(ctx, workspace, limit, signal) {
|
|
337
|
+
const query = ctx.get('sessionQuery')
|
|
338
|
+
if (query === undefined) return []
|
|
339
|
+
const archived = new Set(ctx.get('workspaceRegistry')?.archivedSessionIds ?? [])
|
|
340
|
+
const records = await query.listSessions(signal)
|
|
341
|
+
return records
|
|
342
|
+
.filter((record) => !archived.has(record.header.id))
|
|
343
|
+
.filter((record) => record.header?.origin !== 'subagent')
|
|
344
|
+
.filter((record) => workspace === undefined
|
|
345
|
+
|| (workspace.sessionIds ?? []).includes(record.header.id)
|
|
346
|
+
|| record.header.cwd === workspace.path)
|
|
347
|
+
.sort((left, right) => (right.header.createdAt ?? 0) - (left.header.createdAt ?? 0))
|
|
348
|
+
.slice(0, limit)
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/** Sandbox mode and approval policy behind each built-in access mode. */
|
|
352
|
+
const ACCESS_MODES = {
|
|
353
|
+
'workspace-write': ['workspace-write', 'ask'],
|
|
354
|
+
'danger-full-access': ['danger-full-access', 'never'],
|
|
355
|
+
'read-only': ['read-only', 'ask'],
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/**
|
|
359
|
+
* Set a session's access mode by appending its knob events, for a DSH whose
|
|
360
|
+
* `permissionPresets` service cannot set it from a plugin.
|
|
361
|
+
* @param session - DSH session.
|
|
362
|
+
* @param value - a built-in access mode.
|
|
363
|
+
* @returns false for a mode this fallback does not know.
|
|
364
|
+
*/
|
|
365
|
+
export function appendAccessMode(session, value) {
|
|
366
|
+
const spec = ACCESS_MODES[value]
|
|
367
|
+
if (spec === undefined) return false
|
|
368
|
+
session.append('permission/preset', { preset: value })
|
|
369
|
+
session.append('sandbox/mode', { mode: spec[0] })
|
|
370
|
+
session.append('approval/policy', { policy: spec[1] })
|
|
371
|
+
return true
|
|
372
|
+
}
|
package/src/spool.js
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File spool for requests from outside the Host process (a bridge's command
|
|
3
|
+
* line, a scheduled job): a sender writes one request file, the running
|
|
4
|
+
* plugin handles it and writes a result file next to it. Senders need no network access to the
|
|
5
|
+
* Host, only write access to the DSH home, and requests wait while the bot is
|
|
6
|
+
* stopped.
|
|
7
|
+
*/
|
|
8
|
+
import { randomUUID } from 'node:crypto'
|
|
9
|
+
import { watch } from 'node:fs'
|
|
10
|
+
import { mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'
|
|
11
|
+
import { join } from 'node:path'
|
|
12
|
+
|
|
13
|
+
/** Result files older than this are removed by the plugin. */
|
|
14
|
+
const RESULT_TTL_MS = 24 * 60 * 60 * 1000
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Write one request atomically.
|
|
18
|
+
* @param request - `{ op, ... }`.
|
|
19
|
+
* @param dir - spool directory.
|
|
20
|
+
* @returns the request id.
|
|
21
|
+
*/
|
|
22
|
+
export async function enqueue(request, dir) {
|
|
23
|
+
await mkdir(dir, { recursive: true, mode: 0o700 })
|
|
24
|
+
const id = `${Date.now()}-${randomUUID().slice(0, 8)}`
|
|
25
|
+
const temporary = join(dir, `${id}.tmp`)
|
|
26
|
+
await writeFile(temporary, JSON.stringify({ ...request, id, createdAt: Date.now() }) + '\n', { mode: 0o600 })
|
|
27
|
+
await rename(temporary, join(dir, `${id}.json`))
|
|
28
|
+
return id
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Wait for the plugin's result for one request.
|
|
33
|
+
* @param id - request id from {@link enqueue}.
|
|
34
|
+
* @param timeoutMs - how long to wait.
|
|
35
|
+
* @param dir - spool directory.
|
|
36
|
+
* @returns the result document, or undefined after the timeout.
|
|
37
|
+
*/
|
|
38
|
+
export async function waitForResult(id, timeoutMs, dir) {
|
|
39
|
+
const path = join(dir, `${id}.result.json`)
|
|
40
|
+
const deadline = Date.now() + timeoutMs
|
|
41
|
+
for (;;) {
|
|
42
|
+
try {
|
|
43
|
+
const result = JSON.parse(await readFile(path, 'utf8'))
|
|
44
|
+
await rm(path, { force: true })
|
|
45
|
+
return result
|
|
46
|
+
} catch {
|
|
47
|
+
// Not written yet.
|
|
48
|
+
}
|
|
49
|
+
if (Date.now() >= deadline) return undefined
|
|
50
|
+
await new Promise((resolve) => setTimeout(resolve, 200))
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Remove a request that was never picked up.
|
|
56
|
+
* @param id - request id.
|
|
57
|
+
* @param dir - spool directory.
|
|
58
|
+
* @returns true when it was still waiting and is gone now.
|
|
59
|
+
*/
|
|
60
|
+
export async function withdraw(id, dir) {
|
|
61
|
+
try {
|
|
62
|
+
await rm(join(dir, `${id}.json`))
|
|
63
|
+
return true
|
|
64
|
+
} catch {
|
|
65
|
+
return false
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Plugin side: handle spooled requests one at a time.
|
|
71
|
+
* @param options - `{ dir, handle, ready, onError, intervalMs }`: `handle`
|
|
72
|
+
* resolves one request to its result; `ready` says whether requests can be
|
|
73
|
+
* handled now.
|
|
74
|
+
* @returns `{ start, stop, drain }`.
|
|
75
|
+
*/
|
|
76
|
+
export function createSpool({ dir, handle, ready, onError, intervalMs = 1000 }) {
|
|
77
|
+
let timer
|
|
78
|
+
let watcher
|
|
79
|
+
let draining
|
|
80
|
+
let again = false
|
|
81
|
+
let running = false
|
|
82
|
+
|
|
83
|
+
async function recover() {
|
|
84
|
+
for (const name of await readdir(dir).catch(() => [])) {
|
|
85
|
+
if (name.endsWith('.processing')) {
|
|
86
|
+
await rename(join(dir, name), join(dir, name.replace(/\.processing$/u, '.json'))).catch(() => {})
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async function sweep(names) {
|
|
92
|
+
for (const name of names) {
|
|
93
|
+
if (!name.endsWith('.result.json') && !name.endsWith('.tmp')) continue
|
|
94
|
+
const path = join(dir, name)
|
|
95
|
+
const info = await stat(path).catch(() => undefined)
|
|
96
|
+
if (info !== undefined && Date.now() - info.mtimeMs > RESULT_TTL_MS) await rm(path, { force: true })
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async function drainOnce() {
|
|
101
|
+
if (!ready()) return
|
|
102
|
+
const names = (await readdir(dir).catch(() => [])).sort()
|
|
103
|
+
await sweep(names)
|
|
104
|
+
for (const name of names) {
|
|
105
|
+
if (!name.endsWith('.json') || name.endsWith('.result.json')) continue
|
|
106
|
+
if (!ready()) return
|
|
107
|
+
const id = name.slice(0, -'.json'.length)
|
|
108
|
+
const claimed = join(dir, `${id}.processing`)
|
|
109
|
+
try {
|
|
110
|
+
await rename(join(dir, name), claimed)
|
|
111
|
+
} catch {
|
|
112
|
+
continue
|
|
113
|
+
}
|
|
114
|
+
let outcome
|
|
115
|
+
try {
|
|
116
|
+
const request = JSON.parse(await readFile(claimed, 'utf8'))
|
|
117
|
+
outcome = { ok: true, result: await handle(request) }
|
|
118
|
+
} catch (error) {
|
|
119
|
+
outcome = { ok: false, error: typeof error?.message === 'string' ? error.message : String(error) }
|
|
120
|
+
}
|
|
121
|
+
try {
|
|
122
|
+
// The claim goes before the result shows: a stop in between loses
|
|
123
|
+
// only the confirmation, never sends the request twice.
|
|
124
|
+
const pending = join(dir, `${id}.result.tmp`)
|
|
125
|
+
await writeFile(pending, JSON.stringify(outcome) + '\n', { mode: 0o600 })
|
|
126
|
+
await rm(claimed, { force: true })
|
|
127
|
+
await rename(pending, join(dir, `${id}.result.json`))
|
|
128
|
+
} catch (error) {
|
|
129
|
+
onError(error)
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function drain() {
|
|
135
|
+
if (draining !== undefined) {
|
|
136
|
+
again = true
|
|
137
|
+
return draining
|
|
138
|
+
}
|
|
139
|
+
draining = (async () => {
|
|
140
|
+
do {
|
|
141
|
+
again = false
|
|
142
|
+
await drainOnce()
|
|
143
|
+
} while (again)
|
|
144
|
+
})().catch(onError).finally(() => { draining = undefined })
|
|
145
|
+
return draining
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async function start() {
|
|
149
|
+
if (running) return
|
|
150
|
+
running = true
|
|
151
|
+
await mkdir(dir, { recursive: true, mode: 0o700 })
|
|
152
|
+
await recover()
|
|
153
|
+
// Stopped while getting ready.
|
|
154
|
+
if (!running) return
|
|
155
|
+
try {
|
|
156
|
+
watcher = watch(dir, () => { void drain() })
|
|
157
|
+
watcher.on('error', () => {})
|
|
158
|
+
} catch {
|
|
159
|
+
// The interval still picks requests up.
|
|
160
|
+
}
|
|
161
|
+
timer = setInterval(() => { void drain() }, intervalMs)
|
|
162
|
+
timer.unref?.()
|
|
163
|
+
void drain()
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function stop() {
|
|
167
|
+
running = false
|
|
168
|
+
if (timer !== undefined) clearInterval(timer)
|
|
169
|
+
timer = undefined
|
|
170
|
+
watcher?.close()
|
|
171
|
+
watcher = undefined
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
return { start, stop, drain }
|
|
175
|
+
}
|
package/src/subagents.js
ADDED
|
@@ -0,0 +1,540 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Subagent activity in chats.
|
|
3
|
+
*
|
|
4
|
+
* Each chat (a Telegram topic, a Matrix room) has at most one status card listing the subagents its session
|
|
5
|
+
* started (description, model, elapsed time), across turns: a subagent
|
|
6
|
+
* started while the card still shows running ones joins it. The card is
|
|
7
|
+
* edited in place as they start and finish; changes that land close together
|
|
8
|
+
* share one edit, and a running card is refreshed once a minute so its times
|
|
9
|
+
* move. On a network whose message ids grow (Telegram), the card stays the
|
|
10
|
+
* last message of the chat while anything runs: a pin sits at the top, so
|
|
11
|
+
* when any message lands below the card it is sent again, silently, and the
|
|
12
|
+
* old copy deleted (the usual "sticky message" approach of chat bots). A
|
|
13
|
+
* bridge that never reports messages (`noteMessage`) gets a card edited in
|
|
14
|
+
* place. Once every subagent on it is
|
|
15
|
+
* done the card is left where it is as the final state; the next subagent
|
|
16
|
+
* opens a new one. Subagents started by subagents are listed under their
|
|
17
|
+
* parent, in the chat of the session at the top of the chain.
|
|
18
|
+
*
|
|
19
|
+
* `/agents` lists a session's subagents from DSH's durable catalogs, so it
|
|
20
|
+
* also works after a restart.
|
|
21
|
+
*
|
|
22
|
+
* Texts take the bridge's translator `tr(en, ru)`; English is the default.
|
|
23
|
+
*/
|
|
24
|
+
import { messageAnswer } from './answer.js'
|
|
25
|
+
|
|
26
|
+
/** Pause that lets several starts or ends share one edit. */
|
|
27
|
+
const EDIT_DELAY_MS = 1500
|
|
28
|
+
/** How often a board with running subagents is refreshed for its times. */
|
|
29
|
+
const TICK_MS = 60_000
|
|
30
|
+
/** Parent links followed from a subagent up to a bound session. */
|
|
31
|
+
const MAX_DEPTH = 8
|
|
32
|
+
/** Subagents `/agents` lists at most, running ones first. */
|
|
33
|
+
const LIST_LIMIT = 8
|
|
34
|
+
/** Lines a status message shows at most; older finished lines are folded. */
|
|
35
|
+
const MAX_LINES = 25
|
|
36
|
+
/** Longest description shown on a line. */
|
|
37
|
+
const LABEL_MAX = 60
|
|
38
|
+
/** Longest report preview `/agents` shows per subagent. */
|
|
39
|
+
const REPORT_MAX = 240
|
|
40
|
+
|
|
41
|
+
/** @returns the text cut to `max` characters with an ellipsis. */
|
|
42
|
+
function clip(text, max) {
|
|
43
|
+
const value = String(text ?? '')
|
|
44
|
+
return value.length <= max ? value : `${value.slice(0, Math.max(0, max - 1)).trimEnd()}…`
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Format a duration. Running times are shown in whole minutes, so a board
|
|
49
|
+
* refreshed once a minute stays accurate; finished times also show seconds.
|
|
50
|
+
* @param ms - duration in milliseconds.
|
|
51
|
+
* @param precise - include seconds.
|
|
52
|
+
*/
|
|
53
|
+
export function formatElapsed(ms, precise) {
|
|
54
|
+
const seconds = Math.max(0, Math.floor(ms / 1000))
|
|
55
|
+
const minutes = Math.floor(seconds / 60)
|
|
56
|
+
const hours = Math.floor(minutes / 60)
|
|
57
|
+
if (hours > 0) return `${hours}h ${minutes % 60}m`
|
|
58
|
+
if (!precise) return minutes < 1 ? '<1m' : `${minutes}m`
|
|
59
|
+
if (minutes < 1) return `${seconds}s`
|
|
60
|
+
return `${minutes}m ${seconds % 60}s`
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** @returns true when a finished run did not complete normally. */
|
|
64
|
+
function failed(stopReason) {
|
|
65
|
+
return stopReason !== undefined && stopReason !== 'completed'
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** @returns the reason text for a failed run (`max_tokens` → `max tokens`). */
|
|
69
|
+
function reasonText(stopReason) {
|
|
70
|
+
return String(stopReason).replace(/[_-]+/gu, ' ')
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* The status text of one board.
|
|
75
|
+
* @param entries - `{ label, model, depth, startedAt, endedAt, stopReason }` in start order.
|
|
76
|
+
* @param now - current time in ms.
|
|
77
|
+
* @param tr - `(en, ru) => text` for the bot language.
|
|
78
|
+
*/
|
|
79
|
+
export function boardText(entries, now, tr = (en) => en) {
|
|
80
|
+
const running = entries.filter((entry) => entry.endedAt === undefined).length
|
|
81
|
+
const failures = entries.filter((entry) => entry.endedAt !== undefined && failed(entry.stopReason)).length
|
|
82
|
+
const total = entries.length
|
|
83
|
+
const noun = tr(total === 1 ? 'subagent' : 'subagents', 'субагент(ов)')
|
|
84
|
+
let head
|
|
85
|
+
if (running > 0) head = `🤖 ${total} ${noun} · ${running} ${tr('running', 'работают')}`
|
|
86
|
+
else if (failures > 0) head = `🤖 ${total} ${noun} · ${tr('done', 'готово')}, ${failures} ${tr('failed', 'с ошибкой')}`
|
|
87
|
+
else head = `🤖 ${total} ${noun} · ${tr('all done', 'все готовы')}`
|
|
88
|
+
const lines = entries.map((entry) => {
|
|
89
|
+
const indent = entry.depth > 1 ? `${' '.repeat(entry.depth - 2)}↳ ` : ''
|
|
90
|
+
const parts = [clip(entry.label, LABEL_MAX)]
|
|
91
|
+
if (entry.model) parts.push(entry.model)
|
|
92
|
+
if (entry.endedAt === undefined) {
|
|
93
|
+
parts.push(formatElapsed(now - entry.startedAt, false))
|
|
94
|
+
return `${indent}⏳ ${parts.join(' · ')}`
|
|
95
|
+
}
|
|
96
|
+
parts.push(formatElapsed(entry.endedAt - entry.startedAt, true))
|
|
97
|
+
if (failed(entry.stopReason)) parts.push(reasonText(entry.stopReason))
|
|
98
|
+
return `${indent}${failed(entry.stopReason) ? '✗' : '✓'} ${parts.join(' · ')}`
|
|
99
|
+
})
|
|
100
|
+
if (lines.length > MAX_LINES) {
|
|
101
|
+
// Keep running lines and the newest ones; fold the oldest finished lines.
|
|
102
|
+
const keep = new Set()
|
|
103
|
+
entries.forEach((entry, index) => { if (entry.endedAt === undefined) keep.add(index) })
|
|
104
|
+
for (let index = entries.length - 1; index >= 0 && keep.size < MAX_LINES - 1; index -= 1) keep.add(index)
|
|
105
|
+
const folded = lines.length - keep.size
|
|
106
|
+
const shown = lines.filter((_line, index) => keep.has(index))
|
|
107
|
+
return [head, `… ${folded} ${tr('earlier finished', 'завершённых ранее')}`, ...shown].join('\n')
|
|
108
|
+
}
|
|
109
|
+
return [head, ...lines].join('\n')
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** @returns whether a tool name is the subagent reporting tool (`send_message`, maybe prefixed). */
|
|
113
|
+
function isReportTool(name) {
|
|
114
|
+
return typeof name === 'string' && (name === 'send_message' || name.endsWith('__send_message'))
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** @returns the `message` argument of a tool call, or ''. */
|
|
118
|
+
function reportArgument(block) {
|
|
119
|
+
let args = block?.arguments ?? block?.input
|
|
120
|
+
if (typeof args === 'string') {
|
|
121
|
+
try {
|
|
122
|
+
args = JSON.parse(args)
|
|
123
|
+
} catch {
|
|
124
|
+
return ''
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return typeof args?.message === 'string' ? args.message.trim() : ''
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* The latest report a subagent left: a message it sent its parent, or the
|
|
132
|
+
* answer of its last tool-free message, whichever is newer.
|
|
133
|
+
* @param events - the child's session events (`{ type, data }`).
|
|
134
|
+
* @returns the report text, or ''.
|
|
135
|
+
*/
|
|
136
|
+
export function reportOf(events) {
|
|
137
|
+
if (!Array.isArray(events)) return ''
|
|
138
|
+
for (let index = events.length - 1; index >= 0; index -= 1) {
|
|
139
|
+
const event = events[index]
|
|
140
|
+
if (event?.type !== 'assistant/message') continue
|
|
141
|
+
const message = event.data?.message ?? event.data
|
|
142
|
+
const content = Array.isArray(message?.content) ? message.content : []
|
|
143
|
+
for (let block = content.length - 1; block >= 0; block -= 1) {
|
|
144
|
+
const item = content[block]
|
|
145
|
+
if (item?.type === 'tool-call' && isReportTool(item.name)) {
|
|
146
|
+
const text = reportArgument(item)
|
|
147
|
+
if (text.length > 0) return text
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
const answer = messageAnswer(message)
|
|
151
|
+
if (answer.length > 0) return answer
|
|
152
|
+
}
|
|
153
|
+
return ''
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* State of one listed subagent, from its live agent and durable timing.
|
|
158
|
+
* @param facts - `{ status, timing }`: live agent status (or undefined when not loaded) and the `subagentTiming` view.
|
|
159
|
+
* @param now - current time in ms.
|
|
160
|
+
* @returns `{ state, elapsedMs }`; state is running, done, failed, interrupted or idle.
|
|
161
|
+
*/
|
|
162
|
+
export function childState({ status, timing }, now) {
|
|
163
|
+
const settled = Number.isFinite(timing?.settledMs) ? timing.settledMs : 0
|
|
164
|
+
const active = timing?.active
|
|
165
|
+
if (status === 'running') {
|
|
166
|
+
return { state: 'running', elapsedMs: active === undefined ? settled : settled + Math.max(0, now - active.since) }
|
|
167
|
+
}
|
|
168
|
+
if (active !== undefined) {
|
|
169
|
+
// A turn left open with no live agent was cut off, usually by a restart.
|
|
170
|
+
return { state: status === undefined ? 'interrupted' : 'running', elapsedMs: settled + Math.max(0, (status === undefined ? active.through : now) - active.since) }
|
|
171
|
+
}
|
|
172
|
+
if (timing?.lastTurnCompleted === false) return { state: 'failed', elapsedMs: settled }
|
|
173
|
+
if (timing?.lastTurnCompleted === true) return { state: 'done', elapsedMs: settled }
|
|
174
|
+
return { state: 'idle', elapsedMs: settled }
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** @returns relative age such as `5m ago`. */
|
|
178
|
+
function ageText(createdAt, now, tr = (en) => en) {
|
|
179
|
+
if (!Number.isFinite(createdAt)) return ''
|
|
180
|
+
const minutes = Math.max(0, Math.floor((now - createdAt) / 60_000))
|
|
181
|
+
if (minutes < 1) return tr('just now', 'только что')
|
|
182
|
+
if (minutes < 60) return tr(`${minutes}m ago`, `${minutes} мин назад`)
|
|
183
|
+
const hours = Math.floor(minutes / 60)
|
|
184
|
+
if (hours < 48) return tr(`${hours}h ago`, `${hours} ч назад`)
|
|
185
|
+
return tr(`${Math.floor(hours / 24)}d ago`, `${Math.floor(hours / 24)} дн назад`)
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const STATE_ICONS = { running: '⏳', done: '✓', failed: '✗', interrupted: '⚠️', idle: '•' }
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* The `/agents` reply.
|
|
192
|
+
* @param rows - `{ label, model, depth, state, elapsedMs, createdAt, report }`, newest first.
|
|
193
|
+
* @param total - how many subagents the session has in all.
|
|
194
|
+
* @param now - current time in ms.
|
|
195
|
+
* @param tr - `(en, ru) => text`.
|
|
196
|
+
*/
|
|
197
|
+
export function agentsListText(rows, total, now, tr = (en) => en) {
|
|
198
|
+
if (rows.length === 0) return tr('This session has started no subagents.', 'Эта сессия не запускала субагентов.')
|
|
199
|
+
const head = total > rows.length
|
|
200
|
+
? tr(`🤖 Subagents (latest ${rows.length} of ${total}):`, `🤖 Субагенты (последние ${rows.length} из ${total}):`)
|
|
201
|
+
: tr('🤖 Subagents:', '🤖 Субагенты:')
|
|
202
|
+
const states = {
|
|
203
|
+
running: tr('running', 'работает'),
|
|
204
|
+
done: tr('done', 'готово'),
|
|
205
|
+
failed: tr('failed', 'ошибка'),
|
|
206
|
+
interrupted: tr('interrupted', 'прерван'),
|
|
207
|
+
idle: tr('idle', 'ожидает'),
|
|
208
|
+
}
|
|
209
|
+
const blocks = rows.map((row) => {
|
|
210
|
+
const indent = row.depth > 1 ? '↳ ' : ''
|
|
211
|
+
const facts = [states[row.state] ?? row.state]
|
|
212
|
+
if (row.model) facts.push(row.model)
|
|
213
|
+
if (row.elapsedMs > 0 || row.state === 'running') facts.push(formatElapsed(row.elapsedMs, row.state !== 'running'))
|
|
214
|
+
const age = ageText(row.createdAt, now, tr)
|
|
215
|
+
if (age) facts.push(age)
|
|
216
|
+
const lines = [`${indent}${STATE_ICONS[row.state] ?? '•'} ${clip(row.label, LABEL_MAX)}`, ` ${facts.join(' · ')}`]
|
|
217
|
+
const report = clip(String(row.report ?? '').replace(/\s+/gu, ' ').trim(), REPORT_MAX)
|
|
218
|
+
if (report) lines.push(` “${report}”`)
|
|
219
|
+
return lines.join('\n')
|
|
220
|
+
})
|
|
221
|
+
return [head, '', blocks.join('\n\n')].join('\n')
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Track subagent runs and keep one status card per chat.
|
|
226
|
+
* @param deps - Host and Telegram access:
|
|
227
|
+
* - `parentOf(sessionId)`: the parent session id of a live session, or undefined.
|
|
228
|
+
* - `topicOf(sessionId)`: the chat (`{ key }`) a session is bound to, or undefined.
|
|
229
|
+
* - `showsTurn(topic)`: whether the chat is showing a turn now; a new card opens only then.
|
|
230
|
+
* - `labelOf(parentId, childId)`: the child's description from its parent's catalog.
|
|
231
|
+
* - `modelOf(childId)`: the child's model id.
|
|
232
|
+
* - `post(topic, text)`: send a message silently, resolves to its id or undefined.
|
|
233
|
+
* - `edit(topic, messageId, text)`: resolves to `ok`, `gone` (send a new one) or `failed` (try later).
|
|
234
|
+
* - `remove(topic, messageId)`: delete a message.
|
|
235
|
+
* - `reportError(scope, error)`, `tr(en, ru)`, `now()`, `delayMs`, `tickMs`.
|
|
236
|
+
* @returns `{ onStart, onEnd, noteMessage, dispose, boards }`; a bridge whose message ids grow
|
|
237
|
+
* calls `noteMessage(topicKey, messageId)` for every message that lands in a chat, so the card
|
|
238
|
+
* can follow it down.
|
|
239
|
+
*/
|
|
240
|
+
export function createAgentBoards(deps) {
|
|
241
|
+
const {
|
|
242
|
+
parentOf, topicOf, showsTurn, labelOf, modelOf, post, edit, remove, reportError,
|
|
243
|
+
tr = (en) => en, now = Date.now, delayMs = EDIT_DELAY_MS, tickMs = TICK_MS,
|
|
244
|
+
} = deps
|
|
245
|
+
/** The open card of each topic, by topic key. */
|
|
246
|
+
const open = new Map()
|
|
247
|
+
let disposed = false
|
|
248
|
+
|
|
249
|
+
function closeBoard(board) {
|
|
250
|
+
if (open.get(board.topic.key) === board) open.delete(board.topic.key)
|
|
251
|
+
if (board.tick !== undefined) clearInterval(board.tick)
|
|
252
|
+
board.tick = undefined
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** Publish soon; changes before the timer fires share the edit. */
|
|
256
|
+
function schedule(board) {
|
|
257
|
+
if (disposed || board.timer !== undefined) return
|
|
258
|
+
board.timer = setTimeout(() => {
|
|
259
|
+
board.timer = undefined
|
|
260
|
+
board.chain = board.chain
|
|
261
|
+
.then(() => publish(board))
|
|
262
|
+
.catch((error) => reportError('subagent status', error))
|
|
263
|
+
}, delayMs)
|
|
264
|
+
board.timer.unref?.()
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
async function fillLabels(board) {
|
|
268
|
+
await Promise.all([...board.entries.values()].filter((entry) => !entry.labelKnown).map(async (entry) => {
|
|
269
|
+
const label = await Promise.resolve(labelOf(entry.parentId, entry.id)).catch(() => undefined)
|
|
270
|
+
if (typeof label === 'string' && label.trim()) {
|
|
271
|
+
entry.label = label.trim()
|
|
272
|
+
entry.labelKnown = true
|
|
273
|
+
}
|
|
274
|
+
}))
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** Entries in start order, each nested subagent right under its parent. */
|
|
278
|
+
function displayOrder(board) {
|
|
279
|
+
const entries = [...board.entries.values()]
|
|
280
|
+
const ids = new Set(entries.map((entry) => entry.id))
|
|
281
|
+
const children = new Map()
|
|
282
|
+
for (const entry of entries) {
|
|
283
|
+
const parent = ids.has(entry.parentId) ? entry.parentId : undefined
|
|
284
|
+
if (!children.has(parent)) children.set(parent, [])
|
|
285
|
+
children.get(parent).push(entry)
|
|
286
|
+
}
|
|
287
|
+
const ordered = []
|
|
288
|
+
const seen = new Set()
|
|
289
|
+
const walk = (parent) => {
|
|
290
|
+
for (const entry of children.get(parent) ?? []) {
|
|
291
|
+
if (seen.has(entry)) continue
|
|
292
|
+
seen.add(entry)
|
|
293
|
+
ordered.push(entry)
|
|
294
|
+
walk(entry.id)
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
walk(undefined)
|
|
298
|
+
// A cycle cannot come from DSH's parent links; keep any entry it would hide.
|
|
299
|
+
for (const entry of entries) if (!seen.has(entry)) ordered.push(entry)
|
|
300
|
+
return ordered
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** Whether a message landed in the topic after the card. */
|
|
304
|
+
function buried(board) {
|
|
305
|
+
return board.messageId !== undefined && board.latestSeen > board.messageId
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
async function publish(board) {
|
|
309
|
+
if (disposed) return
|
|
310
|
+
await fillLabels(board)
|
|
311
|
+
const entries = displayOrder(board)
|
|
312
|
+
const done = entries.every((entry) => entry.endedAt !== undefined)
|
|
313
|
+
// Freeze before any wait, so a subagent starting meanwhile opens a new card.
|
|
314
|
+
if (done) closeBoard(board)
|
|
315
|
+
const text = boardText(entries, now(), tr)
|
|
316
|
+
// A finished card stays where it is as the final state.
|
|
317
|
+
if (!done && buried(board)) {
|
|
318
|
+
await repost(board, text)
|
|
319
|
+
return
|
|
320
|
+
}
|
|
321
|
+
if (text === board.lastText) return
|
|
322
|
+
if (board.messageId !== undefined) {
|
|
323
|
+
const outcome = await edit(board.topic, board.messageId, text)
|
|
324
|
+
if (outcome === 'ok') {
|
|
325
|
+
board.lastText = text
|
|
326
|
+
return
|
|
327
|
+
}
|
|
328
|
+
if (outcome !== 'gone') {
|
|
329
|
+
// A running card retries with its next change or tick; a finished
|
|
330
|
+
// one has neither, so it tries once more after a pause.
|
|
331
|
+
if (done) {
|
|
332
|
+
await new Promise((resolve) => { setTimeout(resolve, delayMs * 4).unref?.() })
|
|
333
|
+
if (!disposed && (await edit(board.topic, board.messageId, text)) === 'ok') board.lastText = text
|
|
334
|
+
}
|
|
335
|
+
return
|
|
336
|
+
}
|
|
337
|
+
board.messageId = undefined
|
|
338
|
+
}
|
|
339
|
+
await repost(board, text)
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/** Send the card as the newest message, then delete the copy above. */
|
|
343
|
+
async function repost(board, text) {
|
|
344
|
+
const previous = board.messageId
|
|
345
|
+
const messageId = await post(board.topic, text)
|
|
346
|
+
if (messageId === undefined) return
|
|
347
|
+
board.messageId = messageId
|
|
348
|
+
board.lastText = text
|
|
349
|
+
board.latestSeen = Math.max(board.latestSeen, messageId)
|
|
350
|
+
if (previous !== undefined) await Promise.resolve(remove(board.topic, previous)).catch(() => {})
|
|
351
|
+
// Something landed while the card was being sent: follow it down.
|
|
352
|
+
if (buried(board) && open.get(board.topic.key) === board) schedule(board)
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/**
|
|
356
|
+
* A subagent run started (`subagent/start`).
|
|
357
|
+
* @param info - `{ runId, id }`.
|
|
358
|
+
*/
|
|
359
|
+
async function onStart(info) {
|
|
360
|
+
if (disposed || typeof info?.id !== 'string') return
|
|
361
|
+
const parentId = parentOf(info.id)
|
|
362
|
+
let topic
|
|
363
|
+
let depth = 1
|
|
364
|
+
let current = parentId
|
|
365
|
+
for (let hop = 0; hop < MAX_DEPTH && typeof current === 'string'; hop += 1) {
|
|
366
|
+
topic = topicOf(current)
|
|
367
|
+
if (topic !== undefined) break
|
|
368
|
+
depth += 1
|
|
369
|
+
current = parentOf(current)
|
|
370
|
+
}
|
|
371
|
+
if (topic === undefined) return
|
|
372
|
+
let board = open.get(topic.key)
|
|
373
|
+
if (board === undefined) {
|
|
374
|
+
// A nested subagent belongs to a chain the topic already shows; a
|
|
375
|
+
// top-level one opens a card only while the topic shows a turn.
|
|
376
|
+
if (depth === 1 && !showsTurn(topic)) return
|
|
377
|
+
board = { topic, entries: new Map(), messageId: undefined, lastText: undefined, latestSeen: 0, timer: undefined, tick: undefined, chain: Promise.resolve() }
|
|
378
|
+
open.set(topic.key, board)
|
|
379
|
+
board.tick = setInterval(() => schedule(board), tickMs)
|
|
380
|
+
board.tick.unref?.()
|
|
381
|
+
}
|
|
382
|
+
const entry = {
|
|
383
|
+
id: info.id,
|
|
384
|
+
parentId,
|
|
385
|
+
label: tr(`subagent ${info.id.slice(0, 8)}`, `субагент ${info.id.slice(0, 8)}`),
|
|
386
|
+
labelKnown: false,
|
|
387
|
+
model: '',
|
|
388
|
+
depth,
|
|
389
|
+
startedAt: now(),
|
|
390
|
+
endedAt: undefined,
|
|
391
|
+
stopReason: undefined,
|
|
392
|
+
}
|
|
393
|
+
board.entries.set(info.runId ?? info.id, entry)
|
|
394
|
+
schedule(board)
|
|
395
|
+
const model = await Promise.resolve(modelOf(info.id)).catch(() => undefined)
|
|
396
|
+
if (typeof model === 'string' && model.length > 0) entry.model = model
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* A subagent run ended (`subagent/end`).
|
|
401
|
+
* @param info - `{ runId, id, stopReason }`.
|
|
402
|
+
*/
|
|
403
|
+
function onEnd(info) {
|
|
404
|
+
const key = info?.runId ?? info?.id
|
|
405
|
+
for (const board of open.values()) {
|
|
406
|
+
const entry = board.entries.get(key)
|
|
407
|
+
if (entry === undefined || entry.endedAt !== undefined) continue
|
|
408
|
+
entry.endedAt = now()
|
|
409
|
+
entry.stopReason = info.stopReason
|
|
410
|
+
schedule(board)
|
|
411
|
+
return
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/**
|
|
416
|
+
* A message landed in a topic (sent by anyone, the bot included).
|
|
417
|
+
* @param topicKey - the topic's key.
|
|
418
|
+
* @param messageId - the Telegram message id; ids grow within a chat.
|
|
419
|
+
*/
|
|
420
|
+
function noteMessage(topicKey, messageId) {
|
|
421
|
+
const board = open.get(topicKey)
|
|
422
|
+
if (board === undefined || !Number.isSafeInteger(messageId)) return
|
|
423
|
+
board.latestSeen = Math.max(board.latestSeen, messageId)
|
|
424
|
+
if (buried(board)) schedule(board)
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
function dispose() {
|
|
428
|
+
disposed = true
|
|
429
|
+
for (const board of open.values()) {
|
|
430
|
+
if (board.timer !== undefined) clearTimeout(board.timer)
|
|
431
|
+
if (board.tick !== undefined) clearInterval(board.tick)
|
|
432
|
+
}
|
|
433
|
+
open.clear()
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
return { onStart, onEnd, noteMessage, dispose, boards: open }
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/**
|
|
440
|
+
* Collect a session's subagents for `/agents`: every descendant reachable
|
|
441
|
+
* through the catalogs of recent children, newest first, running ones kept.
|
|
442
|
+
* @param listChildren - `(sessionId) => Promise<[{ id, label, createdAt, mode }]>`.
|
|
443
|
+
* @param rootId - the topic's session.
|
|
444
|
+
* @param isRunning - `(id) => boolean` for live, working subagents.
|
|
445
|
+
* @param limit - rows to return.
|
|
446
|
+
* @returns `{ rows: [{ id, label, createdAt, depth }], total }`.
|
|
447
|
+
*/
|
|
448
|
+
export async function collectSubagents(listChildren, rootId, isRunning, limit = LIST_LIMIT) {
|
|
449
|
+
const found = []
|
|
450
|
+
const seen = new Set([rootId])
|
|
451
|
+
/** Catalog reads are bounded: descendants of old children are old too. */
|
|
452
|
+
let budget = limit * 4
|
|
453
|
+
const walk = async (parentId, depth) => {
|
|
454
|
+
let children
|
|
455
|
+
try {
|
|
456
|
+
children = await listChildren(parentId)
|
|
457
|
+
} catch {
|
|
458
|
+
return
|
|
459
|
+
}
|
|
460
|
+
if (!Array.isArray(children)) return
|
|
461
|
+
const recent = [...children].sort((left, right) => (right.createdAt ?? 0) - (left.createdAt ?? 0))
|
|
462
|
+
for (const child of recent) {
|
|
463
|
+
if (seen.has(child.id)) continue
|
|
464
|
+
seen.add(child.id)
|
|
465
|
+
found.push({ id: child.id, label: child.label, createdAt: child.createdAt, depth })
|
|
466
|
+
}
|
|
467
|
+
for (const child of recent) {
|
|
468
|
+
if (child.mode === 'external' || depth >= MAX_DEPTH) continue
|
|
469
|
+
if (budget <= 0 && !isRunning(child.id)) continue
|
|
470
|
+
budget -= 1
|
|
471
|
+
await walk(child.id, depth + 1)
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
await walk(rootId, 1)
|
|
475
|
+
found.sort((left, right) => (right.createdAt ?? 0) - (left.createdAt ?? 0))
|
|
476
|
+
const running = found.filter((row) => isRunning(row.id))
|
|
477
|
+
const rows = [...running, ...found.filter((row) => !isRunning(row.id)).slice(0, Math.max(0, limit - running.length))]
|
|
478
|
+
rows.sort((left, right) => (right.createdAt ?? 0) - (left.createdAt ?? 0))
|
|
479
|
+
return { rows, total: found.length }
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/**
|
|
483
|
+
* The description a parent gave one of its subagents, from its catalog.
|
|
484
|
+
* @param ctx - Host context.
|
|
485
|
+
* @param parentId - parent session.
|
|
486
|
+
* @param childId - subagent session.
|
|
487
|
+
* @returns the label, or undefined.
|
|
488
|
+
*/
|
|
489
|
+
export async function subagentLabel(ctx, parentId, childId) {
|
|
490
|
+
if (typeof parentId !== 'string') return undefined
|
|
491
|
+
const children = await ctx.get('subagents')?.listChildren(parentId).catch(() => undefined)
|
|
492
|
+
const label = Array.isArray(children) ? children.find((child) => child.id === childId)?.label : undefined
|
|
493
|
+
return typeof label === 'string' && label.trim().length > 0 ? label.trim() : undefined
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/**
|
|
497
|
+
* The `/agents` text for a session: its running and latest subagents with
|
|
498
|
+
* their state and the start of their last report. Read from DSH's durable
|
|
499
|
+
* catalogs and session logs, so it works for subagents of earlier runs.
|
|
500
|
+
* @param ctx - Host context.
|
|
501
|
+
* @param sessionId - the chat's session.
|
|
502
|
+
* @param tr - `(en, ru) => text`.
|
|
503
|
+
* @returns the reply text, or undefined when this DSH has no subagent service.
|
|
504
|
+
*/
|
|
505
|
+
export async function subagentsText(ctx, sessionId, tr = (en) => en) {
|
|
506
|
+
const subagents = ctx.get('subagents')
|
|
507
|
+
if (typeof subagents?.listChildren !== 'function') return undefined
|
|
508
|
+
const agents = ctx.get('agents')
|
|
509
|
+
const isRunning = (id) => agents?.get(id)?.status === 'running'
|
|
510
|
+
const { rows, total } = await collectSubagents((id) => subagents.listChildren(id), sessionId, isRunning)
|
|
511
|
+
const now = Date.now()
|
|
512
|
+
const query = ctx.get('sessionQuery')
|
|
513
|
+
const detailed = await Promise.all(rows.map(async (row) => {
|
|
514
|
+
let timing
|
|
515
|
+
let model
|
|
516
|
+
let observation
|
|
517
|
+
try {
|
|
518
|
+
observation = await query?.observeSession(row.id)
|
|
519
|
+
const values = observation?.projections?.values
|
|
520
|
+
timing = values?.subagentTiming
|
|
521
|
+
const selection = values?.modelSelection
|
|
522
|
+
model = (selection?.next ?? selection?.pending ?? selection?.lastUsed)?.model
|
|
523
|
+
} catch {
|
|
524
|
+
// State falls back to what the live agent says.
|
|
525
|
+
} finally {
|
|
526
|
+
observation?.[Symbol.dispose]?.()
|
|
527
|
+
}
|
|
528
|
+
const live = agents?.get(row.id)
|
|
529
|
+
if (typeof live?.model?.current === 'function') model = live.model.current()?.model ?? model
|
|
530
|
+
let events = []
|
|
531
|
+
try {
|
|
532
|
+
events = (await query?.readSurface(row.id))?.events ?? []
|
|
533
|
+
} catch {
|
|
534
|
+
// No report preview.
|
|
535
|
+
}
|
|
536
|
+
const { state, elapsedMs } = childState({ status: live?.status, timing }, now)
|
|
537
|
+
return { ...row, label: (typeof row.label === 'string' ? row.label.trim() : '') || `subagent ${String(row.id).slice(0, 8)}`, model, state, elapsedMs, report: reportOf(events) }
|
|
538
|
+
}))
|
|
539
|
+
return agentsListText(detailed, total, now, tr)
|
|
540
|
+
}
|
package/testing.js
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fakes of DSH behaviour for bridge tests, imported as
|
|
3
|
+
* `@soffits/dsh-channel-core/testing`: how a queued message passes the
|
|
4
|
+
* `agent/pre-step` gate, the `sessionTitle` service, and `agent.model` folded
|
|
5
|
+
* from the session log. A bridge builds its own fake Host and agents around
|
|
6
|
+
* them, so every bridge's tests model DSH the same way.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/** @returns a fake session's events, from `snapshotEvents()` or an `events` array. */
|
|
10
|
+
function eventsOf(session) {
|
|
11
|
+
if (typeof session.snapshotEvents === 'function') return session.snapshotEvents()
|
|
12
|
+
return Array.isArray(session.events) ? session.events : []
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Model how DSH starts a turn for a queued message: every follow-up opens a
|
|
17
|
+
* turn (so the session is no longer blank), and `agent/pre-step` handlers may
|
|
18
|
+
* reject it before any model request, in which case the message is never
|
|
19
|
+
* recorded. Messages a handler adds with another source kind (notices) go
|
|
20
|
+
* to `agent.notices`; `received` holds the prompts as recorded.
|
|
21
|
+
* @param agent - fake agent with `received`; gets `turns` and `rejected`.
|
|
22
|
+
* @param message - the queued user message.
|
|
23
|
+
* @param handlers - the `agent/pre-step` handlers registered now, the
|
|
24
|
+
* agent's own first, then host-wide ones.
|
|
25
|
+
*/
|
|
26
|
+
export function followupThroughGate(agent, message, handlers) {
|
|
27
|
+
agent.turns = (agent.turns ?? 0) + 1
|
|
28
|
+
agent.received.push(message)
|
|
29
|
+
const run = (index) => index < handlers.length
|
|
30
|
+
? Promise.resolve(handlers[index]({ agent, messages: [message] }, () => run(index + 1)))
|
|
31
|
+
: Promise.resolve({ kind: 'enter', messages: [message] })
|
|
32
|
+
void run(0).then((decision) => {
|
|
33
|
+
const at = agent.received.indexOf(message)
|
|
34
|
+
if (at === -1) return
|
|
35
|
+
if (decision?.kind === 'reject') {
|
|
36
|
+
agent.received.splice(at, 1)
|
|
37
|
+
agent.rejected ??= []
|
|
38
|
+
agent.rejected.push(message)
|
|
39
|
+
} else if (Array.isArray(decision?.messages)) {
|
|
40
|
+
// What DSH records: the step's messages as the handlers left them;
|
|
41
|
+
// producer notices (source kinds other than user) are kept apart.
|
|
42
|
+
agent.received.splice(at, 1, ...decision.messages.filter((item) => item.source?.kind === 'user'))
|
|
43
|
+
agent.notices ??= []
|
|
44
|
+
agent.notices.push(...decision.messages.filter((item) => item.source?.kind !== 'user'))
|
|
45
|
+
}
|
|
46
|
+
})
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Fake `sessionTitle` service. A title is the latest `session/title` event
|
|
51
|
+
* of the session, else the fields a test put on the session object (`title`,
|
|
52
|
+
* `titleSource`, `titleSeqs`, a title kept from an earlier run). Titles are
|
|
53
|
+
* written through `session.append('session/title', ...)` when the fake
|
|
54
|
+
* session has one, so listeners see the event as in DSH. `refresh` stands in
|
|
55
|
+
* for the title model: it writes `session.nextGeneratedTitle`, or a fixed one.
|
|
56
|
+
* @returns the service.
|
|
57
|
+
*/
|
|
58
|
+
export function makeTitleService() {
|
|
59
|
+
const write = (session, data) => {
|
|
60
|
+
if (typeof session.append === 'function') session.append('session/title', data)
|
|
61
|
+
else Object.assign(session, { title: data.title, titleSource: data.source, titleSeqs: data.messageSeqs })
|
|
62
|
+
}
|
|
63
|
+
const service = {
|
|
64
|
+
refreshed: [],
|
|
65
|
+
// DSH's private provider slot; set to undefined to run without a provider.
|
|
66
|
+
registration: { provider: { id: 'fake' }, closing: false },
|
|
67
|
+
get: (session) => {
|
|
68
|
+
const event = eventsOf(session).filter((item) => item.type === 'session/title').at(-1)
|
|
69
|
+
if (event !== undefined) return { title: event.data.title, source: event.data.source ?? { kind: 'user' }, messageSeqs: event.data.messageSeqs ?? [] }
|
|
70
|
+
return typeof session.title === 'string'
|
|
71
|
+
? { title: session.title, source: session.titleSource ?? { kind: 'user' }, messageSeqs: session.titleSeqs ?? [] }
|
|
72
|
+
: undefined
|
|
73
|
+
},
|
|
74
|
+
rename: (session, title) => {
|
|
75
|
+
write(session, { title, messageSeqs: [], source: { kind: 'user' } })
|
|
76
|
+
return service.get(session)
|
|
77
|
+
},
|
|
78
|
+
async refresh(session) {
|
|
79
|
+
service.refreshed.push(session.id)
|
|
80
|
+
if (service.registration === undefined) {
|
|
81
|
+
// DSH's built-in fallback: the first words of the first human message, over any title.
|
|
82
|
+
const first = eventsOf(session).find((event) => event.type === 'user/message' && event.data?.source?.kind === 'user')
|
|
83
|
+
const text = (first?.data.content ?? []).filter((block) => block.type === 'text').map((block) => block.text).join('\n')
|
|
84
|
+
write(session, { title: text.split(/\s+/u).filter(Boolean).slice(0, 5).join(' '), messageSeqs: [first?.seq ?? 1], source: { kind: 'fallback' } })
|
|
85
|
+
return service.get(session)
|
|
86
|
+
}
|
|
87
|
+
write(session, { title: session.nextGeneratedTitle ?? 'Generated task', messageSeqs: [1], source: { kind: 'provider', provider: 'fake' } })
|
|
88
|
+
return service.get(session)
|
|
89
|
+
},
|
|
90
|
+
}
|
|
91
|
+
return service
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Fake `agent.model`, folding the session log the way DSH's modelSelection
|
|
96
|
+
* projection does: a `model/selection` event is the pending choice, a
|
|
97
|
+
* `request/header` is the last route used and retires a matching pending
|
|
98
|
+
* choice; with neither, the agent's options apply.
|
|
99
|
+
* @param session - fake session with `append` and `snapshotEvents()` or `events`.
|
|
100
|
+
* @param options - agent options (`provider`, `model`, `reasoningEffort`), may be getters.
|
|
101
|
+
* @returns the model handle.
|
|
102
|
+
*/
|
|
103
|
+
export function makeAgentModel(session, options = {}) {
|
|
104
|
+
const same = (left, right) => left !== null && right !== null
|
|
105
|
+
&& left.provider === right.provider && left.model === right.model && left.reasoningEffort === right.reasoningEffort
|
|
106
|
+
const recorded = () => {
|
|
107
|
+
let lastUsed = null
|
|
108
|
+
let pending = null
|
|
109
|
+
for (const event of eventsOf(session)) {
|
|
110
|
+
if (event.type === 'model/selection') pending = { ...event.data }
|
|
111
|
+
if (event.type === 'request/header') {
|
|
112
|
+
const { provider, model, reasoningEffort } = event.data.header.config
|
|
113
|
+
lastUsed = { provider, model, ...(reasoningEffort === undefined ? {} : { reasoningEffort }) }
|
|
114
|
+
if (same(pending, lastUsed)) pending = null
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return pending ?? lastUsed
|
|
118
|
+
}
|
|
119
|
+
return {
|
|
120
|
+
current() {
|
|
121
|
+
const found = recorded()
|
|
122
|
+
if (found !== null) return { ...found }
|
|
123
|
+
const { provider, model, reasoningEffort } = options
|
|
124
|
+
return provider && model ? { provider, model, ...(reasoningEffort === undefined ? {} : { reasoningEffort }) } : undefined
|
|
125
|
+
},
|
|
126
|
+
select(selection) {
|
|
127
|
+
const next = { provider: selection.provider, model: selection.model, ...(selection.reasoningEffort === undefined ? {} : { reasoningEffort: selection.reasoningEffort }) }
|
|
128
|
+
if (same(recorded(), next)) return
|
|
129
|
+
session.append('model/selection', next)
|
|
130
|
+
},
|
|
131
|
+
}
|
|
132
|
+
}
|