From dec70de9cba685b912ded87b69c5022cb4db7231 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A7=A3=E4=BC=9F?= Date: Tue, 10 Nov 2026 14:38:09 +0800 Subject: [PATCH 1/5] fix(harness): announce failed subagent tasks as failures, not completions The message-bus completion callback pushed the same "has completed ... Result: (no output)" inbox hint for FAILED tasks as for delivered results, so the parent model treated execution failures (e.g. model retries exhausted) as empty business results and closed the loop instead of retrying or escalating. The callback now carries the terminal TaskStatus plus the failure message, and the hint wording mirrors the task-delivery reminder's semantics. --- .../harness/agent/HarnessAgent.java | 12 ++-- .../agent/middleware/SubagentsMiddleware.java | 42 +++++++++--- .../agent/subagent/task/TaskRepository.java | 12 ++-- .../task/WorkspaceTaskRepository.java | 40 ++++++++--- .../SubagentTaskSettledHintTest.java | 64 ++++++++++++++++++ ...paceTaskRepositoryRemoteStreamingTest.java | 3 +- .../task/WorkspaceTaskRepositoryTest.java | 66 ++++++++++++++++++- 7 files changed, 209 insertions(+), 30 deletions(-) create mode 100644 agentscope-harness/src/test/java/io/agentscope/harness/agent/middleware/SubagentTaskSettledHintTest.java diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java index 43b2fd9d26..f3c673a305 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java @@ -2730,16 +2730,12 @@ private static void wireTaskRepositoryMessageBus( io.agentscope.harness.agent.bus.MessageBus bus, String agentId) { repo.setCompletionCallback( - (rc, taskId, subAgentId, sessionId, result) -> { + (rc, taskId, subAgentId, sessionId, status, result, errorMessage) -> { String userId = rc != null ? rc.getUserId() : null; String hintContent = - String.format( - "Background subagent task '%s'" - + " (agent=%s) has completed.\n\nResult:\n\n%s" - + "", - taskId, - subAgentId, - result != null ? result : "(no output)"); + io.agentscope.harness.agent.middleware.SubagentsMiddleware + .taskSettledHintContent( + taskId, subAgentId, status, result, errorMessage); String hintId = java.util.UUID.randomUUID().toString().replace("-", ""); bus.inboxPush( sessionId, diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/middleware/SubagentsMiddleware.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/middleware/SubagentsMiddleware.java index f48fb6776e..b2d4fc79cc 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/middleware/SubagentsMiddleware.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/middleware/SubagentsMiddleware.java @@ -296,6 +296,34 @@ public TaskRepository getTaskRepository() { return taskRepository; } + /** + * Formats the inbox hint pushed when a background subagent task settles. + * + *

Failed tasks must not be announced with completion wording: the parent model would treat + * the run as a delivered (empty) business result instead of an infrastructure failure to retry + * or escalate. Mirrors the task-delivery reminder's {@code } semantics.

+ */ + public static String taskSettledHintContent( + String taskId, + String subAgentId, + TaskStatus status, + String result, + String errorMessage) { + if (status == TaskStatus.FAILED) { + return String.format( + "Background subagent task '%s' (agent=%s) FAILED and" + + " produced no result.\n\nError:\n\n%s\n\nThis is an execution" + + " failure, not a business conclusion. Use task_output(task_id=...," + + " block=false) or task_list() if you need the task" + + " record.", + taskId, subAgentId, errorMessage != null ? errorMessage : "(no error message)"); + } + return String.format( + "Background subagent task '%s' (agent=%s) has completed." + + "\n\nResult:\n\n%s", + taskId, subAgentId, result != null ? result : "(no output)"); + } + /** * Wires a {@link io.agentscope.harness.agent.bus.MessageBus} so that background task completions are * pushed to the session inbox and a wakeup signal is enqueued. This enables the @@ -315,14 +343,11 @@ public SubagentsMiddleware wireMessageBus( return this; } taskRepository.setCompletionCallback( - (rc, taskId, subAgentId, sessionId, result) -> { + (rc, taskId, subAgentId, sessionId, status, result, errorMessage) -> { String userId = rc != null ? rc.getUserId() : null; String hintContent = - String.format( - "Background subagent task '%s'" - + " (agent=%s) has completed.\n\nResult:\n\n%s" - + "", - taskId, subAgentId, result != null ? result : "(no output)"); + taskSettledHintContent( + taskId, subAgentId, status, result, errorMessage); String hintId = java.util.UUID.randomUUID().toString().replace("-", ""); java.util.Map hintPayload = java.util.Map.of( @@ -349,9 +374,10 @@ public SubagentsMiddleware wireMessageBus( taskId, err.getMessage())); log.info( - "Subagent task {} completed, pushed to inbox and enqueued wakeup:" - + " session={}", + "Subagent task {} settled (status={}), pushed to inbox and enqueued" + + " wakeup: session={}", taskId, + status, sessionId); }); return this; diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/TaskRepository.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/TaskRepository.java index 95bd619a0d..ed4078a928 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/TaskRepository.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/TaskRepository.java @@ -128,8 +128,9 @@ default boolean isDelivered(RuntimeContext rc, String sessionId, String taskId) /** * Registers a callback invoked when any task reaches a terminal state (COMPLETED or FAILED). * Used by {@link io.agentscope.harness.agent.middleware.SubagentsMiddleware} to push results - * to the session inbox and enqueue a wakeup signal. The {@code result} argument is {@code null} - * for failed tasks. + * to the session inbox and enqueue a wakeup signal. The callback receives the terminal + * {@link TaskStatus}; {@code result} is {@code null} for failed tasks and + * {@code errorMessage} is {@code null} for completed ones. * *

Callers retaining execution ownership can set {@link #SUPPRESS_COMPLETION_CALLBACK} * in their RuntimeContext to suppress inbox/wakeup callbacks while preserving durable results. @@ -147,7 +148,8 @@ default void shutdown() { /** * Callback invoked when a background task reaches a terminal state (COMPLETED or FAILED). - * {@code result} is {@code null} when the task failed. + * {@code result} is {@code null} when the task failed; {@code errorMessage} is {@code null} + * when it completed. */ @FunctionalInterface interface TaskCompletionCallback { @@ -156,6 +158,8 @@ void onCompleted( String taskId, String subAgentId, String sessionId, - String result); + TaskStatus status, + String result, + String errorMessage); } } diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepository.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepository.java index 3fcfeafb24..7fa145c109 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepository.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepository.java @@ -318,11 +318,25 @@ public BackgroundTask putTask( ? cause.getClass().getSimpleName() : err.getClass().getSimpleName()); updateStatus(capturedRc, sid, taskId, TaskStatus.FAILED, null, errMsg); - fireCompletionCallback(capturedRc, taskId, subAgentId, sid, null); + fireCompletionCallback( + capturedRc, + taskId, + subAgentId, + sid, + TaskStatus.FAILED, + null, + errMsg); } else { updateStatus( capturedRc, sid, taskId, TaskStatus.COMPLETED, result, null); - fireCompletionCallback(capturedRc, taskId, subAgentId, sid, result); + fireCompletionCallback( + capturedRc, + taskId, + subAgentId, + sid, + TaskStatus.COMPLETED, + result, + null); } }); } else if (spec instanceof TaskRunSpec.LocalTaskRunSpec local) { @@ -382,12 +396,14 @@ private String runLocalSupplier( return null; } updateStatus(rc, sessionId, taskId, TaskStatus.COMPLETED, result, null); - fireCompletionCallback(rc, taskId, subAgentId, sessionId, result); + fireCompletionCallback( + rc, taskId, subAgentId, sessionId, TaskStatus.COMPLETED, result, null); return result; } catch (Exception e) { String errMsg = e.getMessage() != null ? e.getMessage() : e.getClass().getSimpleName(); updateStatus(rc, sessionId, taskId, TaskStatus.FAILED, null, errMsg); - fireCompletionCallback(rc, taskId, subAgentId, sessionId, null); + fireCompletionCallback( + rc, taskId, subAgentId, sessionId, TaskStatus.FAILED, null, errMsg); throw e instanceof RuntimeException re ? re : new RuntimeException(e); } } @@ -415,13 +431,15 @@ private String runRemoteTask( } String result = pollRemoteUntilDone(rc, sessionId, taskId, target); if (result != null) { - fireCompletionCallback(rc, taskId, subAgentId, sessionId, result); + fireCompletionCallback( + rc, taskId, subAgentId, sessionId, TaskStatus.COMPLETED, result, null); } return result; } catch (Exception e) { String errMsg = e.getMessage() != null ? e.getMessage() : e.getClass().getSimpleName(); updateStatus(rc, sessionId, taskId, TaskStatus.FAILED, null, errMsg); - fireCompletionCallback(rc, taskId, subAgentId, sessionId, null); + fireCompletionCallback( + rc, taskId, subAgentId, sessionId, TaskStatus.FAILED, null, errMsg); throw e instanceof RuntimeException re ? re : new RuntimeException(e); } } @@ -974,14 +992,20 @@ private BackgroundTask syntheticTask(RuntimeContext rc, TaskRecord record) { } private void fireCompletionCallback( - RuntimeContext rc, String taskId, String subAgentId, String sessionId, String result) { + RuntimeContext rc, + String taskId, + String subAgentId, + String sessionId, + TaskStatus status, + String result, + String errorMessage) { TaskCompletionCallback cb = this.completionCallback; if (cb == null || (rc != null && Boolean.TRUE.equals(rc.get(SUPPRESS_COMPLETION_CALLBACK)))) { return; } try { - cb.onCompleted(rc, taskId, subAgentId, sessionId, result); + cb.onCompleted(rc, taskId, subAgentId, sessionId, status, result, errorMessage); } catch (Exception e) { log.warn("TaskCompletionCallback failed for task {}: {}", taskId, e.getMessage(), e); } diff --git a/agentscope-harness/src/test/java/io/agentscope/harness/agent/middleware/SubagentTaskSettledHintTest.java b/agentscope-harness/src/test/java/io/agentscope/harness/agent/middleware/SubagentTaskSettledHintTest.java new file mode 100644 index 0000000000..5e23b2ca72 --- /dev/null +++ b/agentscope-harness/src/test/java/io/agentscope/harness/agent/middleware/SubagentTaskSettledHintTest.java @@ -0,0 +1,64 @@ +/* + * Copyright 2024-2026 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.agentscope.harness.agent.middleware; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import io.agentscope.harness.agent.subagent.task.TaskStatus; +import org.junit.jupiter.api.Test; + +/** + * Failed background subagent tasks must be announced as failures, not with the completion wording + * used for delivered results: the parent model otherwise treats the run as an empty business + * result and closes the loop instead of retrying or escalating the execution failure. + */ +class SubagentTaskSettledHintTest { + + @Test + void failedTaskIsAnnouncedWithErrorNotCompletion() { + String hint = + SubagentsMiddleware.taskSettledHintContent( + "task_1", "image-reader", TaskStatus.FAILED, null, "boom: rate limited"); + + assertTrue(hint.contains("FAILED"), hint); + assertTrue(hint.contains("boom: rate limited"), hint); + assertTrue(hint.contains("execution failure, not a business conclusion"), hint); + assertFalse(hint.contains("has completed"), hint); + assertFalse(hint.contains("Result:"), hint); + } + + @Test + void completedTaskKeepsCompletionWording() { + String hint = + SubagentsMiddleware.taskSettledHintContent( + "task_1", "image-reader", TaskStatus.COMPLETED, "done: 3 findings", null); + + assertTrue(hint.contains("has completed"), hint); + assertTrue(hint.contains("done: 3 findings"), hint); + assertFalse(hint.contains("FAILED"), hint); + } + + @Test + void failedTaskWithoutMessageStillSaysFailed() { + String hint = + SubagentsMiddleware.taskSettledHintContent( + "task_1", "worker", TaskStatus.FAILED, null, null); + + assertTrue(hint.contains("FAILED"), hint); + assertTrue(hint.contains("(no error message)"), hint); + } +} diff --git a/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryRemoteStreamingTest.java b/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryRemoteStreamingTest.java index 203e64a6f4..d1490ce758 100644 --- a/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryRemoteStreamingTest.java +++ b/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryRemoteStreamingTest.java @@ -72,7 +72,8 @@ void remoteTask_togglesAwaitingConfirm_thenFiresCompletionOnSuccess() throws Exc AtomicReference completedResult = new AtomicReference<>(); repo.setCompletionCallback( - (rc, taskId, subAgentId, sessionId, result) -> completedResult.set(result)); + (rc, taskId, subAgentId, sessionId, status, result, errorMessage) -> + completedResult.set(result)); String session = "sess-remote"; String taskId = "task-remote-hitl"; diff --git a/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryTest.java b/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryTest.java index 09798523be..9ca704704e 100644 --- a/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryTest.java +++ b/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryTest.java @@ -172,6 +172,69 @@ void putTask_writesFailedOnException() throws Exception { assertTrue(record.get().getErrorMessage().contains("intentional failure")); } + @Test + @DisplayName("completion callback receives FAILED status and error message when task throws") + void completionCallback_receivesFailedStatusAndError() throws Exception { + java.util.concurrent.atomic.AtomicReference status = + new java.util.concurrent.atomic.AtomicReference<>(); + java.util.concurrent.atomic.AtomicReference result = + new java.util.concurrent.atomic.AtomicReference<>(); + java.util.concurrent.atomic.AtomicReference error = + new java.util.concurrent.atomic.AtomicReference<>(); + repo.setCompletionCallback( + (rc, taskId, subAgentId, sessionId, cbStatus, cbResult, cbError) -> { + status.set(cbStatus); + result.set(cbResult); + error.set(cbError); + }); + + repo.putTask( + RuntimeContext.empty(), + "task-callback-fail", + "sub-agent-fail", + "sess-callback", + new TaskRunSpec.LocalTaskRunSpec( + () -> { + throw new RuntimeException("callback failure detail"); + })); + + awaitCondition(() -> status.get() != null); + + assertEquals(TaskStatus.FAILED, status.get()); + assertEquals(null, result.get()); + assertTrue(error.get().contains("callback failure detail")); + } + + @Test + @DisplayName("completion callback receives COMPLETED status and result on success") + void completionCallback_receivesCompletedStatusAndResult() throws Exception { + java.util.concurrent.atomic.AtomicReference status = + new java.util.concurrent.atomic.AtomicReference<>(); + java.util.concurrent.atomic.AtomicReference result = + new java.util.concurrent.atomic.AtomicReference<>(); + java.util.concurrent.atomic.AtomicReference error = + new java.util.concurrent.atomic.AtomicReference<>(); + repo.setCompletionCallback( + (rc, taskId, subAgentId, sessionId, cbStatus, cbResult, cbError) -> { + status.set(cbStatus); + result.set(cbResult); + error.set(cbError); + }); + + repo.putTask( + RuntimeContext.empty(), + "task-callback-ok", + "sub-agent-ok", + "sess-callback", + new TaskRunSpec.LocalTaskRunSpec(() -> "delivered")); + + awaitCondition(() -> status.get() != null); + + assertEquals(TaskStatus.COMPLETED, status.get()); + assertEquals("delivered", result.get()); + assertEquals(null, error.get()); + } + // ------------------------------------------------------------------ // Cross-node fallback: no local future // ------------------------------------------------------------------ @@ -960,7 +1023,8 @@ void cancellationListenersObservePersistedTerminalState() throws Exception { void executionOwnerCanSuppressWakeupWithoutLosingDurableDelivery() throws Exception { AtomicInteger wakeups = new AtomicInteger(); repo.setCompletionCallback( - (rc, taskId, agentId, sessionId, result) -> wakeups.incrementAndGet()); + (rc, taskId, agentId, sessionId, status, result, errorMessage) -> + wakeups.incrementAndGet()); RuntimeContext managed = RuntimeContext.builder() .sessionId("managed") From 24a8cf5e0c747971116aa3a82c4a2c5afc3f8ba7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A7=A3=E4=BC=9F?= Date: Tue, 10 Nov 2026 21:34:49 +0800 Subject: [PATCH 2/5] fix(harness): keep the task completion callback backward compatible Changing TaskCompletionCallback.onCompleted to seven parameters broke existing lambdas, custom repositories and precompiled callers, and left ControlPlaneTaskRepository uncompilable. Restore the original method and carry terminal status and errors through an additive default onSettled; TaskSettledCallback lets the built-in message-bus wiring consume them through the unchanged setCompletionCallback. Built-in repositories, including the control-plane one, call onSettled explicitly, so empty successes stay completions. Tests now cover both bridge directions (including callers compiled against the old interface), both repository backends and every message-bus wiring path. --- .../harness/agent/HarnessAgent.java | 56 ++-- .../agent/middleware/SubagentsMiddleware.java | 75 ++--- .../agent/subagent/task/TaskRepository.java | 53 +++- .../task/WorkspaceTaskRepository.java | 2 +- .../SubagentTaskSettledHintTest.java | 265 +++++++++++++++++- ...paceTaskRepositoryRemoteStreamingTest.java | 40 ++- .../task/WorkspaceTaskRepositoryTest.java | 220 ++++++++++++--- docs/v2/en/docs/harness/subagent.md | 2 + docs/v2/zh/docs/harness/subagent.md | 2 + 9 files changed, 604 insertions(+), 111 deletions(-) diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java index f3c673a305..f85d9e2f7e 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java @@ -2730,31 +2730,37 @@ private static void wireTaskRepositoryMessageBus( io.agentscope.harness.agent.bus.MessageBus bus, String agentId) { repo.setCompletionCallback( - (rc, taskId, subAgentId, sessionId, status, result, errorMessage) -> { - String userId = rc != null ? rc.getUserId() : null; - String hintContent = - io.agentscope.harness.agent.middleware.SubagentsMiddleware - .taskSettledHintContent( - taskId, subAgentId, status, result, errorMessage); - String hintId = java.util.UUID.randomUUID().toString().replace("-", ""); - bus.inboxPush( - sessionId, - java.util.Map.of( - "type", - "hint", - "id", - hintId, - "hint", - hintContent, - "source", - "subagent_task")) - .subscribe(); - bus.enqueueWakeup( - userId != null ? userId : "", - sessionId, - agentId != null ? agentId : "") - .subscribe(); - }); + (io.agentscope.harness.agent.subagent.task.TaskRepository.TaskSettledCallback) + (rc, taskId, subAgentId, sessionId, status, result, errorMessage) -> { + String userId = rc != null ? rc.getUserId() : null; + String hintContent = + io.agentscope.harness.agent.middleware.SubagentsMiddleware + .taskSettledHintContent( + taskId, + subAgentId, + status, + result, + errorMessage); + String hintId = + java.util.UUID.randomUUID().toString().replace("-", ""); + bus.inboxPush( + sessionId, + java.util.Map.of( + "type", + "hint", + "id", + hintId, + "hint", + hintContent, + "source", + "subagent_task")) + .subscribe(); + bus.enqueueWakeup( + userId != null ? userId : "", + sessionId, + agentId != null ? agentId : "") + .subscribe(); + }); } /** diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/middleware/SubagentsMiddleware.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/middleware/SubagentsMiddleware.java index b2d4fc79cc..24060c1d7d 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/middleware/SubagentsMiddleware.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/middleware/SubagentsMiddleware.java @@ -343,43 +343,44 @@ public SubagentsMiddleware wireMessageBus( return this; } taskRepository.setCompletionCallback( - (rc, taskId, subAgentId, sessionId, status, result, errorMessage) -> { - String userId = rc != null ? rc.getUserId() : null; - String hintContent = - taskSettledHintContent( - taskId, subAgentId, status, result, errorMessage); - String hintId = java.util.UUID.randomUUID().toString().replace("-", ""); - java.util.Map hintPayload = - java.util.Map.of( - "type", - "hint", - "id", - hintId, - "hint", - hintContent, - "source", - "subagent_task"); - messageBus.inboxPush(sessionId, hintPayload).subscribe(); - messageBus - .enqueueWakeup( - userId != null ? userId : "", - sessionId, - agentId != null ? agentId : "") - .subscribe( - unused -> {}, - err -> - log.warn( - "Failed to enqueue wakeup after task {}" - + " completion: {}", - taskId, - err.getMessage())); - log.info( - "Subagent task {} settled (status={}), pushed to inbox and enqueued" - + " wakeup: session={}", - taskId, - status, - sessionId); - }); + (TaskRepository.TaskSettledCallback) + (rc, taskId, subAgentId, sessionId, status, result, errorMessage) -> { + String userId = rc != null ? rc.getUserId() : null; + String hintContent = + taskSettledHintContent( + taskId, subAgentId, status, result, errorMessage); + String hintId = java.util.UUID.randomUUID().toString().replace("-", ""); + java.util.Map hintPayload = + java.util.Map.of( + "type", + "hint", + "id", + hintId, + "hint", + hintContent, + "source", + "subagent_task"); + messageBus.inboxPush(sessionId, hintPayload).subscribe(); + messageBus + .enqueueWakeup( + userId != null ? userId : "", + sessionId, + agentId != null ? agentId : "") + .subscribe( + unused -> {}, + err -> + log.warn( + "Failed to enqueue wakeup after task {}" + + " completion: {}", + taskId, + err.getMessage())); + log.info( + "Subagent task {} settled (status={}), pushed to inbox and" + + " enqueued wakeup: session={}", + taskId, + status, + sessionId); + }); return this; } diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/TaskRepository.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/TaskRepository.java index ed4078a928..015ed288a9 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/TaskRepository.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/TaskRepository.java @@ -128,9 +128,8 @@ default boolean isDelivered(RuntimeContext rc, String sessionId, String taskId) /** * Registers a callback invoked when any task reaches a terminal state (COMPLETED or FAILED). * Used by {@link io.agentscope.harness.agent.middleware.SubagentsMiddleware} to push results - * to the session inbox and enqueue a wakeup signal. The callback receives the terminal - * {@link TaskStatus}; {@code result} is {@code null} for failed tasks and - * {@code errorMessage} is {@code null} for completed ones. + * to the session inbox and enqueue a wakeup signal. The {@code result} argument is {@code null} + * for failed tasks. Use {@link TaskSettledCallback} to also receive terminal status and errors. * *

