Skip to content

Commit 2723927

Browse files
authored
refactor(agent): unify run context and add integration harness (#1009)
* refactor(agent): unify run context and add integration harness - Make AgentRunContext the canonical per-run context threaded through main and sub-agent executions; attach parent request ids for tracing - Thread requestId/conversationId consistently into agent, chain, and computer tool calls - Add maxTokenLimit handling and detect token-limit finish reasons in shared adapter error mapping - Add deterministic integration harness and agent eval bench scripts, replace the previous mocha test suite - Add file-changes tracking for computer tools * refactor(agent): drop eval harness and simplify stream/sandbox - Remove bench/ and integration/ from version control, keep them locally - Revert integration/bench scripts and their devDependencies in package.json - Simplify readSSE abort handling: cancel reader and throw signal reason - sseIterable takes a params object instead of positional timeout/signal - Split local sandbox builder into sandbox_darwin.ts / sandbox_linux.ts - Restore caller-first toolMask priority * fix(agent): address code review findings - Cover HTTP connect phase with request timeout in deepseek/dify/gemini/qwen stream requesters via createRequestSignal - Forward maxTokenLimit and caller source through the plain chat chain - Guard LocalComputerSession methods against disconnected state; clear FileStore on disconnect; mkdir session tmp with 0o700 - Reject empty tmp in wrapCommandWithSandbox and empty oldString in replaceFileContent - Cache FileStore.scope realpath in constructor instead of per-access realpathSync - Clean up expired chatluna-agent-* session temp dirs by mtime - Isolate bwrap sandbox with --unshare-pid/--unshare-ipc/--new-session - Support AbortSignal in open-terminal and e2b execute (kill remote command on abort) * fix(adapter): honor explicit timeouts instead of capping at 60s - Remove the 60s clamp on stream request timeouts everywhere (shared-adapter, deepseek, dify, gemini, qwen, sseIterable): an explicit params.timeout is now used as-is; the 60s default already comes from the model/reranker layer when no timeout is set - Align dify _agentStream/_workflowStream error handling with the other adapters: rethrow signal reason on abort, keep ChatLunaError as-is, wrap the rest in API_REQUEST_FAILED, dispose signal in finally * fix(sse): pass signal into ollama sse reader, reset idle timer on any chunk - Ollama requester now forwards params.signal to rawSeeAsIterable so the stream read phase preserves the abort reason after the response is established - sseIterable resets the idle timeout on every raw chunk instead of only on non-comment events, so keepalive comments (e.g. ': ping') keep long-lived streams alive * fix(search): build AgentRunContext in browsing chain tool configs ChatLunaToolRunnable.configurable now requires agentContext; browsing_chain constructed its tool run configs with the old { model, session, conversationId } shape. Add a shared buildRunConfig helper that builds a main-kind AgentRunContext and use it for both web_search invoke and browser readText calls. * fix(search): thread abort signal and per-call context in browsing chain - Pass the AbortSignal into buildRunConfig so tool.invoke and readText receive cancellation through runConfig.signal instead of only racing it - Use the stable browsing agent identity (agentId 'browsing-chain', agentName botName) instead of reusing conversationId for agentId/agentName - Build the run config inside each urls.map callback so every readText call gets its own requestId
1 parent a3f2518 commit 2723927

86 files changed

Lines changed: 2065 additions & 7283 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎package.json‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414
"build": "yarn process-dynamic-import --lint && yarn fast-build shared-prompt-renderer && yarn fast-build core && yarn fast-build",
1515
"bump": "yakumo version",
1616
"dep": "yakumo upgrade",
17-
"test": "cross-env TS_NODE_PROJECT=packages/core/tests/tsconfig.json yakumo mocha -r tsconfig-paths/register -r esbuild-register -r yml-register --exit",
1817
"pub": "yakumo publish --tag latest",
1918
"pub:next": "yakumo publish --tag next",
2019
"lint": "yarn eslint packages --cache --ext=ts",

‎packages/adapter-claude/src/requester.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ export class ClaudeRequester extends ModelRequester<ClientConfig> {
142142
: undefined
143143
})
144144

145-
const iterator = sseIterable(response)
145+
const iterator = sseIterable(response, params)
146146
const reasoningState = new ReasoningState<ClaudeReasoningBlockParam>()
147147

148148
for await (const event of iterator) {

‎packages/adapter-deepseek/src/requester.ts‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import {
1818
completionStream,
1919
createEmbeddings,
2020
createRequestContext,
21+
createRequestSignal,
2122
parseOpenAIModelNameWithReasoningEffort,
2223
processStreamResponse
2324
} from '@chatluna/v1-shared-adapter'
@@ -87,17 +88,31 @@ export class DeepseekRequester
8788
delete request.top_p
8889
}
8990

