JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix(agentos): emit handoff JSON to stdout for launcher-driven 3rdagent.switch
haowenzhong1b4318421c43e
diff --git a/jiuwenswarm/channels/tui/frontend/src/app-state.ts b/jiuwenswarm/channels/tui/frontend/src/app-state.tsindex 73024850e5..588c922388 100644--- a/jiuwenswarm/channels/tui/frontend/src/app-state.ts+++ b/jiuwenswarm/channels/tui/frontend/src/app-state.ts@@ -1226,8 +1226,8 @@ export class CliPiAppState {code: "NOT_SUPERVISED",message: "Running outside agentos-tui launcher; start via `agentos-tui` to use /switch",},- requestHandoff: (target) => this.handoffPort- ? this.handoffPort.requestHandoff(target)+ requestHandoff: (target, switchContent) => this.handoffPort+ ? this.handoffPort.requestHandoff(target, switchContent): Promise.reject(new Error("Handoff port not available (not supervised)")),hasServerTask: () => this.taskLifecycle?.hasServerTask() ?? this.hasServerTask(),cancelAndWaitForIdle: (opts) => this.taskLifecyclediff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/switch.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/switch.tsindex 87948dbbe6..8c98b7a148 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/switch.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/switch.ts@@ -10,7 +10,10 @@* 2. checkHandoff 预检 — 失败时显示错误并返回(不询问、不取消任务)* 3. hasServerTask() — 有任务时询问用户;取消则直接返回(不发送 interrupt)* 4. 确认后 cancelAndWaitForIdle({ timeoutMs: 5000 }) — 失败则显示错误并返回- * 5. requestHandoff — 二次校验 + 统一关闭路径+ * 5. requestHandoff — 二次校验 + 统一关闭路径(输出 handoff JSON 到 stdout,以 88 退出)+ *+ * TUI 不直接发送 3rdagent.switch RPC;launcher 从 stdout 读取 handoff JSON 后,+ * 由 launcher 连接 gateway 发起 RPC 并建立 SSH 隧道到三方 agentos。*/import { makeItem } from "../helpers.js";import { HANDOFF_TARGET_CC_TUI } from "../../supervision/protocol.js";@@ -125,8 +128,11 @@ async function performSwitch(}// 5. 请求 handoff(二次校验 + 统一关闭路径)+ // requestHandoff 会构造 handoff JSON 输出到 stdout(供 launcher 读取),+ // 然后以动作退出码 88 退出。launcher 从 stdout 读取 JSON 后,+ // 由 launcher 连接 gateway 发起 3rdagent.switch RPC 并建立 SSH 隧道。try {- await ctx.requestHandoff(target.handoffTarget);+ await ctx.requestHandoff(target.handoffTarget, `switch ${target.name}`);} catch (err) {const msg = err instanceof Error ? err.message : String(err);ctx.addItem(makeItem(ctx.sessionId, "error", `Handoff failed: ${msg}`));diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/types.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/types.tsindex 31dfa78985..4234cc8d98 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/types.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/types.ts@@ -130,8 +130,8 @@ export interface CommandContext {/** HandoffPort 预检:校验托管标记、动作退出码和目标能力。 */checkHandoff?: (target: HandoffTarget) => HandoffCheckResult;- /** HandoffPort 请求:二次校验后调用统一顶层关闭路径。 */- requestHandoff?: (target: HandoffTarget) => Promise<void>;+ /** HandoffPort 请求:二次校验后调用统一顶层关闭路径,输出 handoff JSON 到 stdout。 */+ requestHandoff?: (target: HandoffTarget, switchContent: string) => Promise<void>;/** TaskLifecyclePort:统一任务快照;/switch 用于判断是否需要询问中断。 */hasServerTask?: () => boolean;/** TaskLifecyclePort:等待型取消;只供 /switch 等生命周期动作使用。 */diff --git a/jiuwenswarm/channels/tui/frontend/src/core/supervision/handoff-port.ts b/jiuwenswarm/channels/tui/frontend/src/core/supervision/handoff-port.tsindex 4bab9e6463..516b709c3b 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/supervision/handoff-port.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/supervision/handoff-port.ts@@ -64,7 +64,7 @@ export class HandoffPortImpl implements HandoffPort {return { ok: true };}- async requestHandoff(target: HandoffTarget): Promise<void> {+ async requestHandoff(target: HandoffTarget, switchContent: string): Promise<void> {// requestHandoff 在询问/取消任务之后才被调用;必须二次校验。const check = this.checkHandoff(target);if (!check.ok) {@@ -78,9 +78,18 @@ export class HandoffPortImpl implements HandoffPort {if (exitCode === null) {throw new Error("Switch exit code unexpectedly null after checkHandoff");}+ // 构造 handoff JSON,供 launcher 从 stdout 读取后发起 3rdagent.switch RPC。+ // content 是完整命令文本(如 "switch claude"),parsed 是目标名(如 "claude")。+ const parsed = switchContent.replace(/^switch\s+/i, "").trim();+ const handoffMessage = JSON.stringify({+ action: "switch",+ content: switchContent,+ parsed,+ });await this.lifecycle.closeUi({reason: "switch",exitCode,+ handoffMessage,});} catch (err) {// 清理失败:尽力恢复终端,以非动作错误码退出;不得使用切换动作码。diff --git a/jiuwenswarm/channels/tui/frontend/src/core/supervision/protocol.ts b/jiuwenswarm/channels/tui/frontend/src/core/supervision/protocol.tsindex 16c715dd7b..b6e69c5baf 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/supervision/protocol.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/supervision/protocol.ts@@ -68,9 +68,11 @@ export interface HandoffPort {checkHandoff(target: HandoffTarget): HandoffCheckResult;/*** 请求 handoff:二次校验后调用统一顶层关闭路径,以 launcher 注入的动作退出码退出。+ * switchContent 是原始命令文本(如 "switch claude"),会在退出前以 handoff JSON+ * 输出到 stdout,供 launcher 读取并解析后发起 3rdagent.switch RPC。* 成功路径不会返回(process.exit)。*/- requestHandoff(target: HandoffTarget): Promise<void>;+ requestHandoff(target: HandoffTarget, switchContent: string): Promise<void>;}/** 重新认证触发原因。 */@@ -94,9 +96,14 @@ export type UiExitReason =/*** 统一顶层关闭路径:串行完成退出通知 → screen.dispose → appState.stop →- * wsClient.disconnect → tui.stop → process.exit。+ * wsClient.disconnect → tui.stop → stdout handoff JSON(如有)→ process.exit。* 任一时刻只允许一次关闭调用;重复调用直接返回已存在的 Promise。*/export interface UiLifecyclePort {- closeUi(options: { reason: UiExitReason; exitCode: number }): Promise<void>;+ closeUi(options: {+ reason: UiExitReason;+ exitCode: number;+ /** 退出前输出到 stdout 的 handoff JSON,供 launcher 读取。仅 switch reason 使用。 */+ handoffMessage?: string;+ }): Promise<void>;}diff --git a/jiuwenswarm/channels/tui/frontend/src/core/supervision/ui-lifecycle.ts b/jiuwenswarm/channels/tui/frontend/src/core/supervision/ui-lifecycle.tsindex 151e0237c6..5d8ec31299 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/supervision/ui-lifecycle.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/supervision/ui-lifecycle.ts@@ -23,7 +23,11 @@ export class UiLifecyclePortImpl implements UiLifecyclePort {constructor(private readonly deps: UiLifecycleDeps) {}- async closeUi(options: { reason: UiExitReason; exitCode: number }): Promise<void> {+ async closeUi(options: {+ reason: UiExitReason;+ exitCode: number;+ handoffMessage?: string;+ }): Promise<void> {// 并发保护:正在关闭时第二次调用直接返回已存在的 Promise。if (this.closed) {return this.closingPromise ?? Promise.resolve();@@ -59,7 +63,17 @@ export class UiLifecyclePortImpl implements UiLifecyclePort {} catch {// ignore — 进程即将退出}- // 5. process.exit — 使用 launcher 注入的动作退出码+ // 5. stdout handoff JSON — 供 launcher 读取(仅 switch reason)+ // 必须在 screen.dispose 之后输出,避免污染 alternate screen;+ // 必须在 process.exit 之前输出,确保 launcher 能从 stdout 管道读取。+ if (options.handoffMessage) {+ try {+ process.stdout.write(options.handoffMessage + "\n");+ } catch {+ // ignore — 进程即将退出+ }+ }+ // 6. process.exit — 使用 launcher 注入的动作退出码process.exit(options.exitCode);})();return this.closingPromise;diff --git a/jiuwenswarm/channels/tui/frontend/tests/handoff-port.test.mjs b/jiuwenswarm/channels/tui/frontend/tests/handoff-port.test.mjsindex 9774c5af12..67d6c397f0 100644--- a/jiuwenswarm/channels/tui/frontend/tests/handoff-port.test.mjs+++ b/jiuwenswarm/channels/tui/frontend/tests/handoff-port.test.mjs@@ -79,7 +79,7 @@ class MockUiLifecycle {const lifecycle = new MockUiLifecycle();const handoff = new HandoffPortImpl(env, lifecycle);// 第一次 requestHandoff 触发 handoffInProgress=true(但 mock closeUi 不退出)- await handoff.requestHandoff(HANDOFF_TARGET_CC_TUI).catch(() => {});+ await handoff.requestHandoff(HANDOFF_TARGET_CC_TUI, "switch claude").catch(() => {});const result = handoff.checkHandoff(HANDOFF_TARGET_CC_TUI);assert.equal(result.ok, false);assert.equal(result.code, "HANDOFF_IN_PROGRESS");@@ -100,7 +100,7 @@ class MockUiLifecycle {assert.equal(result.code, "HANDOFF_IN_PROGRESS");}-// 7. requestHandoff 成功:调用 closeUi with reason=switch and correct exit code+// 7. requestHandoff 成功:调用 closeUi with reason=switch, correct exit code and handoff JSON{const env = readSupervisionEnv({AGENTOS_TUI_SUPERVISED: "1",@@ -109,9 +109,14 @@ class MockUiLifecycle {});const lifecycle = new MockUiLifecycle();const handoff = new HandoffPortImpl(env, lifecycle);- await handoff.requestHandoff(HANDOFF_TARGET_CC_TUI);+ await handoff.requestHandoff(HANDOFF_TARGET_CC_TUI, "switch claude");assert.equal(lifecycle.lastCall.reason, "switch");assert.equal(lifecycle.lastCall.exitCode, 88);+ // handoff JSON 应包含 action、content 和 parsed 字段+ const msg = JSON.parse(lifecycle.lastCall.handoffMessage);+ assert.equal(msg.action, "switch");+ assert.equal(msg.content, "switch claude");+ assert.equal(msg.parsed, "claude");}// 8. requestHandoff 在预检失败时抛错@@ -120,7 +125,7 @@ class MockUiLifecycle {const lifecycle = new MockUiLifecycle();const handoff = new HandoffPortImpl(env, lifecycle);await assert.rejects(- () => handoff.requestHandoff(HANDOFF_TARGET_CC_TUI),+ () => handoff.requestHandoff(HANDOFF_TARGET_CC_TUI, "switch claude"),/Running outside agentos-tui launcher/,);assert.equal(lifecycle.calls.length, 0); // closeUi 未被调用diff --git a/jiuwenswarm/channels/tui/frontend/tests/reauth-port.test.mjs b/jiuwenswarm/channels/tui/frontend/tests/reauth-port.test.mjsindex a31e8cc0b8..fe2b063fbc 100644--- a/jiuwenswarm/channels/tui/frontend/tests/reauth-port.test.mjs+++ b/jiuwenswarm/channels/tui/frontend/tests/reauth-port.test.mjs@@ -74,7 +74,7 @@ class MockUiLifecycle {const handoff = new HandoffPortImpl(env, lifecycle);const reauth = new ReauthenticationPortImpl(env, handoff, lifecycle);// 触发 handoff(mock closeUi 不退出,但 handoffInProgress=true)- await handoff.requestHandoff("cc-tui").catch(() => {});+ await handoff.requestHandoff("cc-tui", "switch claude").catch(() => {});await assert.rejects(reauth.requestReauthentication("access-token-expired"),/Handoff or reauthentication already in progress/,diff --git a/jiuwenswarm/channels/tui/frontend/tests/switch-command.test.mjs b/jiuwenswarm/channels/tui/frontend/tests/switch-command.test.mjsindex 8567ac20ad..5c0873c387 100644--- a/jiuwenswarm/channels/tui/frontend/tests/switch-command.test.mjs+++ b/jiuwenswarm/channels/tui/frontend/tests/switch-command.test.mjs@@ -84,7 +84,7 @@ const listSub = switchCmd.subCommands.find((s) => s.name === "list");const cancelCalls = [];const { ctx, addedItems, askedQuestions } = makeMockContext({checkHandoff: () => ({ ok: true }),- requestHandoff: async (target) => handoffCalls.push(target),+ requestHandoff: async (target, switchContent) => handoffCalls.push({ target, switchContent }),hasServerTask: () => false,cancelAndWaitForIdle: async () => cancelCalls.push(true),});@@ -92,7 +92,8 @@ const listSub = switchCmd.subCommands.find((s) => s.name === "list");assert.equal(askedQuestions.length, 0); // 无任务不询问assert.equal(cancelCalls.length, 0); // 无任务不取消assert.equal(handoffCalls.length, 1);- assert.equal(handoffCalls[0], HANDOFF_TARGET_CC_TUI);+ assert.equal(handoffCalls[0].target, HANDOFF_TARGET_CC_TUI);+ assert.equal(handoffCalls[0].switchContent, "switch claude");}// 6. /switch claude 有任务 + 用户取消:不发送 interrupt、不调用 requestHandoff@@ -102,7 +103,7 @@ const listSub = switchCmd.subCommands.find((s) => s.name === "list");let askedCount = 0;const { ctx, addedItems } = makeMockContext({checkHandoff: () => ({ ok: true }),- requestHandoff: async (target) => handoffCalls.push(target),+ requestHandoff: async (target, switchContent) => handoffCalls.push({ target, switchContent }),hasServerTask: () => true,cancelAndWaitForIdle: async () => cancelCalls.push(true),askQuestions: async (questions, id) => {@@ -127,7 +128,7 @@ const listSub = switchCmd.subCommands.find((s) => s.name === "list");let askedCount = 0;const { ctx, addedItems } = makeMockContext({checkHandoff: () => ({ ok: true }),- requestHandoff: async (target) => handoffCalls.push(target),+ requestHandoff: async (target, switchContent) => handoffCalls.push({ target, switchContent }),hasServerTask: () => true,cancelAndWaitForIdle: async (opts) => cancelCalls.push(opts),askQuestions: async () => {@@ -139,7 +140,8 @@ const listSub = switchCmd.subCommands.find((s) => s.name === "list");assert.equal(askedCount, 1);assert.equal(cancelCalls.length, 1);assert.equal(handoffCalls.length, 1);- assert.equal(handoffCalls[0], HANDOFF_TARGET_CC_TUI);+ assert.equal(handoffCalls[0].target, HANDOFF_TARGET_CC_TUI);+ assert.equal(handoffCalls[0].switchContent, "switch claude");}// 8. /switch claude 有任务 + 用户确认 + 取消失败:保留 TUI,不调用 handoff@@ -148,7 +150,7 @@ const listSub = switchCmd.subCommands.find((s) => s.name === "list");let askedCount = 0;const { ctx, addedItems } = makeMockContext({checkHandoff: () => ({ ok: true }),- requestHandoff: async (target) => handoffCalls.push(target),+ requestHandoff: async (target, switchContent) => handoffCalls.push({ target, switchContent }),hasServerTask: () => true,cancelAndWaitForIdle: async () => {const err = new Error("CANCEL_TIMEOUT");