Callers retaining execution ownership can set {@link #SUPPRESS_COMPLETION_CALLBACK} * in their RuntimeContext to suppress inbox/wakeup callbacks while preserving durable results. @@ -146,14 +145,34 @@ default void shutdown() { // no-op } - /** - * Callback invoked when a background task reaches a terminal state (COMPLETED or FAILED). - * {@code result} is {@code null} when the task failed; {@code errorMessage} is {@code null} - * when it completed. - */ + /** Callback for completed or failed tasks; {@code result} is null on failure. */ @FunctionalInterface interface TaskCompletionCallback { void onCompleted( + RuntimeContext rc, + String taskId, + String subAgentId, + String sessionId, + String result); + + /** Delivers terminal details while preserving the five-argument callback contract. */ + default void onSettled( + RuntimeContext rc, + String taskId, + String subAgentId, + String sessionId, + TaskStatus status, + String result, + String errorMessage) { + onCompleted(rc, taskId, subAgentId, sessionId, result); + } + } + + /** Terminal callback; register through {@link TaskRepository#setCompletionCallback}. */ + @FunctionalInterface + interface TaskSettledCallback extends TaskCompletionCallback { + @Override + void onSettled( RuntimeContext rc, String taskId, String subAgentId, @@ -161,5 +180,23 @@ void onCompleted( TaskStatus status, String result, String errorMessage); + + /** Legacy repositories only distinguish failures by a null result and provide no error. */ + @Override + default void onCompleted( + RuntimeContext rc, + String taskId, + String subAgentId, + String sessionId, + String result) { + onSettled( + rc, + taskId, + subAgentId, + sessionId, + result != null ? TaskStatus.COMPLETED : TaskStatus.FAILED, + result, + null); + } } } diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepository.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepository.java index 7fa145c109..59cd708c72 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepository.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepository.java @@ -1005,7 +1005,7 @@ private void fireCompletionCallback( return; } try { - cb.onCompleted(rc, taskId, subAgentId, sessionId, status, result, errorMessage); + cb.onSettled(rc, taskId, subAgentId, sessionId, status, result, errorMessage); } catch (Exception e) { log.warn("TaskCompletionCallback failed for task {}: {}", taskId, e.getMessage(), e); } diff --git a/agentscope-harness/src/test/java/io/agentscope/harness/agent/middleware/SubagentTaskSettledHintTest.java b/agentscope-harness/src/test/java/io/agentscope/harness/agent/middleware/SubagentTaskSettledHintTest.java index 5e23b2ca72..ba2ec37188 100644 --- a/agentscope-harness/src/test/java/io/agentscope/harness/agent/middleware/SubagentTaskSettledHintTest.java +++ b/agentscope-harness/src/test/java/io/agentscope/harness/agent/middleware/SubagentTaskSettledHintTest.java @@ -15,19 +15,74 @@ */ package io.agentscope.harness.agent.middleware; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.CALLS_REAL_METHODS; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import io.agentscope.core.agent.RuntimeContext; +import io.agentscope.core.model.Model; +import io.agentscope.harness.agent.HarnessAgent; +import io.agentscope.harness.agent.bus.MessageBus; +import io.agentscope.harness.agent.filesystem.local.LocalFilesystem; +import io.agentscope.harness.agent.subagent.task.BackgroundTask; +import io.agentscope.harness.agent.subagent.task.TaskRepository; +import io.agentscope.harness.agent.subagent.task.TaskRunSpec.LocalTaskRunSpec; import io.agentscope.harness.agent.subagent.task.TaskStatus; +import io.agentscope.harness.agent.subagent.task.WorkspaceTaskRepository; +import io.agentscope.harness.agent.workspace.WorkspaceManager; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import reactor.core.publisher.Mono; -/** - * Failed background subagent tasks must be announced as failures, not with the completion wording - * used for delivered results: the parent model otherwise treats the run as an empty business - * result and closes the loop instead of retrying or escalating the execution failure. - */ +/** Subagent task hints preserve terminal status and errors through every message-bus wiring path. */ class SubagentTaskSettledHintTest { + private static final String PARENT_ID = "parent"; + private static final String USER_ID = "original-user"; + private static final String SESSION_ID = "original-session"; + private static final String TASK_ID = "task_settled"; + private static final String SUBAGENT_ID = "image-reader"; + private static final String ERROR = "boom: rate limited"; + private static final String OUTPUT = "done: 3 findings"; + + @TempDir Path tempDir; + + private HarnessAgent agent; + private WorkspaceManager workspaceManager; + private WorkspaceTaskRepository repo; + private RecordingBus recordingBus; + + @AfterEach + void closeResources() { + try { + if (agent != null) { + agent.close(); + } + } finally { + if (repo != null) { + repo.shutdown(); + } + if (workspaceManager != null) { + workspaceManager.close(); + } + } + } + @Test void failedTaskIsAnnouncedWithErrorNotCompletion() { String hint = @@ -61,4 +116,204 @@ void failedTaskWithoutMessageStillSaysFailed() { assertTrue(hint.contains("FAILED"), hint); assertTrue(hint.contains("(no error message)"), hint); } + + @ParameterizedTest + @EnumSource(EntryMode.class) + void failedTaskWiringPushesErrorAndWakesOriginalSession(EntryMode mode) throws Exception { + wire(mode); + RuntimeContext rc = runtimeContext(false); + BackgroundTask task = submitFailingTask(rc); + + String hint = awaitHintAndWakeup(task); + + assertEquals(TaskStatus.FAILED, task.getTaskStatus()); + assertEquals(ERROR, task.getError().getMessage()); + assertDurableResult(rc, TaskStatus.FAILED, null, ERROR); + assertTrue(hint.contains("FAILED"), hint); + assertTrue(hint.contains(ERROR), hint); + assertFalse(hint.contains("has completed"), hint); + assertFalse(hint.contains("Result:"), hint); + } + + @ParameterizedTest + @EnumSource(EntryMode.class) + void completedTaskWiringPushesOutputAndWakesOriginalSession(EntryMode mode) throws Exception { + wire(mode); + RuntimeContext rc = runtimeContext(false); + BackgroundTask task = submitTask(rc, () -> OUTPUT); + + String hint = awaitHintAndWakeup(task); + + assertEquals(TaskStatus.COMPLETED, task.getTaskStatus()); + assertDurableResult(rc, TaskStatus.COMPLETED, OUTPUT, null); + assertTrue(hint.contains("has completed"), hint); + assertTrue(hint.contains(OUTPUT), hint); + assertFalse(hint.contains("FAILED"), hint); + } + + @ParameterizedTest + @EnumSource(EntryMode.class) + void nullResultTaskWiringStillAnnouncesCompletion(EntryMode mode) throws Exception { + wire(mode); + RuntimeContext rc = runtimeContext(false); + BackgroundTask task = submitTask(rc, () -> null); + + String hint = awaitHintAndWakeup(task); + + assertEquals(TaskStatus.COMPLETED, task.getTaskStatus()); + assertDurableResult(rc, TaskStatus.COMPLETED, null, null); + assertTrue(hint.contains("has completed"), hint); + assertTrue(hint.contains("(no output)"), hint); + assertFalse(hint.contains("FAILED"), hint); + } + + @ParameterizedTest + @EnumSource(EntryMode.class) + void suppressedFailedTaskPreservesDurableErrorWithoutNotifications(EntryMode mode) + throws Exception { + wire(mode); + RuntimeContext rc = runtimeContext(true); + BackgroundTask task = submitFailingTask(rc); + + assertTrue(task.waitForCompletion(5_000), "task did not settle within 5 seconds"); + + assertEquals(TaskStatus.FAILED, task.getTaskStatus()); + assertEquals(ERROR, task.getError().getMessage()); + assertDurableResult(rc, TaskStatus.FAILED, null, ERROR); + assertEquals(List.of(), recordingBus.queued); + assertEquals(List.of(), recordingBus.published); + } + + private void wire(EntryMode mode) { + workspaceManager = new WorkspaceManager(tempDir); + repo = WorkspaceTaskRepository.forTests(workspaceManager, PARENT_ID); + recordingBus = new RecordingBus(); + if (mode == EntryMode.DIRECT) { + new SubagentsMiddleware(List.of(), repo, workspaceManager) + .wireMessageBus(recordingBus.bus, PARENT_ID); + return; + } + Model model = mock(Model.class); + HarnessAgent.Builder builder = + HarnessAgent.builder() + .name(PARENT_ID) + .agentId(PARENT_ID) + .model(model) + .workspace(tempDir) + .abstractFilesystem(new LocalFilesystem(tempDir)) + .taskRepository(repo) + .messageBus(recordingBus.bus) + .disableMemoryTools() + .disableMemoryHooks(); + if (mode == EntryMode.BUILDER_STATIC) { + builder.disableDynamicSubagents(); + } + agent = builder.build(); + } + + private static RuntimeContext runtimeContext(boolean suppress) { + return RuntimeContext.builder() + .userId(USER_ID) + .sessionId(SESSION_ID) + .put(TaskRepository.SUPPRESS_COMPLETION_CALLBACK, suppress) + .build(); + } + + private BackgroundTask submitTask(RuntimeContext rc, Supplier execution) { + return repo.putTask(rc, TASK_ID, SUBAGENT_ID, SESSION_ID, new LocalTaskRunSpec(execution)); + } + + private BackgroundTask submitFailingTask(RuntimeContext rc) { + return submitTask( + rc, + () -> { + throw new IllegalStateException(ERROR); + }); + } + + private String awaitHintAndWakeup(BackgroundTask task) throws Exception { + recordingBus.notified.get(5, TimeUnit.SECONDS); + assertTrue(task.waitForCompletion(5_000), "task did not settle within 5 seconds"); + assertEquals( + List.of("agentscope:inbox:" + SESSION_ID, "agentscope:wakeups"), + recordingBus.queued.stream().map(BusCall::key).toList()); + Map payload = recordingBus.queued.get(0).payload(); + assertEquals("hint", payload.get("type")); + assertEquals("subagent_task", payload.get("source")); + String hint = (String) payload.get("hint"); + assertTrue(hint.contains(TASK_ID), hint); + assertTrue(hint.contains(SUBAGENT_ID), hint); + assertEquals( + Map.of("userId", USER_ID, "sessionId", SESSION_ID, "agentId", PARENT_ID), + recordingBus.queued.get(1).payload()); + assertEquals( + List.of(new BusCall("agentscope:wakeup_signal", Map.of())), recordingBus.published); + return hint; + } + + private void assertDurableResult( + RuntimeContext rc, TaskStatus status, String result, String errorMessage) { + var record = + workspaceManager.readTaskRecord(rc, PARENT_ID, SESSION_ID, TASK_ID).orElseThrow(); + assertEquals(TASK_ID, record.getTaskId()); + assertEquals(SUBAGENT_ID, record.getSubAgentId()); + assertEquals(PARENT_ID, record.getParentAgentId()); + assertEquals(SESSION_ID, record.getParentSessionId()); + assertEquals(status, record.getStatus()); + assertEquals(result, record.getResult()); + assertEquals(errorMessage, record.getErrorMessage()); + } + + enum EntryMode { + DIRECT, + BUILDER_DYNAMIC, + BUILDER_STATIC + } + + private record BusCall(String key, Map payload) {} + + private static final class RecordingBus { + private final MessageBus bus = mock(MessageBus.class, CALLS_REAL_METHODS); + private final List queued = new CopyOnWriteArrayList<>(); + private final List published = new CopyOnWriteArrayList<>(); + private final CompletableFuture notified = new CompletableFuture<>(); + + private RecordingBus() { + doAnswer( + invocation -> { + String key = invocation.getArgument(0); + Map payload = invocation.getArgument(1); + return Mono.fromSupplier( + () -> { + queued.add(new BusCall(key, Map.copyOf(payload))); + completeIfNotified(); + return "entry-" + queued.size(); + }); + }) + .when(bus) + .queuePush(anyString(), anyMap()); + doAnswer( + invocation -> { + String key = invocation.getArgument(0); + Map payload = invocation.getArgument(1); + return Mono.defer( + () -> { + published.add(new BusCall(key, Map.copyOf(payload))); + completeIfNotified(); + return Mono.empty(); + }); + }) + .when(bus) + .publish(anyString(), anyMap()); + } + + private void completeIfNotified() { + if (queued.stream().anyMatch(call -> call.key().startsWith("agentscope:inbox:")) + && queued.stream().anyMatch(call -> call.key().equals("agentscope:wakeups")) + && published.stream() + .anyMatch(call -> call.key().equals("agentscope:wakeup_signal"))) { + notified.complete(null); + } + } + } } diff --git a/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryRemoteStreamingTest.java b/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryRemoteStreamingTest.java index d1490ce758..bcaa40684f 100644 --- a/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryRemoteStreamingTest.java +++ b/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryRemoteStreamingTest.java @@ -17,7 +17,12 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import io.agentscope.core.agent.RuntimeContext; import io.agentscope.harness.agent.subagent.protocol.RemoteAgentEvent; @@ -29,7 +34,9 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; @@ -62,6 +69,36 @@ void tearDown() { } } + @Test + void remoteFailureDeliversStatusAndError() throws Exception { + RemoteSubagentTransport transport = mock(RemoteSubagentTransport.class); + when(transport.getStatus(any(), anyString())) + .thenReturn(new RemoteTaskStatus("failed", "remote execution error")); + repo.setTransport(transport); + CompletableFuture callback = new CompletableFuture<>(); + repo.setCompletionCallback( + (TaskRepository.TaskSettledCallback) + (rc, taskId, agentId, sessionId, status, result, error) -> + callback.complete( + new TaskDelivery( + taskId, agentId, status, result, error, null))); + repo.putTask( + RuntimeContext.empty(), + "remote-failure", + "remote-worker", + "remote-session", + new TaskRunSpec.RemoteTaskRunSpec( + "http://remote.test", + Map.of(), + "remote-worker", + "do work", + RemoteSubmitContext.empty())); + TaskDelivery delivery = callback.get(5, TimeUnit.SECONDS); + assertEquals(TaskStatus.FAILED, delivery.status()); + assertEquals("remote execution error", delivery.errorMessage()); + assertNull(delivery.result()); + } + @Test void remoteTask_togglesAwaitingConfirm_thenFiresCompletionOnSuccess() throws Exception { AtomicInteger statusCalls = new AtomicInteger(); @@ -72,8 +109,7 @@ void remoteTask_togglesAwaitingConfirm_thenFiresCompletionOnSuccess() throws Exc AtomicReference completedResult = new AtomicReference<>(); repo.setCompletionCallback( - (rc, taskId, subAgentId, sessionId, status, result, errorMessage) -> - completedResult.set(result)); + (rc, taskId, subAgentId, sessionId, result) -> completedResult.set(result)); String session = "sess-remote"; String taskId = "task-remote-hitl"; diff --git a/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryTest.java b/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryTest.java index 9ca704704e..82a62137a6 100644 --- a/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryTest.java +++ b/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryTest.java @@ -29,6 +29,8 @@ import io.agentscope.harness.agent.filesystem.remote.store.NamespaceFactory; import io.agentscope.harness.agent.filesystem.spec.RemoteFilesystemSpec; import io.agentscope.harness.agent.workspace.WorkspaceManager; +import java.net.URL; +import java.net.URLClassLoader; import java.nio.file.Files; import java.nio.file.Path; import java.time.Duration; @@ -37,9 +39,13 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import javax.tools.ToolProvider; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; @@ -175,18 +181,18 @@ void putTask_writesFailedOnException() throws Exception { @Test @DisplayName("completion callback receives FAILED status and error message when task throws") void completionCallback_receivesFailedStatusAndError() throws Exception { - java.util.concurrent.atomic.AtomicReference status = - new java.util.concurrent.atomic.AtomicReference<>(); - java.util.concurrent.atomic.AtomicReference result = - new java.util.concurrent.atomic.AtomicReference<>(); - java.util.concurrent.atomic.AtomicReference error = - new java.util.concurrent.atomic.AtomicReference<>(); + CompletableFuture callback = new CompletableFuture<>(); repo.setCompletionCallback( - (rc, taskId, subAgentId, sessionId, cbStatus, cbResult, cbError) -> { - status.set(cbStatus); - result.set(cbResult); - error.set(cbError); - }); + (TaskRepository.TaskSettledCallback) + (rc, taskId, subAgentId, sessionId, status, result, errorMessage) -> + callback.complete( + new TaskDelivery( + taskId, + subAgentId, + status, + result, + errorMessage, + null))); repo.putTask( RuntimeContext.empty(), @@ -198,28 +204,27 @@ void completionCallback_receivesFailedStatusAndError() throws Exception { throw new RuntimeException("callback failure detail"); })); - awaitCondition(() -> status.get() != null); - - assertEquals(TaskStatus.FAILED, status.get()); - assertEquals(null, result.get()); - assertTrue(error.get().contains("callback failure detail")); + TaskDelivery delivery = callback.get(5, TimeUnit.SECONDS); + assertEquals(TaskStatus.FAILED, delivery.status()); + assertNull(delivery.result()); + assertEquals("callback failure detail", delivery.errorMessage()); } @Test @DisplayName("completion callback receives COMPLETED status and result on success") void completionCallback_receivesCompletedStatusAndResult() throws Exception { - java.util.concurrent.atomic.AtomicReference status = - new java.util.concurrent.atomic.AtomicReference<>(); - java.util.concurrent.atomic.AtomicReference result = - new java.util.concurrent.atomic.AtomicReference<>(); - java.util.concurrent.atomic.AtomicReference error = - new java.util.concurrent.atomic.AtomicReference<>(); + CompletableFuture callback = new CompletableFuture<>(); repo.setCompletionCallback( - (rc, taskId, subAgentId, sessionId, cbStatus, cbResult, cbError) -> { - status.set(cbStatus); - result.set(cbResult); - error.set(cbError); - }); + (TaskRepository.TaskSettledCallback) + (rc, taskId, subAgentId, sessionId, status, result, errorMessage) -> + callback.complete( + new TaskDelivery( + taskId, + subAgentId, + status, + result, + errorMessage, + null))); repo.putTask( RuntimeContext.empty(), @@ -228,11 +233,161 @@ void completionCallback_receivesCompletedStatusAndResult() throws Exception { "sess-callback", new TaskRunSpec.LocalTaskRunSpec(() -> "delivered")); - awaitCondition(() -> status.get() != null); + TaskDelivery delivery = callback.get(5, TimeUnit.SECONDS); + assertEquals(TaskStatus.COMPLETED, delivery.status()); + assertEquals("delivered", delivery.result()); + assertNull(delivery.errorMessage()); + } + + @Test + void legacyCallbackReceivesSuccessAndFailure() throws Exception { + CompletableFuture callback = new CompletableFuture<>(); + repo.setCompletionCallback( + (rc, taskId, subAgentId, sessionId, result) -> callback.complete(result)); + repo.putTask( + RuntimeContext.empty(), + "legacy-success", + "worker", + "session", + new TaskRunSpec.LocalTaskRunSpec(() -> "legacy result")); + assertEquals("legacy result", callback.get(5, TimeUnit.SECONDS)); + + CompletableFuture failure = new CompletableFuture<>(); + repo.setCompletionCallback( + (rc, taskId, subAgentId, sessionId, result) -> failure.complete(result)); + repo.putTask( + RuntimeContext.empty(), + "legacy-failure", + "worker", + "session", + new TaskRunSpec.LocalTaskRunSpec( + () -> { + throw new IllegalStateException("legacy error"); + })); + assertNull(failure.get(5, TimeUnit.SECONDS)); + } + + @Test + void callbacksCompiledAgainstFiveArgumentApiRemainBinaryCompatible() throws Exception { + Path source = Files.createDirectories(tempDir.resolve("legacy-source")); + Path output = Files.createDirectories(tempDir.resolve("legacy-classes")); + Path api = source.resolve("TaskRepository.java"); + Files.writeString( + api, + """ + package io.agentscope.harness.agent.subagent.task; + import io.agentscope.core.agent.RuntimeContext; + public interface TaskRepository { + @FunctionalInterface + interface TaskCompletionCallback { + void onCompleted(RuntimeContext rc, String taskId, String subAgentId, + String sessionId, String result); + } + } + """); + Path client = source.resolve("LegacyCallbacks.java"); + Files.writeString( + client, + """ + package compat; + import io.agentscope.core.agent.RuntimeContext; + import io.agentscope.harness.agent.subagent.task.TaskRepository.TaskCompletionCallback; + public class LegacyCallbacks { + public static String result; + public static TaskCompletionCallback callback() { + return (rc, taskId, agentId, sessionId, value) -> result = value; + } + public static void invoke(TaskCompletionCallback callback, String value) { + callback.onCompleted(RuntimeContext.empty(), "task", "worker", "session", value); + } + } + """); + assertEquals( + 0, + ToolProvider.getSystemJavaCompiler() + .run( + null, + null, + null, + "--release", + "17", + "-classpath", + System.getProperty("java.class.path"), + "-d", + output.toString(), + api.toString(), + client.toString())); + try (var loader = + new URLClassLoader( + new URL[] {output.toUri().toURL()}, getClass().getClassLoader())) { + Class legacy = loader.loadClass("compat.LegacyCallbacks"); + var callback = + (TaskRepository.TaskCompletionCallback) + legacy.getMethod("callback").invoke(null); + callback.onSettled( + RuntimeContext.empty(), + "task", + "worker", + "session", + TaskStatus.COMPLETED, + "new result", + null); + assertEquals("new result", legacy.getField("result").get(null)); + callback.onSettled( + RuntimeContext.empty(), + "task", + "worker", + "session", + TaskStatus.FAILED, + null, + "new error"); + assertNull(legacy.getField("result").get(null)); + + AtomicReference status = new AtomicReference<>(); + TaskRepository.TaskSettledCallback settled = + (rc, taskId, agentId, sessionId, state, result, error) -> status.set(state); + var invoke = + legacy.getMethod( + "invoke", TaskRepository.TaskCompletionCallback.class, String.class); + invoke.invoke(null, settled, "old result"); + assertEquals(TaskStatus.COMPLETED, status.get()); + invoke.invoke(null, settled, null); + assertEquals(TaskStatus.FAILED, status.get()); + } + } - assertEquals(TaskStatus.COMPLETED, status.get()); - assertEquals("delivered", result.get()); - assertEquals(null, error.get()); + @Test + void adoptedFutureDeliversAuthoritativeFailureAndEmptySuccess() throws Exception { + for (boolean fails : List.of(false, true)) { + CompletableFuture callback = new CompletableFuture<>(); + repo.setCompletionCallback( + (TaskRepository.TaskSettledCallback) + (rc, taskId, subAgentId, sessionId, status, result, errorMessage) -> + callback.complete( + new TaskDelivery( + taskId, + subAgentId, + status, + result, + errorMessage, + null))); + CompletableFuture future = new CompletableFuture<>(); + repo.putTask( + RuntimeContext.empty(), + "adopted-" + fails, + "worker", + "session", + new TaskRunSpec.AdoptedTaskRunSpec(future)); + if (fails) { + future.completeExceptionally(new IllegalStateException("adopted error")); + } else { + future.complete(null); + } + TaskDelivery delivery = callback.get(5, TimeUnit.SECONDS); + assertEquals(fails ? TaskStatus.FAILED : TaskStatus.COMPLETED, delivery.status()); + assertNull(delivery.result()); + assertEquals(fails ? "adopted error" : null, delivery.errorMessage()); + } } // ------------------------------------------------------------------ @@ -1023,8 +1178,7 @@ void cancellationListenersObservePersistedTerminalState() throws Exception { void executionOwnerCanSuppressWakeupWithoutLosingDurableDelivery() throws Exception { AtomicInteger wakeups = new AtomicInteger(); repo.setCompletionCallback( - (rc, taskId, agentId, sessionId, status, result, errorMessage) -> - wakeups.incrementAndGet()); + (rc, taskId, agentId, sessionId, result) -> wakeups.incrementAndGet()); RuntimeContext managed = RuntimeContext.builder() .sessionId("managed") diff --git a/docs/v2/en/docs/harness/subagent.md b/docs/v2/en/docs/harness/subagent.md index a0a2873d3a..91eb22245d 100644 --- a/docs/v2/en/docs/harness/subagent.md +++ b/docs/v2/en/docs/harness/subagent.md @@ -223,6 +223,8 @@ Background tasks delivered: The parent naturally responds or continues. This means **you do not** write "remember to poll task_output" in your prompt — that was the old way. +Message-bus notifications distinguish `FAILED` tasks from successful completion and include the execution error, not an empty business result. The five-argument `TaskRepository.TaskCompletionCallback` remains compatible; use `TaskRepository.TaskSettledCallback` with the same `setCompletionCallback` method to receive status and error details. Custom repositories should call `onSettled` after persisting the terminal state; legacy `onCompleted` calls retain their null-result failure convention but cannot supply error details. + ### Background task tools Behind the scenes, subagent lifecycle is split across two groups of tools: diff --git a/docs/v2/zh/docs/harness/subagent.md b/docs/v2/zh/docs/harness/subagent.md index a598e512b6..91799d09d9 100644 --- a/docs/v2/zh/docs/harness/subagent.md +++ b/docs/v2/zh/docs/harness/subagent.md @@ -216,6 +216,8 @@ RuntimeContext ctx = RuntimeContext.builder() 主 agent 看到这条 reminder 自然地回应或继续行动。这意味着你**不需要**在 prompt 里写"记得调 task_output 轮询"——那是旧版本的做法。 +消息总线通知会区分 `FAILED` 任务和正常完成,并携带执行错误,而不是空的业务结果。五参数 `TaskRepository.TaskCompletionCallback` 保持兼容;通过同一个 `setCompletionCallback` 方法注册 `TaskRepository.TaskSettledCallback` 可获取状态及错误。自定义任务仓库应在持久化终态后调用 `onSettled`;旧的 `onCompleted` 调用保留 null 结果表示失败的约定,但无法提供错误详情。 + ### 后台任务工具 子 agent 的生命周期背后由两组工具配合完成: From 86229e5be439b118a9a6bfe7189a38c027eb7a14 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A7=A3=E4=BC=9F?= Date: Fri, 20 Nov 2026 17:50:24 +0800 Subject: [PATCH 3/5] fix(harness): sanitize error summaries in subagent task hints Per maintainer feedback on #4102, notifications to the parent agent now carry a short, sanitized error summary: the raw exception message is reduced to its first line and truncated, since stack traces and long internal dumps can leak paths, endpoints, or credentials into the conversation prompt. The full message stays in the durable task record, reachable via task_output/task_list. Applies the same cap to the aggregated blocks in the delivery reminder, and documents the new behavior in both the v2 and dev docs sets. --- .../agent/middleware/SubagentsMiddleware.java | 36 +++++++++++++--- .../middleware/SubagentDeliveryTest.java | 24 +++++++++++ .../SubagentTaskSettledHintTest.java | 23 ++++++++++ .../task/WorkspaceTaskRepositoryTest.java | 42 +++++++++++++++++++ docs/dev/en/docs/harness/subagent.md | 2 + docs/dev/zh/docs/harness/subagent.md | 2 + docs/v2/en/docs/harness/subagent.md | 2 +- docs/v2/zh/docs/harness/subagent.md | 2 +- 8 files changed, 126 insertions(+), 7 deletions(-) diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/middleware/SubagentsMiddleware.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/middleware/SubagentsMiddleware.java index 24060c1d7d..39b28689ec 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/middleware/SubagentsMiddleware.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/middleware/SubagentsMiddleware.java @@ -92,6 +92,9 @@ public class SubagentsMiddleware implements HarnessRuntimeMiddleware { */ static final int MAX_DELIVERIES_PER_REMINDER = 10; + /** Cap for the error summary embedded in a settled-task hint; details stay in the task record. */ + static final int ERROR_SUMMARY_MAX_LENGTH = 200; + // @formatter:off private static final String SUBAGENT_SECTION_TEMPLATE = """ @@ -302,6 +305,10 @@ public TaskRepository getTaskRepository() { *

Failed tasks must not be announced with completion wording: the parent model would treat * the run as a delivered (empty) business result instead of an infrastructure failure to retry * or escalate. Mirrors the task-delivery reminder's {@code } semantics.

+ * + *

The hint carries only a short, sanitized error summary — raw exception messages can be + * long and may leak internals (paths, endpoints, credentials) into the conversation. The full + * message stays in the durable task record, reachable via {@code task_output}.

*/ public static String taskSettledHintContent( String taskId, @@ -312,11 +319,11 @@ public static String taskSettledHintContent( if (status == TaskStatus.FAILED) { return String.format( "Background subagent task '%s' (agent=%s) FAILED and" - + " produced no result.\n\nError:\n\n%s\n\nThis is an execution" + + " produced no result.\n\nError summary: %s\n\nThis is an execution" + " failure, not a business conclusion. Use task_output(task_id=...," - + " block=false) or task_list() if you need the task" - + " record.", - taskId, subAgentId, errorMessage != null ? errorMessage : "(no error message)"); + + " block=false) or task_list() for the full task record and error" + + " details.", + taskId, subAgentId, sanitizeErrorSummary(errorMessage)); } return String.format( "Background subagent task '%s' (agent=%s) has completed." @@ -324,6 +331,25 @@ public static String taskSettledHintContent( taskId, subAgentId, result != null ? result : "(no output)"); } + /** + * Reduces a raw exception message to a single-line summary capped at {@value + * #ERROR_SUMMARY_MAX_LENGTH} characters, so stack traces and long internal dumps never reach + * the conversation prompt. + */ + static String sanitizeErrorSummary(String errorMessage) { + if (errorMessage == null || errorMessage.isBlank()) { + return "(no error message)"; + } + String firstLine = errorMessage.strip().split("\\R", 2)[0].strip(); + if (firstLine.isEmpty()) { + return "(no error message)"; + } + if (firstLine.length() > ERROR_SUMMARY_MAX_LENGTH) { + firstLine = firstLine.substring(0, ERROR_SUMMARY_MAX_LENGTH) + "..."; + } + return firstLine; + } + /** * Wires a {@link io.agentscope.harness.agent.bus.MessageBus} so that background task completions are * pushed to the session inbox and a wakeup signal is enqueued. This enables the @@ -577,7 +603,7 @@ static Msg buildDeliveryReminder(List deliveries) { } case FAILED -> { sb.append("\n"); - sb.append(d.errorMessage() != null ? d.errorMessage() : "(no error message)"); + sb.append(sanitizeErrorSummary(d.errorMessage())); sb.append("\n\n"); } case CANCELLED -> sb.append("Task was cancelled before producing a result.\n"); diff --git a/agentscope-harness/src/test/java/io/agentscope/harness/agent/middleware/SubagentDeliveryTest.java b/agentscope-harness/src/test/java/io/agentscope/harness/agent/middleware/SubagentDeliveryTest.java index 32b0d8dd0f..18521a3dee 100644 --- a/agentscope-harness/src/test/java/io/agentscope/harness/agent/middleware/SubagentDeliveryTest.java +++ b/agentscope-harness/src/test/java/io/agentscope/harness/agent/middleware/SubagentDeliveryTest.java @@ -16,6 +16,7 @@ package io.agentscope.harness.agent.middleware; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -156,6 +157,29 @@ void reminder_failedRendersTaskErrorBlock() { assertTrue(text.contains("boom")); } + @Test + void reminder_failedErrorIsSanitizedToASingleTruncatedLine() { + Msg msg = + SubagentsMiddleware.buildDeliveryReminder( + List.of( + delivery( + "tx", + TaskStatus.FAILED, + null, + "first line " + + "x".repeat(300) + + "\n\tat leaked.Frame(internal/File.java:42)"))); + String text = textOf(msg); + assertTrue(text.contains("first line"), text); + int summaryStart = text.indexOf("\n") + "\n".length(); + int summaryEnd = text.indexOf("\n"); + String summary = text.substring(summaryStart, summaryEnd); + assertEquals( + SubagentsMiddleware.ERROR_SUMMARY_MAX_LENGTH + "...".length(), summary.length()); + assertFalse(summary.contains("\n")); + assertFalse(text.contains("leaked.Frame"), text); + } + @Test void reminder_cancelledRendersCancelledLine() { Msg msg = diff --git a/agentscope-harness/src/test/java/io/agentscope/harness/agent/middleware/SubagentTaskSettledHintTest.java b/agentscope-harness/src/test/java/io/agentscope/harness/agent/middleware/SubagentTaskSettledHintTest.java index ba2ec37188..01aa8ffbfa 100644 --- a/agentscope-harness/src/test/java/io/agentscope/harness/agent/middleware/SubagentTaskSettledHintTest.java +++ b/agentscope-harness/src/test/java/io/agentscope/harness/agent/middleware/SubagentTaskSettledHintTest.java @@ -91,11 +91,34 @@ void failedTaskIsAnnouncedWithErrorNotCompletion() { assertTrue(hint.contains("FAILED"), hint); assertTrue(hint.contains("boom: rate limited"), hint); + assertTrue(hint.contains("Error summary: boom: rate limited"), hint); assertTrue(hint.contains("execution failure, not a business conclusion"), hint); assertFalse(hint.contains("has completed"), hint); assertFalse(hint.contains("Result:"), hint); } + @Test + void multilineErrorIsReducedToASingleTruncatedLine() { + String message = + "first line with the cause " + + "x".repeat(300) + + "\n\tat internal.stack.Frame1(internal/File.java:42)\n" + + "secret-token-from-later-frame"; + String hint = + SubagentsMiddleware.taskSettledHintContent( + "task_1", "worker", TaskStatus.FAILED, null, message); + + assertTrue(hint.contains("first line with the cause"), hint); + String summary = + hint.substring( + hint.indexOf("Error summary: ") + "Error summary: ".length(), + hint.indexOf("\n\nThis is an execution failure")); + assertEquals(SubagentsMiddleware.ERROR_SUMMARY_MAX_LENGTH + "...".length(), summary.length()); + assertFalse(summary.contains("\n"), summary); + assertFalse(hint.contains("internal.stack.Frame1"), hint); + assertFalse(hint.contains("secret-token-from-later-frame"), hint); + } + @Test void completedTaskKeepsCompletionWording() { String hint = diff --git a/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryTest.java b/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryTest.java index 82a62137a6..528801a550 100644 --- a/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryTest.java +++ b/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryTest.java @@ -390,6 +390,48 @@ void adoptedFutureDeliversAuthoritativeFailureAndEmptySuccess() throws Exception } } + @Test + void suppressedSettledFailuresRetainDurableErrors() throws Exception { + AtomicInteger callbacks = new AtomicInteger(); + repo.setCompletionCallback( + (TaskRepository.TaskSettledCallback) + (rc, taskId, agentId, sessionId, status, result, error) -> + callbacks.incrementAndGet()); + for (boolean adopted : List.of(false, true)) { + String sessionId = "suppressed-failure-" + adopted; + RuntimeContext context = + RuntimeContext.builder() + .sessionId(sessionId) + .put(TaskRepository.SUPPRESS_COMPLETION_CALLBACK, true) + .build(); + CompletableFuture future = new CompletableFuture<>(); + TaskRunSpec spec = + adopted + ? new TaskRunSpec.AdoptedTaskRunSpec(future) + : new TaskRunSpec.LocalTaskRunSpec( + () -> { + throw new IllegalStateException( + "suppressed execution error"); + }); + BackgroundTask task = + repo.putTask(context, "suppressed-task", "worker", sessionId, spec); + if (adopted) { + future.completeExceptionally( + new IllegalStateException("suppressed execution error")); + } + assertTrue(task.waitForCompletion(5000)); + assertEquals(0, callbacks.get()); + List deliveries = repo.findPendingDeliveries(context, sessionId); + assertEquals(1, deliveries.size()); + TaskDelivery delivery = deliveries.get(0); + assertEquals("suppressed-task", delivery.taskId()); + assertEquals("worker", delivery.agentId()); + assertEquals(TaskStatus.FAILED, delivery.status()); + assertNull(delivery.result()); + assertEquals("suppressed execution error", delivery.errorMessage()); + } + } + // ------------------------------------------------------------------ // Cross-node fallback: no local future // ------------------------------------------------------------------ diff --git a/docs/dev/en/docs/harness/subagent.md b/docs/dev/en/docs/harness/subagent.md index 4f13770f21..9f4763fc66 100644 --- a/docs/dev/en/docs/harness/subagent.md +++ b/docs/dev/en/docs/harness/subagent.md @@ -158,6 +158,8 @@ Background tasks delivered: The parent naturally responds or continues. This means **you do not** write "remember to poll task_output" in your prompt — that was the old way. +Message-bus notifications distinguish `FAILED` tasks from successful completion and carry a short, sanitized error summary (a single truncated line) rather than the raw exception message; the full error remains available through the task record via `task_output`. The five-argument `TaskRepository.TaskCompletionCallback` remains compatible; use `TaskRepository.TaskSettledCallback` with the same `setCompletionCallback` method to receive status and error details. Custom repositories should call `onSettled` after persisting the terminal state; legacy `onCompleted` calls retain their null-result failure convention but cannot supply error details. + ### Background task tools Behind the scenes, subagent lifecycle is split across two groups of tools: diff --git a/docs/dev/zh/docs/harness/subagent.md b/docs/dev/zh/docs/harness/subagent.md index 565554c5c4..59e7a04af0 100644 --- a/docs/dev/zh/docs/harness/subagent.md +++ b/docs/dev/zh/docs/harness/subagent.md @@ -156,6 +156,8 @@ RuntimeContext ctx = RuntimeContext.builder() 主 agent 看到这条 reminder 自然地回应或继续行动。这意味着你**不需要**在 prompt 里写"记得调 task_output 轮询"——那是旧版本的做法。 +消息总线通知会区分 `FAILED` 任务和正常完成,并携带简短、脱敏的错误摘要(截断为单行),而不是原始异常消息或空的业务结果;完整错误仍可通过 `task_output` 从任务记录中获取。五参数 `TaskRepository.TaskCompletionCallback` 保持兼容;通过同一个 `setCompletionCallback` 方法注册 `TaskRepository.TaskSettledCallback` 可获取状态及错误。自定义任务仓库应在持久化终态后调用 `onSettled`;旧的 `onCompleted` 调用保留 null 结果表示失败的约定,但无法提供错误详情。 + ### 后台任务工具 子 agent 的生命周期背后由两组工具配合完成: diff --git a/docs/v2/en/docs/harness/subagent.md b/docs/v2/en/docs/harness/subagent.md index 91eb22245d..8cf45e9d9d 100644 --- a/docs/v2/en/docs/harness/subagent.md +++ b/docs/v2/en/docs/harness/subagent.md @@ -223,7 +223,7 @@ Background tasks delivered: The parent naturally responds or continues. This means **you do not** write "remember to poll task_output" in your prompt — that was the old way. -Message-bus notifications distinguish `FAILED` tasks from successful completion and include the execution error, not an empty business result. The five-argument `TaskRepository.TaskCompletionCallback` remains compatible; use `TaskRepository.TaskSettledCallback` with the same `setCompletionCallback` method to receive status and error details. Custom repositories should call `onSettled` after persisting the terminal state; legacy `onCompleted` calls retain their null-result failure convention but cannot supply error details. +Message-bus notifications distinguish `FAILED` tasks from successful completion and carry a short, sanitized error summary (a single truncated line) rather than the raw exception message; the full error remains available through the task record via `task_output`. The five-argument `TaskRepository.TaskCompletionCallback` remains compatible; use `TaskRepository.TaskSettledCallback` with the same `setCompletionCallback` method to receive status and error details. Custom repositories should call `onSettled` after persisting the terminal state; legacy `onCompleted` calls retain their null-result failure convention but cannot supply error details. ### Background task tools diff --git a/docs/v2/zh/docs/harness/subagent.md b/docs/v2/zh/docs/harness/subagent.md index 91799d09d9..3a49498dfc 100644 --- a/docs/v2/zh/docs/harness/subagent.md +++ b/docs/v2/zh/docs/harness/subagent.md @@ -216,7 +216,7 @@ RuntimeContext ctx = RuntimeContext.builder() 主 agent 看到这条 reminder 自然地回应或继续行动。这意味着你**不需要**在 prompt 里写"记得调 task_output 轮询"——那是旧版本的做法。 -消息总线通知会区分 `FAILED` 任务和正常完成,并携带执行错误,而不是空的业务结果。五参数 `TaskRepository.TaskCompletionCallback` 保持兼容;通过同一个 `setCompletionCallback` 方法注册 `TaskRepository.TaskSettledCallback` 可获取状态及错误。自定义任务仓库应在持久化终态后调用 `onSettled`;旧的 `onCompleted` 调用保留 null 结果表示失败的约定,但无法提供错误详情。 +消息总线通知会区分 `FAILED` 任务和正常完成,并携带简短、脱敏的错误摘要(截断为单行),而不是原始异常消息或空的业务结果;完整错误仍可通过 `task_output` 从任务记录中获取。五参数 `TaskRepository.TaskCompletionCallback` 保持兼容;通过同一个 `setCompletionCallback` 方法注册 `TaskRepository.TaskSettledCallback` 可获取状态及错误。自定义任务仓库应在持久化终态后调用 `onSettled`;旧的 `onCompleted` 调用保留 null 结果表示失败的约定,但无法提供错误详情。 ### 后台任务工具 From 8fd178649746b5f420d32dee5097fcca95d92c6d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A7=A3=E4=BC=9F?= Date: Tue, 24 Nov 2026 09:42:08 +0800 Subject: [PATCH 4/5] fix(harness): notify the persisted terminal state and drop raw errors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review follow-up on #4102, fixing two reproduced issues: 1. Cancelled tasks must not announce FAILED. updateStatus now returns the status actually persisted, and every settlement goes through settleAndNotify, which fires the callback with that effective status. Cancelling an adopted future (or a local supplier failing after cancellation) enters the exception branch, but the record — and now the notification — stays CANCELLED, so the parent agent no longer risks retrying a task the user just cancelled. Settled hints gained a CANCELLED wording. Covered by tests for the adopted+cancelTask path and the local post-cancel failure path. 2. Automatic notifications no longer embed any part of the exception message: the first line of a single-line error still leaked verbatim. Hints and blocks now carry only the task id, the terminal status, and a fixed error category; the raw error remains in the durable task record, reachable via task_output. The truncating sanitizer is removed along with its length cap. Also fixes the Spotless violations in the settled-hint tests. --- .../harness/agent/HarnessAgent.java | 6 +- .../agent/middleware/SubagentsMiddleware.java | 61 +++++------- .../agent/subagent/task/TaskRepository.java | 9 +- .../task/WorkspaceTaskRepository.java | 63 ++++++++----- .../middleware/SubagentDeliveryTest.java | 31 ++----- .../SubagentTaskSettledHintTest.java | 53 ++++------- .../task/WorkspaceTaskRepositoryTest.java | 92 +++++++++++++++++++ docs/dev/en/docs/harness/subagent.md | 2 +- docs/dev/zh/docs/harness/subagent.md | 2 +- docs/v2/en/docs/harness/subagent.md | 2 +- docs/v2/zh/docs/harness/subagent.md | 2 +- 11 files changed, 194 insertions(+), 129 deletions(-) diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java index d1f1257353..81be183465 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java @@ -2857,11 +2857,7 @@ private static void wireTaskRepositoryMessageBus( String hintContent = io.agentscope.harness.agent.middleware.SubagentsMiddleware .taskSettledHintContent( - taskId, - subAgentId, - status, - result, - errorMessage); + taskId, subAgentId, status, result); String hintId = java.util.UUID.randomUUID().toString().replace("-", ""); bus.inboxPush( diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/middleware/SubagentsMiddleware.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/middleware/SubagentsMiddleware.java index 39b28689ec..3a8e9710e8 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/middleware/SubagentsMiddleware.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/middleware/SubagentsMiddleware.java @@ -92,9 +92,6 @@ public class SubagentsMiddleware implements HarnessRuntimeMiddleware { */ static final int MAX_DELIVERIES_PER_REMINDER = 10; - /** Cap for the error summary embedded in a settled-task hint; details stay in the task record. */ - static final int ERROR_SUMMARY_MAX_LENGTH = 200; - // @formatter:off private static final String SUBAGENT_SECTION_TEMPLATE = """ @@ -306,24 +303,31 @@ public TaskRepository getTaskRepository() { * the run as a delivered (empty) business result instead of an infrastructure failure to retry * or escalate. Mirrors the task-delivery reminder's {@code } semantics.

* - *

The hint carries only a short, sanitized error summary — raw exception messages can be - * long and may leak internals (paths, endpoints, credentials) into the conversation. The full - * message stays in the durable task record, reachable via {@code task_output}.

+ *

Automatic notifications identify the task and its terminal state with a fixed error + * category — they never embed the raw exception message, which can leak internals (paths, + * endpoints, credentials) into the conversation. The full message stays in the durable task + * record, reachable via {@code task_output}.

*/ public static String taskSettledHintContent( - String taskId, - String subAgentId, - TaskStatus status, - String result, - String errorMessage) { + String taskId, String subAgentId, TaskStatus status, String result) { if (status == TaskStatus.FAILED) { return String.format( "Background subagent task '%s' (agent=%s) FAILED and" - + " produced no result.\n\nError summary: %s\n\nThis is an execution" - + " failure, not a business conclusion. Use task_output(task_id=...," - + " block=false) or task_list() for the full task record and error" + + " produced no result. Error category: execution failure. This is an" + + " execution failure, not a business conclusion; error details are" + + " omitted from notifications because they may contain sensitive" + + " data. Use task_output(task_id=..., block=false) or task_list() to" + + " retrieve the full task record and error" + " details.", - taskId, subAgentId, sanitizeErrorSummary(errorMessage)); + taskId, subAgentId); + } + if (status == TaskStatus.CANCELLED) { + return String.format( + "Background subagent task '%s' (agent=%s) was CANCELLED and" + + " produced no result. Use task_output(task_id=..., block=false) or" + + " task_list() if you need the task" + + " record.", + taskId, subAgentId); } return String.format( "Background subagent task '%s' (agent=%s) has completed." @@ -331,25 +335,6 @@ public static String taskSettledHintContent( taskId, subAgentId, result != null ? result : "(no output)"); } - /** - * Reduces a raw exception message to a single-line summary capped at {@value - * #ERROR_SUMMARY_MAX_LENGTH} characters, so stack traces and long internal dumps never reach - * the conversation prompt. - */ - static String sanitizeErrorSummary(String errorMessage) { - if (errorMessage == null || errorMessage.isBlank()) { - return "(no error message)"; - } - String firstLine = errorMessage.strip().split("\\R", 2)[0].strip(); - if (firstLine.isEmpty()) { - return "(no error message)"; - } - if (firstLine.length() > ERROR_SUMMARY_MAX_LENGTH) { - firstLine = firstLine.substring(0, ERROR_SUMMARY_MAX_LENGTH) + "..."; - } - return firstLine; - } - /** * Wires a {@link io.agentscope.harness.agent.bus.MessageBus} so that background task completions are * pushed to the session inbox and a wakeup signal is enqueued. This enables the @@ -373,8 +358,7 @@ public SubagentsMiddleware wireMessageBus( (rc, taskId, subAgentId, sessionId, status, result, errorMessage) -> { String userId = rc != null ? rc.getUserId() : null; String hintContent = - taskSettledHintContent( - taskId, subAgentId, status, result, errorMessage); + taskSettledHintContent(taskId, subAgentId, status, result); String hintId = java.util.UUID.randomUUID().toString().replace("-", ""); java.util.Map hintPayload = java.util.Map.of( @@ -603,7 +587,10 @@ static Msg buildDeliveryReminder(List deliveries) { } case FAILED -> { sb.append("\n"); - sb.append(sanitizeErrorSummary(d.errorMessage())); + sb.append( + "execution failure; error details are omitted from notifications" + + " because they may contain sensitive data — call" + + " task_output for the full record"); sb.append("\n\n"); } case CANCELLED -> sb.append("Task was cancelled before producing a result.\n"); diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/TaskRepository.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/TaskRepository.java index 015ed288a9..328c33b965 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/TaskRepository.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/TaskRepository.java @@ -126,10 +126,11 @@ default boolean isDelivered(RuntimeContext rc, String sessionId, String taskId) } /** - * Registers a callback invoked when any task reaches a terminal state (COMPLETED or FAILED). - * Used by {@link io.agentscope.harness.agent.middleware.SubagentsMiddleware} to push results - * to the session inbox and enqueue a wakeup signal. The {@code result} argument is {@code null} - * for failed tasks. Use {@link TaskSettledCallback} to also receive terminal status and errors. + * Registers a callback invoked when any task reaches a terminal state (COMPLETED, FAILED, or + * CANCELLED). Used by {@link io.agentscope.harness.agent.middleware.SubagentsMiddleware} to + * push results to the session inbox and enqueue a wakeup signal. The {@code result} argument is + * {@code null} for failed and cancelled tasks. Use {@link TaskSettledCallback} to also receive + * terminal status and errors. * *

Callers retaining execution ownership can set {@link #SUPPRESS_COMPLETION_CALLBACK} * in their RuntimeContext to suppress inbox/wakeup callbacks while preserving durable results. diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepository.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepository.java index 59cd708c72..12898ec6a2 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepository.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepository.java @@ -317,23 +317,20 @@ public BackgroundTask putTask( : (cause != null ? cause.getClass().getSimpleName() : err.getClass().getSimpleName()); - updateStatus(capturedRc, sid, taskId, TaskStatus.FAILED, null, errMsg); - fireCompletionCallback( + settleAndNotify( capturedRc, + sid, taskId, subAgentId, - sid, TaskStatus.FAILED, null, errMsg); } else { - updateStatus( - capturedRc, sid, taskId, TaskStatus.COMPLETED, result, null); - fireCompletionCallback( + settleAndNotify( capturedRc, + sid, taskId, subAgentId, - sid, TaskStatus.COMPLETED, result, null); @@ -395,15 +392,11 @@ private String runLocalSupplier( markCancelled(rc, sessionId, taskId); return null; } - updateStatus(rc, sessionId, taskId, TaskStatus.COMPLETED, result, null); - fireCompletionCallback( - rc, taskId, subAgentId, sessionId, TaskStatus.COMPLETED, result, null); + settleAndNotify(rc, sessionId, taskId, subAgentId, TaskStatus.COMPLETED, result, null); return result; } catch (Exception e) { String errMsg = e.getMessage() != null ? e.getMessage() : e.getClass().getSimpleName(); - updateStatus(rc, sessionId, taskId, TaskStatus.FAILED, null, errMsg); - fireCompletionCallback( - rc, taskId, subAgentId, sessionId, TaskStatus.FAILED, null, errMsg); + settleAndNotify(rc, sessionId, taskId, subAgentId, TaskStatus.FAILED, null, errMsg); throw e instanceof RuntimeException re ? re : new RuntimeException(e); } } @@ -431,15 +424,13 @@ private String runRemoteTask( } String result = pollRemoteUntilDone(rc, sessionId, taskId, target); if (result != null) { - fireCompletionCallback( - rc, taskId, subAgentId, sessionId, TaskStatus.COMPLETED, result, null); + settleAndNotify( + rc, sessionId, taskId, subAgentId, TaskStatus.COMPLETED, result, null); } return result; } catch (Exception e) { String errMsg = e.getMessage() != null ? e.getMessage() : e.getClass().getSimpleName(); - updateStatus(rc, sessionId, taskId, TaskStatus.FAILED, null, errMsg); - fireCompletionCallback( - rc, taskId, subAgentId, sessionId, TaskStatus.FAILED, null, errMsg); + settleAndNotify(rc, sessionId, taskId, subAgentId, TaskStatus.FAILED, null, errMsg); throw e instanceof RuntimeException re ? re : new RuntimeException(e); } } @@ -872,7 +863,7 @@ record -> { return existing; } - private synchronized void updateStatus( + private synchronized TaskStatus updateStatus( RuntimeContext rc, String sessionId, String taskId, @@ -887,14 +878,14 @@ private synchronized void updateStatus( if (existing.isPresent() && existing.get().getStatus() != null && existing.get().getStatus().isTerminal()) { - return; + return existing.get().getStatus(); } // Guard 2: if cancellation has been requested but the workspace record has not yet reached // a terminal state (e.g. heartbeat races cancelTask()), refuse to persist non-terminal // updates. This stops the heartbeat from writing RUNNING back over a record whose // cancelRequested flag was just set by cancelTask(). if (!status.isTerminal() && existing.isPresent() && existing.get().isCancelRequested()) { - return; + return existing.get().getStatus(); } TaskRecord record = existing.orElseGet( @@ -913,6 +904,36 @@ private synchronized void updateStatus( record.setErrorMessage(error); } persistRecord(rc, sessionId, record); + return status; + } + + /** + * Persists a terminal state and fires the settlement callback with the status actually + * persisted. When cancellation races a settlement, {@link #updateStatus} keeps the record's + * CANCELLED status, so the callback must also report CANCELLED — announcing FAILED for a task + * the user just cancelled would invite the parent agent to retry it. + */ + private void settleAndNotify( + RuntimeContext rc, + String sessionId, + String taskId, + String subAgentId, + TaskStatus status, + String result, + String errorMessage) { + TaskStatus effective = updateStatus(rc, sessionId, taskId, status, result, errorMessage); + if (effective == null || !effective.isTerminal()) { + return; + } + boolean asPersisted = effective == status; + fireCompletionCallback( + rc, + taskId, + subAgentId, + sessionId, + effective, + asPersisted ? result : null, + asPersisted ? errorMessage : null); } private void markCancelled(RuntimeContext rc, String sessionId, String taskId) { diff --git a/agentscope-harness/src/test/java/io/agentscope/harness/agent/middleware/SubagentDeliveryTest.java b/agentscope-harness/src/test/java/io/agentscope/harness/agent/middleware/SubagentDeliveryTest.java index 18521a3dee..d17ff5b42f 100644 --- a/agentscope-harness/src/test/java/io/agentscope/harness/agent/middleware/SubagentDeliveryTest.java +++ b/agentscope-harness/src/test/java/io/agentscope/harness/agent/middleware/SubagentDeliveryTest.java @@ -147,18 +147,7 @@ void reminder_singleCompleted_rendersTaskResultBlock() { } @Test - void reminder_failedRendersTaskErrorBlock() { - Msg msg = - SubagentsMiddleware.buildDeliveryReminder( - List.of(delivery("tx", TaskStatus.FAILED, null, "boom"))); - String text = textOf(msg); - assertTrue(text.contains("state=\"error\"")); - assertTrue(text.contains("")); - assertTrue(text.contains("boom")); - } - - @Test - void reminder_failedErrorIsSanitizedToASingleTruncatedLine() { + void reminder_failedRendersFixedCategoryTaskErrorBlock() { Msg msg = SubagentsMiddleware.buildDeliveryReminder( List.of( @@ -166,18 +155,14 @@ void reminder_failedErrorIsSanitizedToASingleTruncatedLine() { "tx", TaskStatus.FAILED, null, - "first line " - + "x".repeat(300) - + "\n\tat leaked.Frame(internal/File.java:42)"))); + "auth failed: token=sk-live-secret-1234567890"))); String text = textOf(msg); - assertTrue(text.contains("first line"), text); - int summaryStart = text.indexOf("\n") + "\n".length(); - int summaryEnd = text.indexOf("\n"); - String summary = text.substring(summaryStart, summaryEnd); - assertEquals( - SubagentsMiddleware.ERROR_SUMMARY_MAX_LENGTH + "...".length(), summary.length()); - assertFalse(summary.contains("\n")); - assertFalse(text.contains("leaked.Frame"), text); + assertTrue(text.contains("state=\"error\"")); + assertTrue(text.contains("")); + assertTrue(text.contains("execution failure"), text); + assertTrue(text.contains("task_output"), text); + assertFalse(text.contains("boom")); + assertFalse(text.contains("sk-live-secret"), text); } @Test diff --git a/agentscope-harness/src/test/java/io/agentscope/harness/agent/middleware/SubagentTaskSettledHintTest.java b/agentscope-harness/src/test/java/io/agentscope/harness/agent/middleware/SubagentTaskSettledHintTest.java index 01aa8ffbfa..04060a5ca0 100644 --- a/agentscope-harness/src/test/java/io/agentscope/harness/agent/middleware/SubagentTaskSettledHintTest.java +++ b/agentscope-harness/src/test/java/io/agentscope/harness/agent/middleware/SubagentTaskSettledHintTest.java @@ -57,7 +57,7 @@ class SubagentTaskSettledHintTest { private static final String SESSION_ID = "original-session"; private static final String TASK_ID = "task_settled"; private static final String SUBAGENT_ID = "image-reader"; - private static final String ERROR = "boom: rate limited"; + private static final String ERROR = "auth failed: token=sk-live-secret-1234567890"; private static final String OUTPUT = "done: 3 findings"; @TempDir Path tempDir; @@ -84,65 +84,46 @@ void closeResources() { } @Test - void failedTaskIsAnnouncedWithErrorNotCompletion() { + void failedTaskIsAnnouncedWithFixedCategoryNotRawError() { String hint = SubagentsMiddleware.taskSettledHintContent( - "task_1", "image-reader", TaskStatus.FAILED, null, "boom: rate limited"); + "task_1", "image-reader", TaskStatus.FAILED, null); assertTrue(hint.contains("FAILED"), hint); - assertTrue(hint.contains("boom: rate limited"), hint); - assertTrue(hint.contains("Error summary: boom: rate limited"), hint); + assertTrue(hint.contains("Error category: execution failure"), hint); assertTrue(hint.contains("execution failure, not a business conclusion"), hint); + assertTrue(hint.contains("task_output(task_id=..., block=false)"), hint); assertFalse(hint.contains("has completed"), hint); assertFalse(hint.contains("Result:"), hint); } @Test - void multilineErrorIsReducedToASingleTruncatedLine() { - String message = - "first line with the cause " - + "x".repeat(300) - + "\n\tat internal.stack.Frame1(internal/File.java:42)\n" - + "secret-token-from-later-frame"; + void cancelledTaskIsAnnouncedAsCancelled() { String hint = SubagentsMiddleware.taskSettledHintContent( - "task_1", "worker", TaskStatus.FAILED, null, message); - - assertTrue(hint.contains("first line with the cause"), hint); - String summary = - hint.substring( - hint.indexOf("Error summary: ") + "Error summary: ".length(), - hint.indexOf("\n\nThis is an execution failure")); - assertEquals(SubagentsMiddleware.ERROR_SUMMARY_MAX_LENGTH + "...".length(), summary.length()); - assertFalse(summary.contains("\n"), summary); - assertFalse(hint.contains("internal.stack.Frame1"), hint); - assertFalse(hint.contains("secret-token-from-later-frame"), hint); + "task_1", "image-reader", TaskStatus.CANCELLED, null); + + assertTrue(hint.contains("CANCELLED"), hint); + assertFalse(hint.contains("FAILED"), hint); + assertFalse(hint.contains("has completed"), hint); + assertFalse(hint.contains("Result:"), hint); } @Test void completedTaskKeepsCompletionWording() { String hint = SubagentsMiddleware.taskSettledHintContent( - "task_1", "image-reader", TaskStatus.COMPLETED, "done: 3 findings", null); + "task_1", "image-reader", TaskStatus.COMPLETED, "done: 3 findings"); assertTrue(hint.contains("has completed"), hint); assertTrue(hint.contains("done: 3 findings"), hint); assertFalse(hint.contains("FAILED"), hint); } - @Test - void failedTaskWithoutMessageStillSaysFailed() { - String hint = - SubagentsMiddleware.taskSettledHintContent( - "task_1", "worker", TaskStatus.FAILED, null, null); - - assertTrue(hint.contains("FAILED"), hint); - assertTrue(hint.contains("(no error message)"), hint); - } - @ParameterizedTest @EnumSource(EntryMode.class) - void failedTaskWiringPushesErrorAndWakesOriginalSession(EntryMode mode) throws Exception { + void failedTaskWiringNotifiesFixedCategoryAndWakesOriginalSession(EntryMode mode) + throws Exception { wire(mode); RuntimeContext rc = runtimeContext(false); BackgroundTask task = submitFailingTask(rc); @@ -153,7 +134,9 @@ void failedTaskWiringPushesErrorAndWakesOriginalSession(EntryMode mode) throws E assertEquals(ERROR, task.getError().getMessage()); assertDurableResult(rc, TaskStatus.FAILED, null, ERROR); assertTrue(hint.contains("FAILED"), hint); - assertTrue(hint.contains(ERROR), hint); + assertTrue(hint.contains("Error category: execution failure"), hint); + assertFalse(hint.contains(ERROR), hint); + assertFalse(hint.contains("sk-live"), hint); assertFalse(hint.contains("has completed"), hint); assertFalse(hint.contains("Result:"), hint); } diff --git a/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryTest.java b/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryTest.java index 528801a550..1a1a55f8be 100644 --- a/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryTest.java +++ b/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryTest.java @@ -390,6 +390,98 @@ void adoptedFutureDeliversAuthoritativeFailureAndEmptySuccess() throws Exception } } + @Test + void cancelledAdoptedTaskNotifiesCancelledNotFailed() throws Exception { + // Reviewer repro: cancelling an adopted future enters whenComplete's exception branch, + // but the callback must report the persisted CANCELLED terminal state, never FAILED. + CompletableFuture callback = new CompletableFuture<>(); + repo.setCompletionCallback( + (TaskRepository.TaskSettledCallback) + (rc, taskId, subAgentId, sessionId, status, result, errorMessage) -> + callback.complete( + new TaskDelivery( + taskId, + subAgentId, + status, + result, + errorMessage, + null))); + CompletableFuture future = new CompletableFuture<>(); + BackgroundTask task = + repo.putTask( + RuntimeContext.empty(), + "adopted-cancel", + "worker", + "session", + new TaskRunSpec.AdoptedTaskRunSpec(future)); + + assertTrue(repo.cancelTask(RuntimeContext.empty(), "session", "adopted-cancel")); + assertTrue(task.waitForCompletion(5_000), "task did not settle within 5 seconds"); + + TaskDelivery delivery = callback.get(5, TimeUnit.SECONDS); + assertEquals(TaskStatus.CANCELLED, delivery.status()); + assertNull(delivery.result()); + assertNull(delivery.errorMessage()); + var record = + workspaceManager + .readTaskRecord( + RuntimeContext.empty(), "test-agent", "session", "adopted-cancel") + .orElseThrow(); + assertEquals(TaskStatus.CANCELLED, record.getStatus()); + } + + @Test + void cancelledLocalTaskNotifiesCancelledNotFailed() throws Exception { + CompletableFuture callback = new CompletableFuture<>(); + repo.setCompletionCallback( + (TaskRepository.TaskSettledCallback) + (rc, taskId, subAgentId, sessionId, status, result, errorMessage) -> + callback.complete( + new TaskDelivery( + taskId, + subAgentId, + status, + result, + errorMessage, + null))); + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + BackgroundTask task = + repo.putTask( + RuntimeContext.empty(), + "local-cancel", + "worker", + "session", + new TaskRunSpec.LocalTaskRunSpec( + () -> { + started.countDown(); + // The supplier is not interrupted on cancel — it can only + // observe cancellation after its own failure, which must not + // be reported as FAILED. + try { + release.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + throw new IllegalStateException("post-cancel failure"); + })); + + assertTrue(started.await(5, TimeUnit.SECONDS)); + assertTrue(repo.cancelTask(RuntimeContext.empty(), "session", "local-cancel")); + release.countDown(); + assertTrue(task.waitForCompletion(5_000), "task did not settle within 5 seconds"); + + TaskDelivery delivery = callback.get(5, TimeUnit.SECONDS); + assertEquals(TaskStatus.CANCELLED, delivery.status()); + assertNull(delivery.result()); + var record = + workspaceManager + .readTaskRecord( + RuntimeContext.empty(), "test-agent", "session", "local-cancel") + .orElseThrow(); + assertEquals(TaskStatus.CANCELLED, record.getStatus()); + } + @Test void suppressedSettledFailuresRetainDurableErrors() throws Exception { AtomicInteger callbacks = new AtomicInteger(); diff --git a/docs/dev/en/docs/harness/subagent.md b/docs/dev/en/docs/harness/subagent.md index 9f4763fc66..35d4fcc22c 100644 --- a/docs/dev/en/docs/harness/subagent.md +++ b/docs/dev/en/docs/harness/subagent.md @@ -158,7 +158,7 @@ Background tasks delivered: The parent naturally responds or continues. This means **you do not** write "remember to poll task_output" in your prompt — that was the old way. -Message-bus notifications distinguish `FAILED` tasks from successful completion and carry a short, sanitized error summary (a single truncated line) rather than the raw exception message; the full error remains available through the task record via `task_output`. The five-argument `TaskRepository.TaskCompletionCallback` remains compatible; use `TaskRepository.TaskSettledCallback` with the same `setCompletionCallback` method to receive status and error details. Custom repositories should call `onSettled` after persisting the terminal state; legacy `onCompleted` calls retain their null-result failure convention but cannot supply error details. +Message-bus notifications distinguish `FAILED` tasks from successful completion and report a fixed error category (execution failure) instead of the raw exception message, which may contain sensitive data; the full error remains available through the task record via `task_output`. Cancelled tasks are announced as `CANCELLED`, matching the persisted terminal state. The five-argument `TaskRepository.TaskCompletionCallback` remains compatible; use `TaskRepository.TaskSettledCallback` with the same `setCompletionCallback` method to receive status and error details. Custom repositories should call `onSettled` after persisting the terminal state; legacy `onCompleted` calls retain their null-result failure convention but cannot supply error details. ### Background task tools diff --git a/docs/dev/zh/docs/harness/subagent.md b/docs/dev/zh/docs/harness/subagent.md index 59e7a04af0..4ef03d7b50 100644 --- a/docs/dev/zh/docs/harness/subagent.md +++ b/docs/dev/zh/docs/harness/subagent.md @@ -156,7 +156,7 @@ RuntimeContext ctx = RuntimeContext.builder() 主 agent 看到这条 reminder 自然地回应或继续行动。这意味着你**不需要**在 prompt 里写"记得调 task_output 轮询"——那是旧版本的做法。 -消息总线通知会区分 `FAILED` 任务和正常完成,并携带简短、脱敏的错误摘要(截断为单行),而不是原始异常消息或空的业务结果;完整错误仍可通过 `task_output` 从任务记录中获取。五参数 `TaskRepository.TaskCompletionCallback` 保持兼容;通过同一个 `setCompletionCallback` 方法注册 `TaskRepository.TaskSettledCallback` 可获取状态及错误。自定义任务仓库应在持久化终态后调用 `onSettled`;旧的 `onCompleted` 调用保留 null 结果表示失败的约定,但无法提供错误详情。 +消息总线通知会区分 `FAILED` 任务和正常完成,并报告固定的错误类别(执行失败),而非可能包含敏感数据的原始异常消息;完整错误仍可通过 `task_output` 从任务记录中获取。取消的任务会按持久化的终态播报为 `CANCELLED`。五参数 `TaskRepository.TaskCompletionCallback` 保持兼容;通过同一个 `setCompletionCallback` 方法注册 `TaskRepository.TaskSettledCallback` 可获取状态及错误。自定义任务仓库应在持久化终态后调用 `onSettled`;旧的 `onCompleted` 调用保留 null 结果表示失败的约定,但无法提供错误详情。 ### 后台任务工具 diff --git a/docs/v2/en/docs/harness/subagent.md b/docs/v2/en/docs/harness/subagent.md index 080764ea10..cc17b896da 100644 --- a/docs/v2/en/docs/harness/subagent.md +++ b/docs/v2/en/docs/harness/subagent.md @@ -225,7 +225,7 @@ Background tasks delivered: The parent naturally responds or continues. This means **you do not** write "remember to poll task_output" in your prompt — that was the old way. -Message-bus notifications distinguish `FAILED` tasks from successful completion and carry a short, sanitized error summary (a single truncated line) rather than the raw exception message; the full error remains available through the task record via `task_output`. The five-argument `TaskRepository.TaskCompletionCallback` remains compatible; use `TaskRepository.TaskSettledCallback` with the same `setCompletionCallback` method to receive status and error details. Custom repositories should call `onSettled` after persisting the terminal state; legacy `onCompleted` calls retain their null-result failure convention but cannot supply error details. +Message-bus notifications distinguish `FAILED` tasks from successful completion and report a fixed error category (execution failure) instead of the raw exception message, which may contain sensitive data; the full error remains available through the task record via `task_output`. Cancelled tasks are announced as `CANCELLED`, matching the persisted terminal state. The five-argument `TaskRepository.TaskCompletionCallback` remains compatible; use `TaskRepository.TaskSettledCallback` with the same `setCompletionCallback` method to receive status and error details. Custom repositories should call `onSettled` after persisting the terminal state; legacy `onCompleted` calls retain their null-result failure convention but cannot supply error details. ### Background task tools diff --git a/docs/v2/zh/docs/harness/subagent.md b/docs/v2/zh/docs/harness/subagent.md index d478c991d2..ce70e5b692 100644 --- a/docs/v2/zh/docs/harness/subagent.md +++ b/docs/v2/zh/docs/harness/subagent.md @@ -218,7 +218,7 @@ RuntimeContext ctx = RuntimeContext.builder() 主 agent 看到这条 reminder 自然地回应或继续行动。这意味着你**不需要**在 prompt 里写"记得调 task_output 轮询"——那是旧版本的做法。 -消息总线通知会区分 `FAILED` 任务和正常完成,并携带简短、脱敏的错误摘要(截断为单行),而不是原始异常消息或空的业务结果;完整错误仍可通过 `task_output` 从任务记录中获取。五参数 `TaskRepository.TaskCompletionCallback` 保持兼容;通过同一个 `setCompletionCallback` 方法注册 `TaskRepository.TaskSettledCallback` 可获取状态及错误。自定义任务仓库应在持久化终态后调用 `onSettled`;旧的 `onCompleted` 调用保留 null 结果表示失败的约定,但无法提供错误详情。 +消息总线通知会区分 `FAILED` 任务和正常完成,并报告固定的错误类别(执行失败),而非可能包含敏感数据的原始异常消息;完整错误仍可通过 `task_output` 从任务记录中获取。取消的任务会按持久化的终态播报为 `CANCELLED`。五参数 `TaskRepository.TaskCompletionCallback` 保持兼容;通过同一个 `setCompletionCallback` 方法注册 `TaskRepository.TaskSettledCallback` 可获取状态及错误。自定义任务仓库应在持久化终态后调用 `onSettled`;旧的 `onCompleted` 调用保留 null 结果表示失败的约定,但无法提供错误详情。 ### 后台任务工具 From fffe6fe2730745f05b31293853421fceb0ce32c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A7=A3=E4=BC=9F?= Date: Thu, 26 Nov 2026 16:44:05 +0800 Subject: [PATCH 5/5] fix(harness): announce only the status on record when a task settles updateStatus now reads the record back after writing: WorkspaceManager swallows storage failures, so a normal return from the write says nothing about what the task exposes afterwards. The settlement callback therefore never announces a terminal status that is not on record. A completed result exists only in memory, so it is handed over with the on-record status instead of being dropped (#4399 requires the result to survive a failed record write); an unrecorded failure or cancellation has nothing to deliver and is not announced. --- .../agent/middleware/SubagentsMiddleware.java | 11 +++ .../agent/subagent/task/TaskRepository.java | 4 + .../task/WorkspaceTaskRepository.java | 42 +++++++++-- .../SubagentTaskSettledHintTest.java | 48 ++++++++++++ .../task/WorkspaceTaskRepositoryTest.java | 73 +++++++++++++++++++ docs/dev/en/docs/harness/subagent.md | 2 +- docs/dev/zh/docs/harness/subagent.md | 2 +- 7 files changed, 174 insertions(+), 8 deletions(-) diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/middleware/SubagentsMiddleware.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/middleware/SubagentsMiddleware.java index 10fb520d57..b87e33e5a6 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/middleware/SubagentsMiddleware.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/middleware/SubagentsMiddleware.java @@ -265,9 +265,20 @@ public TaskRepository getTaskRepository() { * category — they never embed the raw exception message, which can leak internals (paths, * endpoints, credentials) into the conversation. The full message stays in the durable task * record, reachable via {@code task_output}.

+ * + *

A non-terminal {@code status} means the task finished but its terminal state could not be + * persisted; the in-memory result is delivered once so it is not lost.

*/ public static String taskSettledHintContent( String taskId, String subAgentId, TaskStatus status, String result) { + if (!status.isTerminal()) { + return String.format( + "Background subagent task '%s' (agent=%s) finished and" + + " produced a result, but its terminal state could not be persisted," + + " so task queries may still report it as running. Do not start it" + + " again.\n\nResult:\n\n%s", + taskId, subAgentId, result != null ? result : "(no output)"); + } if (status == TaskStatus.FAILED) { return String.format( "Background subagent task '%s' (agent=%s) FAILED and" diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/TaskRepository.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/TaskRepository.java index 328c33b965..427adde087 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/TaskRepository.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/TaskRepository.java @@ -132,6 +132,10 @@ default boolean isDelivered(RuntimeContext rc, String sessionId, String taskId) * {@code null} for failed and cancelled tasks. Use {@link TaskSettledCallback} to also receive * terminal status and errors. * + *

Through {@link TaskSettledCallback}, {@code status} is always the status on record. When + * a completed task's terminal state cannot be persisted, the callback reports the non-terminal + * status on record together with the result, so the in-memory result is not lost. + * *

Callers retaining execution ownership can set {@link #SUPPRESS_COMPLETION_CALLBACK} * in their RuntimeContext to suppress inbox/wakeup callbacks while preserving durable results. * Implementations supporting this callback should honor the flag. diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepository.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepository.java index 6aab59a11f..d717794e12 100644 --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepository.java +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepository.java @@ -890,6 +890,11 @@ record -> { return existing; } + /** + * Returns the status on record after the call: the existing status when a guard applies or + * {@link WorkspaceManager#writeTaskRecord} fails, {@code status} once the write lands, or + * {@code null} when no record is readable. + */ private synchronized TaskStatus updateStatus( RuntimeContext rc, String sessionId, @@ -931,14 +936,22 @@ private synchronized TaskStatus updateStatus( record.setErrorMessage(error); } persistRecord(rc, sessionId, record); - return status; + // writeTaskRecord is best-effort: storage failures are logged and swallowed, so only a + // read-back proves which status the task now exposes. + return workspaceManager + .readTaskRecord(rc, parentAgentId, sessionId, taskId) + .map(TaskRecord::getStatus) + .orElse(null); } /** - * Persists a terminal state and fires the settlement callback with the status actually - * persisted. When cancellation races a settlement, {@link #updateStatus} keeps the record's - * CANCELLED status, so the callback must also report CANCELLED — announcing FAILED for a task - * the user just cancelled would invite the parent agent to retry it. + * Persists a terminal state and reports the status that is actually on record. When + * cancellation races a settlement, {@link #updateStatus} keeps the record's CANCELLED status, + * so the callback must also report CANCELLED — announcing FAILED for a task the user just + * cancelled would invite the parent agent to retry it. When the terminal write does not land, + * no terminal status is announced: the result of a completed task exists only in memory and is + * handed over with the on-record status, while an unrecorded failure or cancellation has + * nothing to deliver and stays silent. */ private void settleAndNotify( RuntimeContext rc, @@ -949,7 +962,24 @@ private void settleAndNotify( String result, String errorMessage) { TaskStatus effective = updateStatus(rc, sessionId, taskId, status, result, errorMessage); - if (effective == null || !effective.isTerminal()) { + if (effective == null) { + log.warn( + "Task {} settlement notification withheld for session {}: no record is" + + " readable", + taskId, + sessionId); + return; + } + if (!effective.isTerminal()) { + log.warn( + "Task {} status {} was not persisted for session {} (on record: {})", + taskId, + status, + sessionId, + effective); + if (status == TaskStatus.COMPLETED) { + fireCompletionCallback(rc, taskId, subAgentId, sessionId, effective, result, null); + } return; } boolean asPersisted = effective == status; diff --git a/agentscope-harness/src/test/java/io/agentscope/harness/agent/middleware/SubagentTaskSettledHintTest.java b/agentscope-harness/src/test/java/io/agentscope/harness/agent/middleware/SubagentTaskSettledHintTest.java index 04060a5ca0..4f8d67aae7 100644 --- a/agentscope-harness/src/test/java/io/agentscope/harness/agent/middleware/SubagentTaskSettledHintTest.java +++ b/agentscope-harness/src/test/java/io/agentscope/harness/agent/middleware/SubagentTaskSettledHintTest.java @@ -30,6 +30,7 @@ import io.agentscope.harness.agent.bus.MessageBus; import io.agentscope.harness.agent.filesystem.local.LocalFilesystem; import io.agentscope.harness.agent.subagent.task.BackgroundTask; +import io.agentscope.harness.agent.subagent.task.TaskRecord; import io.agentscope.harness.agent.subagent.task.TaskRepository; import io.agentscope.harness.agent.subagent.task.TaskRunSpec.LocalTaskRunSpec; import io.agentscope.harness.agent.subagent.task.TaskStatus; @@ -190,6 +191,53 @@ void suppressedFailedTaskPreservesDurableErrorWithoutNotifications(EntryMode mod assertEquals(List.of(), recordingBus.published); } + @Test + void unpersistedCompletionHintCarriesResultAndWakesOriginalSession() throws Exception { + dropTerminalWrites(); + RuntimeContext rc = runtimeContext(false); + BackgroundTask task = submitTask(rc, () -> OUTPUT); + + String hint = awaitHintAndWakeup(task); + + assertTrue(hint.contains(OUTPUT), hint); + assertTrue(hint.contains("could not be persisted"), hint); + assertFalse(hint.contains("has completed"), hint); + assertFalse(hint.contains("FAILED"), hint); + assertDurableResult(rc, TaskStatus.RUNNING, null, null); + } + + @Test + void unpersistedFailureQueuesNeitherHintNorWakeup() throws Exception { + dropTerminalWrites(); + BackgroundTask task = submitFailingTask(runtimeContext(false)); + + assertTrue(task.waitForCompletion(5_000), "task did not settle within 5 seconds"); + + assertEquals(List.of(), recordingBus.queued); + assertEquals(List.of(), recordingBus.published); + } + + /** WorkspaceManager swallows storage failures, so a dropped write is how a failed one looks. */ + private void dropTerminalWrites() { + workspaceManager = + new WorkspaceManager(tempDir) { + @Override + public void writeTaskRecord( + RuntimeContext rc, + String agentId, + String sessionId, + TaskRecord record) { + if (record.getStatus() == null || !record.getStatus().isTerminal()) { + super.writeTaskRecord(rc, agentId, sessionId, record); + } + } + }; + repo = WorkspaceTaskRepository.forTests(workspaceManager, PARENT_ID); + recordingBus = new RecordingBus(); + new SubagentsMiddleware(List.of(), repo, workspaceManager) + .wireMessageBus(recordingBus.bus, PARENT_ID); + } + private void wire(EntryMode mode) { workspaceManager = new WorkspaceManager(tempDir); repo = WorkspaceTaskRepository.forTests(workspaceManager, PARENT_ID); diff --git a/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryTest.java b/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryTest.java index 1a1a55f8be..3cf977f208 100644 --- a/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryTest.java +++ b/agentscope-harness/src/test/java/io/agentscope/harness/agent/subagent/task/WorkspaceTaskRepositoryTest.java @@ -29,6 +29,8 @@ import io.agentscope.harness.agent.filesystem.remote.store.NamespaceFactory; import io.agentscope.harness.agent.filesystem.spec.RemoteFilesystemSpec; import io.agentscope.harness.agent.workspace.WorkspaceManager; +import java.io.IOException; +import java.io.UncheckedIOException; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.Files; @@ -40,6 +42,7 @@ import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; @@ -51,6 +54,8 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; /** * Tests for {@link WorkspaceTaskRepository}: @@ -482,6 +487,74 @@ var record = assertEquals(TaskStatus.CANCELLED, record.getStatus()); } + @ParameterizedTest + @CsvSource({"false,false", "false,true", "true,false", "true,true"}) + void unpersistedTerminalStateIsNeverAnnounced(boolean taskFails, boolean writeThrows) + throws Exception { + // Storage may fail loudly (writeTaskRecord raises) or silently (WorkspaceManager logs the + // I/O error and returns normally). The record stays RUNNING either way, so the callback + // must never report a terminal status; only a completed result is handed over. + repo.shutdown(); + workspaceManager = + new WorkspaceManager(tempDir) { + @Override + public void writeTaskRecord( + RuntimeContext rc, + String agentId, + String sessionId, + TaskRecord record) { + if (record.getStatus() != null && record.getStatus().isTerminal()) { + if (writeThrows) { + throw new UncheckedIOException(new IOException("disk full")); + } + return; + } + super.writeTaskRecord(rc, agentId, sessionId, record); + } + }; + repo = WorkspaceTaskRepository.forTests(workspaceManager, "test-agent"); + List callbacks = new CopyOnWriteArrayList<>(); + repo.setCompletionCallback( + (TaskRepository.TaskSettledCallback) + (rc, taskId, agentId, sessionId, status, result, error) -> + callbacks.add( + new TaskDelivery( + taskId, agentId, status, result, error, null))); + RuntimeContext rc = RuntimeContext.empty(); + + BackgroundTask task = + repo.putTask( + rc, + "unpersisted", + "worker", + "session", + new TaskRunSpec.LocalTaskRunSpec( + () -> { + if (taskFails) { + throw new IllegalStateException("boom"); + } + return "done"; + })); + + assertTrue(task.waitForCompletion(5_000), "task did not finish within 5 seconds"); + + assertEquals( + TaskStatus.RUNNING, + workspaceManager + .readTaskRecord(rc, "test-agent", "session", "unpersisted") + .orElseThrow() + .getStatus()); + assertTrue(repo.findPendingDeliveries(rc, "session").isEmpty()); + if (taskFails) { + assertEquals(List.of(), callbacks); + } else { + assertEquals(1, callbacks.size()); + assertEquals(TaskStatus.RUNNING, callbacks.get(0).status()); + assertEquals("done", callbacks.get(0).result()); + assertNull(callbacks.get(0).errorMessage()); + } + } + @Test void suppressedSettledFailuresRetainDurableErrors() throws Exception { AtomicInteger callbacks = new AtomicInteger(); diff --git a/docs/dev/en/docs/harness/subagent.md b/docs/dev/en/docs/harness/subagent.md index fea3b558e6..fc26fe0eb0 100644 --- a/docs/dev/en/docs/harness/subagent.md +++ b/docs/dev/en/docs/harness/subagent.md @@ -172,7 +172,7 @@ Automatic delivery and wait barriers include the full output of each result they `task_output` returns the full result of a completed task. -Message-bus notifications distinguish `FAILED` tasks from successful completion and report a fixed error category (execution failure) instead of the raw exception message, which may contain sensitive data; the full error remains available through the task record via `task_output`. Cancelled tasks are announced as `CANCELLED`, matching the persisted terminal state. The five-argument `TaskRepository.TaskCompletionCallback` remains compatible; use `TaskRepository.TaskSettledCallback` with the same `setCompletionCallback` method to receive status and error details. Custom repositories should call `onSettled` after persisting the terminal state; legacy `onCompleted` calls retain their null-result failure convention but cannot supply error details. +Message-bus notifications distinguish `FAILED` tasks from successful completion and report a fixed error category (execution failure) instead of the raw exception message, which may contain sensitive data; the full error remains available through the task record via `task_output`. Cancelled tasks are announced as `CANCELLED`, matching the persisted terminal state. When the terminal state could not be persisted, no terminal status is announced: a completed result is still delivered once with a notice that it is not on record, while an unrecorded failure or cancellation is not announced. The five-argument `TaskRepository.TaskCompletionCallback` remains compatible; use `TaskRepository.TaskSettledCallback` with the same `setCompletionCallback` method to receive status and error details. Custom repositories should call `onSettled` after persisting the terminal state; legacy `onCompleted` calls retain their null-result failure convention but cannot supply error details. ### Background task tools diff --git a/docs/dev/zh/docs/harness/subagent.md b/docs/dev/zh/docs/harness/subagent.md index 07e54cedaf..92f0ecaab6 100644 --- a/docs/dev/zh/docs/harness/subagent.md +++ b/docs/dev/zh/docs/harness/subagent.md @@ -168,7 +168,7 @@ RuntimeContext ctx = RuntimeContext.builder() 自动交付和等待屏障会附上此次返回的完整结果。任务状态摘要用于查看执行状态。需要实际输出时,可以用 `task_output` 获取完整结果。 -消息总线通知会区分 `FAILED` 任务和正常完成,并报告固定的错误类别(执行失败),而非可能包含敏感数据的原始异常消息;完整错误仍可通过 `task_output` 从任务记录中获取。取消的任务会按持久化的终态播报为 `CANCELLED`。五参数 `TaskRepository.TaskCompletionCallback` 保持兼容;通过同一个 `setCompletionCallback` 方法注册 `TaskRepository.TaskSettledCallback` 可获取状态及错误。自定义任务仓库应在持久化终态后调用 `onSettled`;旧的 `onCompleted` 调用保留 null 结果表示失败的约定,但无法提供错误详情。 +消息总线通知会区分 `FAILED` 任务和正常完成,并报告固定的错误类别(执行失败),而非可能包含敏感数据的原始异常消息;完整错误仍可通过 `task_output` 从任务记录中获取。取消的任务会按持久化的终态播报为 `CANCELLED`。终态未能持久化时不播报任何终态:已完成任务的结果仍会附带"未落盘"提示送达一次,未落盘的失败或取消则不播报。五参数 `TaskRepository.TaskCompletionCallback` 保持兼容;通过同一个 `setCompletionCallback` 方法注册 `TaskRepository.TaskSettledCallback` 可获取状态及错误。自定义任务仓库应在持久化终态后调用 `onSettled`;旧的 `onCompleted` 调用保留 null 结果表示失败的约定,但无法提供错误详情。 ### 后台任务工具