91+
const requestSignal = createRequestSignal(params)
92+
9093
try {
9194
const response = await this.post('chat/completions', request, {
92-
signal: params.signal
95+
signal: requestSignal.signal
9396
})
97+
requestSignal.clearTimeout()
9498

95-
yield* processStreamResponse(requestContext, sseIterable(response))
99+
yield* processStreamResponse(
100+
requestContext,
101+
sseIterable(response, {
102+
timeout: params.timeout,
103+
signal: requestSignal.signal
104+
})
105+
)
96106
} catch (e) {
107+
if (requestSignal.signal?.aborted) {
108+
throw requestSignal.signal.reason ?? e
109+
}
97110
if (e instanceof ChatLunaError) {
98111
throw e
99112
}
100113
throw new ChatLunaError(ChatLunaErrorCode.API_REQUEST_FAILED, e)
114+
} finally {
115+
requestSignal.dispose()
101116
}
102117
}
103118

‎packages/adapter-dify/src/requester.ts‎

Lines changed: 138 additions & 95 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import {
3131
isMessageContentText
3232
} from 'koishi-plugin-chatluna/utils/string'
3333
import { File, FormData } from 'undici'
34+
import { createRequestSignal } from '@chatluna/v1-shared-adapter'
3435
import {
3536
mapMimeToFileType,
3637
resolveFilePayload,
@@ -162,73 +163,94 @@ export class DifyRequester extends ModelRequester<DifyClientConfig> {
162163
requestBody.files = files
163164
}
164165

165-
const response = await this._post(
166-
'/chat-messages',
167-
requestBody,
168-
config.apiKey,
169-
{
170-
signal: params.signal
171-
}
172-
)
166+
const requestSignal = createRequestSignal(params)
167+
168+
try {
169+
const response = await this._post(
170+
'/chat-messages',
171+
requestBody,
172+
config.apiKey,
173+
{
174+
signal: requestSignal.signal
175+
}
176+
)
177+
requestSignal.clearTimeout()
173178

174-
const iterator = sseIterable(response)
175-
let updatedDifyConversationId: string | undefined
179+
const iterator = sseIterable(response, {
180+
timeout: params.timeout,
181+
signal: requestSignal.signal
182+
})
183+
let updatedDifyConversationId: string | undefined
176184

177-
for await (const event of iterator) {
178-
const chunk = event.data
185+
for await (const event of iterator) {
186+
const chunk = event.data
179187

180-
if (chunk == null) {
181-
continue
182-
}
188+
if (chunk == null) {
189+
continue
190+
}
183191

184-
let data: AssistantStreamResponse
192+
let data: AssistantStreamResponse
185193

186-
try {
187-
data = JSON.parse(chunk)
188-
} catch (err) {
189-
this.ctx.logger.error(
190-
'error when parsing dify stream response, Result:' + chunk
191-
)
192-
throw new ChatLunaError(
193-
ChatLunaErrorCode.API_REQUEST_FAILED,
194-
new Error(
195-
'error when calling dify completion, Result: ' + chunk
194+
try {
195+
data = JSON.parse(chunk)
196+
} catch (err) {
197+
this.ctx.logger.error(
198+
'error when parsing dify stream response, Result:' +
199+
chunk
196200
)
197-
)
198-
}
201+
throw new ChatLunaError(
202+
ChatLunaErrorCode.API_REQUEST_FAILED,
203+
new Error(
204+
'error when calling dify completion, Result: ' +
205+
chunk
206+
)
207+
)
208+
}
199209

200-
if (data.event === 'error') {
201-
throw new ChatLunaError(
202-
ChatLunaErrorCode.API_REQUEST_FAILED,
203-
new Error(
204-
'error when calling dify completion, Result:' + chunk
210+
if (data.event === 'error') {
211+
throw new ChatLunaError(
212+
ChatLunaErrorCode.API_REQUEST_FAILED,
213+
new Error(
214+
'error when calling dify completion, Result:' +
215+
chunk
216+
)
205217
)
206-
)
207-
}
218+
}
208219

209-
const content = data.answer
220+
const content = data.answer
210221

211-
if (content != null) {
212-
const messageChunk = new AIMessageChunk({ content })
213-
const generationChunk = new ChatGenerationChunk({
214-
message: messageChunk,
215-
text: content
216-
})
222+
if (content != null) {
223+
const messageChunk = new AIMessageChunk({ content })
224+
const generationChunk = new ChatGenerationChunk({
225+
message: messageChunk,
226+
text: content
227+
})
217228

218-
yield generationChunk
219-
}
229+
yield generationChunk
230+
}
220231

221-
updatedDifyConversationId = data.conversation_id
232+
updatedDifyConversationId = data.conversation_id
222233

223-
if (data.event === 'message_end') {
224-
await this.updateDifyConversationId(
225-
conversationId,
226-
config.workflowName,
227-
updatedDifyConversationId,
228-
difyUser
229-
)
230-
break
234+
if (data.event === 'message_end') {
235+
await this.updateDifyConversationId(
236+
conversationId,
237+
config.workflowName,
238+
updatedDifyConversationId,
239+
difyUser
240+
)
241+
break
242+
}
231243
}
244+
} catch (e) {
245+
if (requestSignal.signal?.aborted) {
246+
throw requestSignal.signal.reason ?? e
247+
}
248+
if (e instanceof ChatLunaError) {
249+
throw e
250+
}
251+
throw new ChatLunaError(ChatLunaErrorCode.API_REQUEST_FAILED, e)
252+
} finally {
253+
requestSignal.dispose()
232254
}
233255
}
234256

@@ -267,60 +289,81 @@ export class DifyRequester extends ModelRequester<DifyClientConfig> {
267289
requestBody.files = files
268290
}
269291

270-
const response = await this._post(
271-
'/workflows/run',
272-
requestBody,
273-
config.apiKey,
274-
{
275-
signal: params.signal
276-
}
277-
)
292+
const requestSignal = createRequestSignal(params)
278293

279-
const iterator = sseIterable(response)
294+
try {
295+
const response = await this._post(
296+
'/workflows/run',
297+
requestBody,
298+
config.apiKey,
299+
{
300+
signal: requestSignal.signal
301+
}
302+
)
303+
requestSignal.clearTimeout()
280304

281-
for await (const event of iterator) {
282-
const chunk = event.data
305+
const iterator = sseIterable(response, {
306+
timeout: params.timeout,
307+
signal: requestSignal.signal
308+
})
283309

284-
if (chunk == null) {
285-
continue
286-
}
310+
for await (const event of iterator) {
311+
const chunk = event.data
312+
313+
if (chunk == null) {
314+
continue
315+
}
287316

288-
let data: AssistantStreamResponse
317+
let data: AssistantStreamResponse
289318

290-
try {
291-
data = JSON.parse(chunk)
292-
} catch (err) {
293-
this.ctx.logger.error(
294-
'error when parsing dify stream response, Result:' + chunk
295-
)
296-
throw new ChatLunaError(
297-
ChatLunaErrorCode.API_REQUEST_FAILED,
298-
new Error(
299-
'error when calling dify completion, Result: ' + chunk
319+
try {
320+
data = JSON.parse(chunk)
321+
} catch (err) {
322+
this.ctx.logger.error(
323+
'error when parsing dify stream response, Result:' +
324+
chunk
300325
)
301-
)
302-
}
326+
throw new ChatLunaError(
327+
ChatLunaErrorCode.API_REQUEST_FAILED,
328+
new Error(
329+
'error when calling dify completion, Result: ' +
330+
chunk
331+
)
332+
)
333+
}
303334

304-
if (data.event === 'error') {
305-
throw new ChatLunaError(
306-
ChatLunaErrorCode.API_REQUEST_FAILED,
307-
new Error(
308-
'error when calling dify completion, Result:' + chunk
335+
if (data.event === 'error') {
336+
throw new ChatLunaError(
337+
ChatLunaErrorCode.API_REQUEST_FAILED,
338+
new Error(
339+
'error when calling dify completion, Result:' +
340+
chunk
341+
)
309342
)
310-
)
311-
}
343+
}
312344

313-
const content = data.answer
345+
const content = data.answer
314346

315-
if (content != null) {
316-
const messageChunk = new AIMessageChunk({ content })
317-
const generationChunk = new ChatGenerationChunk({
318-
message: messageChunk,
319-
text: content
320-
})
347+
if (content != null) {
348+
const messageChunk = new AIMessageChunk({ content })
349+
const generationChunk = new ChatGenerationChunk({
350+
message: messageChunk,
351+
text: content
352+
})
321353

322-
yield generationChunk
354+
yield generationChunk
355+
}
356+
}
357+
} catch (e) {
358+
if (requestSignal.signal?.aborted) {
359+
throw requestSignal.signal.reason ?? e
360+
}
361+
if (e instanceof ChatLunaError) {
362+
throw e
323363
}
364+
throw new ChatLunaError(ChatLunaErrorCode.API_REQUEST_FAILED, e)
365+
} finally {
366+
requestSignal.dispose()
324367
}
325368
}
326369

‎packages/adapter-doubao/src/requester.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ export class DoubaoRequester
100100
signal: params.signal
101101
})
102102

103-
const iterator = sseIterable(response)
103+
const iterator = sseIterable(response, params)
104104
yield* processStreamResponse(requestContext, iterator)
105105
} catch (e) {
106106
if (e instanceof ChatLunaError) {

0 commit comments

Comments
 (0)