From 6f79c14c6d8b8d627c00ec3e3d766737b0a5d768 Mon Sep 17 00:00:00 2001 From: taekchef Date: Wed, 15 Jul 2026 22:49:04 +0800 Subject: [PATCH] fix: preserve Pi terminal errors and cancellation --- Sources/WeiBeiCore/PiAgentRuntime.swift | 79 ++-- Sources/WeiBeiCore/PiRPCProtocol.swift | 54 ++- .../WeiBeiSelfCheck/PiAgentSelfChecks.swift | 27 +- .../PiTerminalRuntimeSelfChecks.swift | 367 ++++++++++++++++++ Sources/WeiBeiSelfCheck/main.swift | 10 +- 5 files changed, 507 insertions(+), 30 deletions(-) create mode 100644 Sources/WeiBeiSelfCheck/PiTerminalRuntimeSelfChecks.swift diff --git a/Sources/WeiBeiCore/PiAgentRuntime.swift b/Sources/WeiBeiCore/PiAgentRuntime.swift index 184d60c77..ec0dbda32 100644 --- a/Sources/WeiBeiCore/PiAgentRuntime.swift +++ b/Sources/WeiBeiCore/PiAgentRuntime.swift @@ -264,6 +264,32 @@ public enum PiAgentDiagnosticSanitizer { public actor PiAgentRuntime: StudyAgentRuntime { private static let processReadinessTimeoutSeconds: UInt64 = 12 + private struct ProgressDelivery: Sendable { + let continuation: AsyncStream.Continuation + let task: Task + + init(handler: @escaping StudyAgentProgressHandler) { + let pair = AsyncStream.makeStream( + bufferingPolicy: .bufferingNewest(32) + ) + continuation = pair.continuation + task = Task.detached(priority: .userInitiated) { + for await event in pair.stream { + await handler(event) + } + } + } + + func yield(_ event: StudyAgentProgress) { + continuation.yield(event) + } + + func finish() { + continuation.finish() + task.cancel() + } + } + private struct PendingCommand { var continuation: CheckedContinuation var timeoutTask: Task @@ -289,7 +315,7 @@ public actor PiAgentRuntime: StudyAgentRuntime { var proposal: StudyAgentNoteProposal? var learningUpdate: StudyAgentLearningUpdate? var lastError: String? - var progress: StudyAgentProgressHandler? + var progressDelivery: ProgressDelivery? var continuation: CheckedContinuation? var completed: Result? var watchdogTask: Task? @@ -297,6 +323,7 @@ public actor PiAgentRuntime: StudyAgentRuntime { private let executableOverride: URL? private let runtimeDirectory: URL + private let runInactivityTimeoutNanoseconds: UInt64 private var providerConfiguration = PiAgentProviderConfiguration() private var process: Process? private var inputHandle: FileHandle? @@ -311,12 +338,17 @@ public actor PiAgentRuntime: StudyAgentRuntime { private var idleShutdownTask: Task? private let traceEnabled = ProcessInfo.processInfo.environment["WEIBEI_PI_TRACE"] == "1" - public init(executableURL: URL? = nil, runtimeDirectory: URL? = nil) { + public init( + executableURL: URL? = nil, + runtimeDirectory: URL? = nil, + runInactivityTimeoutNanoseconds: UInt64 = 300_000_000_000 + ) { executableOverride = executableURL self.runtimeDirectory = runtimeDirectory ?? FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first? .appendingPathComponent("WeiBei/AgentRuntime", isDirectory: true) ?? FileManager.default.temporaryDirectory.appendingPathComponent("WeiBeiAgentRuntime", isDirectory: true) + self.runInactivityTimeoutNanoseconds = max(1, runInactivityTimeoutNanoseconds) } public func configure(_ configuration: PiAgentProviderConfiguration) { @@ -348,7 +380,7 @@ public actor PiAgentRuntime: StudyAgentRuntime { try requireStartingRun(request.id) let context = StudyAgentContextEnvelope(request: request) try writeContext(context) - await progress?(.readingContext) + let progressDelivery = progress.map(ProgressDelivery.init(handler:)) let currentJumpEvidence = currentJumpEvidence(in: context) activeRun = ActiveRun( @@ -370,8 +402,9 @@ public actor PiAgentRuntime: StudyAgentRuntime { jumpEvidenceLabels: currentJumpEvidence, lastLocationSourceLabel: context.learning.lastLocation.map { "[材料:\($0.itemTitle)]" }, allowedNoteSourceLabels: currentSourceLabels(in: context), - progress: progress + progressDelivery: progressDelivery ) + progressDelivery?.yield(.readingContext) startingRunID = nil refreshRunWatchdog() do { @@ -409,21 +442,8 @@ public actor PiAgentRuntime: StudyAgentRuntime { private func cancelRun(id runID: UUID) async { guard activeRun?.id == runID else { return } - guard process != nil else { - finishRun(id: runID, with: .failure(PiAgentRuntimeError.cancelled)) - return - } - - do { - _ = try await sendCommand(type: "abort", timeoutSeconds: 2) - } catch { - shutdownProcess(reason: PiAgentRuntimeError.cancelled) - return - } - - if activeRun?.id == runID { - finishRun(id: runID, with: .failure(PiAgentRuntimeError.cancelled)) - } + finishRun(id: runID, with: .failure(PiAgentRuntimeError.cancelled)) + shutdownProcess(reason: PiAgentRuntimeError.cancelled) } public func reset() async { @@ -993,7 +1013,10 @@ public actor PiAgentRuntime: StudyAgentRuntime { run.streamedText += delta activeRun = run refreshRunWatchdog() - await run.progress?(.text(run.streamedText)) + run.progressDelivery?.yield(.text(run.streamedText)) + + case .runActivity: + refreshRunWatchdog() case let .assistantError(message): guard var run = activeRun else { return } @@ -1019,7 +1042,7 @@ public actor PiAgentRuntime: StudyAgentRuntime { return } refreshRunWatchdog() - await run.progress?(.usingTool(name)) + run.progressDelivery?.yield(.usingTool(name)) case let .contextRead(_, contextRevision): guard var run = activeRun else { return } @@ -1112,13 +1135,16 @@ public actor PiAgentRuntime: StudyAgentRuntime { activeRun = run refreshRunWatchdog() - case let .agentEnded(text, stopReason): + case let .agentEnded(text, stopReason, modelError): guard let run = activeRun else { return } let cleanText = (text.isEmpty ? run.streamedText : text).trimmingCharacters(in: .whitespacesAndNewlines) if stopReason == "aborted" { finishRun(id: run.id, with: .failure(PiAgentRuntimeError.cancelled)) } else if stopReason == "error" { - finishRun(id: run.id, with: .failure(PiAgentRuntimeError.agentFailed(run.lastError ?? "Unknown model error"))) + let detail = modelError.map(sanitizedDiagnostic) + ?? run.lastError + ?? "PI 模型请求失败,但运行时没有返回错误详情" + finishRun(id: run.id, with: .failure(PiAgentRuntimeError.agentFailed(detail))) } else if run.answeredBeforeContext { finishRun(id: run.id, with: .failure(PiAgentRuntimeError.agentFailed("PI answered before reading the current WeiBei context"))) } else if !run.didReadContext { @@ -1165,7 +1191,7 @@ public actor PiAgentRuntime: StudyAgentRuntime { } case .event: - refreshRunWatchdog() + break } } @@ -1173,6 +1199,7 @@ public actor PiAgentRuntime: StudyAgentRuntime { guard var run = activeRun, run.id == id, run.completed == nil else { return } run.watchdogTask?.cancel() run.watchdogTask = nil + run.progressDelivery?.finish() clearContextSnapshot() if let continuation = run.continuation { activeRun = nil @@ -1187,6 +1214,7 @@ public actor PiAgentRuntime: StudyAgentRuntime { private func discardRun(id: UUID) { guard let run = activeRun, run.id == id else { return } run.watchdogTask?.cancel() + run.progressDelivery?.finish() activeRun = nil clearContextSnapshot() scheduleIdleShutdown() @@ -1216,9 +1244,10 @@ public actor PiAgentRuntime: StudyAgentRuntime { guard var run = activeRun else { return } run.watchdogTask?.cancel() let runID = run.id + let inactivityTimeoutNanoseconds = runInactivityTimeoutNanoseconds run.watchdogTask = Task { [weak self] in do { - try await Task.sleep(nanoseconds: 300 * 1_000_000_000) + try await Task.sleep(nanoseconds: inactivityTimeoutNanoseconds) } catch { return } diff --git a/Sources/WeiBeiCore/PiRPCProtocol.swift b/Sources/WeiBeiCore/PiRPCProtocol.swift index 8d6a73ba4..7752dad4e 100644 --- a/Sources/WeiBeiCore/PiRPCProtocol.swift +++ b/Sources/WeiBeiCore/PiRPCProtocol.swift @@ -73,9 +73,16 @@ public struct PiRPCResponse: Equatable, Sendable { } } +public enum PiRPCRunActivity: Equatable, Sendable { + case thinking + case tool + case retrying +} + public enum PiRPCIncomingMessage: Equatable, Sendable { case response(PiRPCResponse) case textDelta(String) + case runActivity(PiRPCRunActivity) case assistantError(String) case toolStarted(id: String, name: String) case contextRead(id: String, contextRevision: String) @@ -84,7 +91,7 @@ public enum PiRPCIncomingMessage: Equatable, Sendable { case noteProposal(id: String, StudyAgentNoteProposal) case learningUpdate(id: String, StudyAgentLearningUpdate) case toolFailed(id: String, name: String, message: String) - case agentEnded(text: String, stopReason: String?) + case agentEnded(text: String, stopReason: String?, error: String?) case extensionError(String) case event(String) } @@ -125,6 +132,9 @@ public enum PiRPCMessageDecoder { if eventType == "text_delta", let delta = event["delta"] as? String { return .textDelta(delta) } + if ["thinking_start", "thinking_delta", "thinking_end"].contains(eventType) { + return .runActivity(.thinking) + } if eventType == "error" { let reason = event["error"] as? String ?? event["reason"] as? String @@ -133,6 +143,21 @@ public enum PiRPCMessageDecoder { } return .event(eventType) + case "auto_retry_start", "auto_retry_end": + return .runActivity(.retrying) + + case "tool_execution_update": + return .runActivity(.tool) + + case "message_end", "turn_end": + guard let message = object["message"] as? [String: Any], + message["role"] as? String == "assistant", + message["stopReason"] as? String == "error", + let error = assistantError(in: message) else { + return .event(type) + } + return .assistantError(error) + case "tool_execution_start": guard let name = object["toolName"] as? String else { throw PiRPCProtocolError.invalidEnvelope @@ -271,12 +296,14 @@ public enum PiRPCMessageDecoder { let messages = object["messages"] as? [[String: Any]] ?? [] var finalText = "" var stopReason: String? + var finalError: String? for message in messages where message["role"] as? String == "assistant" { let text = assistantText(in: message) if !text.isEmpty { finalText = text } stopReason = message["stopReason"] as? String ?? stopReason + finalError = assistantError(in: message) ?? finalError } - return .agentEnded(text: finalText, stopReason: stopReason) + return .agentEnded(text: finalText, stopReason: stopReason, error: finalError) case "extension_error": let path = object["extensionPath"] as? String ?? "WeiBei extension" @@ -297,6 +324,29 @@ public enum PiRPCMessageDecoder { }.joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines) } + private static func assistantError(in message: [String: Any]) -> String? { + if let errorMessage = nonEmptyString(message["errorMessage"]) { + return errorMessage + } + let diagnostics = message["diagnostics"] as? [[String: Any]] ?? [] + for diagnostic in diagnostics.reversed() { + if let error = diagnostic["error"] as? [String: Any], + let message = nonEmptyString(error["message"]) { + return message + } + if let message = nonEmptyString(diagnostic["message"]) { + return message + } + } + return nil + } + + private static func nonEmptyString(_ value: Any?) -> String? { + guard let value = value as? String else { return nil } + let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines) + return trimmed.isEmpty ? nil : trimmed + } + private static func firstText(in result: [String: Any]?) -> String? { let content = result?["content"] as? [[String: Any]] ?? [] return content.compactMap { $0["text"] as? String }.first diff --git a/Sources/WeiBeiSelfCheck/PiAgentSelfChecks.swift b/Sources/WeiBeiSelfCheck/PiAgentSelfChecks.swift index f72027f09..bcb4f07a0 100644 --- a/Sources/WeiBeiSelfCheck/PiAgentSelfChecks.swift +++ b/Sources/WeiBeiSelfCheck/PiAgentSelfChecks.swift @@ -179,7 +179,32 @@ private func checkRPCDecoding() throws { ) let ended = try PiRPCMessageDecoder.decode(Data(#"{"type":"agent_end","messages":[{"role":"assistant","content":[{"type":"text","text":"第一轮"}],"stopReason":"toolUse"},{"role":"assistant","content":[{"type":"text","text":"最终回答"}],"stopReason":"stop"}]}"#.utf8)) - try piRequire(ended == .agentEnded(text: "最终回答", stopReason: "stop"), "PI agent_end selects the final assistant answer") + try piRequire(ended == .agentEnded(text: "最终回答", stopReason: "stop", error: nil), "PI agent_end selects the final assistant answer") + + let messageEndError = try PiRPCMessageDecoder.decode(Data(#"{"type":"message_end","message":{"role":"assistant","stopReason":"error","errorMessage":"上游服务拒绝了这次请求"}}"#.utf8)) + try piRequire( + messageEndError == .assistantError("上游服务拒绝了这次请求"), + "PI message_end exposes the assistant error instead of collapsing it into an unknown error" + ) + + let turnEndError = try PiRPCMessageDecoder.decode(Data(#"{"type":"turn_end","message":{"role":"assistant","stopReason":"error","diagnostics":[{"message":"旧诊断"},{"error":{"message":"证书校验失败"}}]}}"#.utf8)) + try piRequire( + turnEndError == .assistantError("证书校验失败"), + "PI turn_end exposes the newest nested diagnostic" + ) + + let thinking = try PiRPCMessageDecoder.decode(Data(#"{"type":"message_update","assistantMessageEvent":{"type":"thinking_delta","delta":"正在核对来源"}}"#.utf8)) + try piRequire(thinking == .runActivity(.thinking), "PI thinking deltas count as real run activity") + let retrying = try PiRPCMessageDecoder.decode(Data(#"{"type":"auto_retry_start","attempt":2}"#.utf8)) + try piRequire(retrying == .runActivity(.retrying), "PI provider retries count as real run activity") + let toolUpdate = try PiRPCMessageDecoder.decode(Data(#"{"type":"tool_execution_update","toolCallId":"tool-9","toolName":"weibei_course_search"}"#.utf8)) + try piRequire(toolUpdate == .runActivity(.tool), "PI tool updates count as real run activity") + + let endedWithError = try PiRPCMessageDecoder.decode(Data(#"{"type":"agent_end","messages":[{"role":"assistant","content":[],"stopReason":"error","diagnostics":[{"error":{"message":"真实模型错误"}}]}]}"#.utf8)) + try piRequire( + endedWithError == .agentEnded(text: "", stopReason: "error", error: "真实模型错误"), + "PI agent_end preserves the terminal model error" + ) try piRequire(try PiRPCMessageDecoder.decode(Data(#"{"type":"future_event"}"#.utf8)) == .event("future_event"), "PI decoder tolerates unknown future events") do { diff --git a/Sources/WeiBeiSelfCheck/PiTerminalRuntimeSelfChecks.swift b/Sources/WeiBeiSelfCheck/PiTerminalRuntimeSelfChecks.swift new file mode 100644 index 000000000..a548e2d4c --- /dev/null +++ b/Sources/WeiBeiSelfCheck/PiTerminalRuntimeSelfChecks.swift @@ -0,0 +1,367 @@ +import CryptoKit +import Foundation +import WeiBeiCore + +private struct PiTerminalRuntimeFixture { + var rootURL: URL + var executableURL: URL + + func workingDirectory(named name: String) throws -> URL { + let url = rootURL.appendingPathComponent(name, isDirectory: true) + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) + return url + } +} + +private enum PiTerminalRuntimeSelfCheckError: LocalizedError { + case failed(String) + + var errorDescription: String? { + switch self { + case let .failed(message): message + } + } +} + +private actor PiProgressProbe { + private var reachedReadingContext = false + + func record(_ event: StudyAgentProgress) { + if event == .readingContext { + reachedReadingContext = true + } + } + + func waitForReadingContext() async -> Bool { + for _ in 0..<250 { + if reachedReadingContext { return true } + try? await Task.sleep(nanoseconds: 20_000_000) + } + return false + } +} + +func runPiTerminalRuntimeSelfChecks() async throws { + let fixture = try makePiTerminalRuntimeFixture() + defer { try? FileManager.default.removeItem(at: fixture.rootURL) } + + try await checkUserStopReturnsImmediately(fixture) + try await checkTerminalErrorBypassesSlowProgress(fixture) + try await checkGenericEventsDoNotDefeatWatchdog(fixture) + try await checkMeaningfulThinkingKeepsRunAlive(fixture) +} + +private func checkUserStopReturnsImmediately(_ fixture: PiTerminalRuntimeFixture) async throws { + let runtime = PiAgentRuntime( + executableURL: fixture.executableURL, + runtimeDirectory: try fixture.workingDirectory(named: "CancelMode"), + runInactivityTimeoutNanoseconds: 2_000_000_000 + ) + let probe = PiProgressProbe() + let run = Task { + await terminalOutcome(runtime: runtime, revision: "cancel-test") { event in + await probe.record(event) + } + } + guard await probe.waitForReadingContext() else { + await runtime.shutdown() + throw PiTerminalRuntimeSelfCheckError.failed("PI cancellation fixture never reached the active run") + } + try? await Task.sleep(nanoseconds: 100_000_000) + + let startedAt = Date() + await runtime.cancel() + let cancellationSeconds = Date().timeIntervalSince(startedAt) + let outcome = await run.value + await runtime.shutdown() + + guard outcome == "error:PI 请求已取消", cancellationSeconds < 0.5 else { + throw PiTerminalRuntimeSelfCheckError.failed( + "PI stop waited for the unresponsive abort command (outcome=\(outcome), seconds=\(cancellationSeconds))" + ) + } +} + +private func checkTerminalErrorBypassesSlowProgress(_ fixture: PiTerminalRuntimeFixture) async throws { + let runtime = PiAgentRuntime( + executableURL: fixture.executableURL, + runtimeDirectory: try fixture.workingDirectory(named: "ErrorMode"), + runInactivityTimeoutNanoseconds: 2_000_000_000 + ) + let startedAt = Date() + let outcome = await terminalOutcome(runtime: runtime, revision: "error-test") { event in + if case .text = event { + try? await Task.sleep(nanoseconds: 3_000_000_000) + } + } + let completionSeconds = Date().timeIntervalSince(startedAt) + await runtime.shutdown() + + guard outcome == "error:PI 回答失败:真实终止错误", completionSeconds < 1.0 else { + throw PiTerminalRuntimeSelfCheckError.failed( + "PI terminal error was hidden or blocked behind progress delivery (outcome=\(outcome), seconds=\(completionSeconds))" + ) + } +} + +private func checkGenericEventsDoNotDefeatWatchdog(_ fixture: PiTerminalRuntimeFixture) async throws { + let runtime = PiAgentRuntime( + executableURL: fixture.executableURL, + runtimeDirectory: try fixture.workingDirectory(named: "HeartbeatMode"), + runInactivityTimeoutNanoseconds: 300_000_000 + ) + let startedAt = Date() + let outcome = await terminalOutcomeWithin( + runtime: runtime, + revision: "heartbeat-test", + timeoutNanoseconds: 1_500_000_000 + ) + let completionSeconds = Date().timeIntervalSince(startedAt) + await runtime.shutdown() + + guard outcome.contains("PI produced no events for five minutes"), completionSeconds < 1.5 else { + throw PiTerminalRuntimeSelfCheckError.failed( + "PI generic event spam defeated the inactivity watchdog (outcome=\(outcome), seconds=\(completionSeconds))" + ) + } +} + +private func terminalOutcomeWithin( + runtime: PiAgentRuntime, + revision: String, + timeoutNanoseconds: UInt64 +) async -> String { + await withTaskGroup(of: String.self) { group in + group.addTask { + await terminalOutcome(runtime: runtime, revision: revision, progress: nil) + } + group.addTask { + try? await Task.sleep(nanoseconds: timeoutNanoseconds) + return "self-check-timeout" + } + let first = await group.next() ?? "self-check-timeout" + group.cancelAll() + return first + } +} + +private func checkMeaningfulThinkingKeepsRunAlive(_ fixture: PiTerminalRuntimeFixture) async throws { + let runtime = PiAgentRuntime( + executableURL: fixture.executableURL, + runtimeDirectory: try fixture.workingDirectory(named: "ThinkingMode"), + runInactivityTimeoutNanoseconds: 300_000_000 + ) + let outcome = await terminalOutcome(runtime: runtime, revision: "thinking-test", progress: nil) + await runtime.shutdown() + + guard outcome == "reply:[材料:测试材料] 思考完成" else { + throw PiTerminalRuntimeSelfCheckError.failed( + "PI meaningful thinking did not keep the run alive (\(outcome))" + ) + } +} + +private func terminalOutcome( + runtime: PiAgentRuntime, + revision: String, + progress: StudyAgentProgressHandler? +) async -> String { + let request = StudyAgentRequest( + purpose: .conversation, + question: "请解释测试材料", + materialTitle: "测试材料", + materialText: "测试正文", + noteTitle: "测试笔记", + noteText: "", + contextRevision: revision + ) + do { + let reply = try await runtime.respond(to: request, progress: progress) + return "reply:\(reply.text)" + } catch { + return "error:\(error.localizedDescription)" + } +} + +private func makePiTerminalRuntimeFixture() throws -> PiTerminalRuntimeFixture { + let fileManager = FileManager.default + let rootURL = fileManager.temporaryDirectory + .appendingPathComponent("weibei-pi-terminal-\(UUID().uuidString)", isDirectory: true) + let runtimeURL = rootURL.appendingPathComponent("PiRuntime", isDirectory: true) + let binURL = runtimeURL.appendingPathComponent("bin", isDirectory: true) + let themeURL = binURL.appendingPathComponent("theme", isDirectory: true) + let executableURL = binURL.appendingPathComponent("pi") + let sourceURL = rootURL.appendingPathComponent("fake-pi.c") + + try fileManager.createDirectory(at: themeURL, withIntermediateDirectories: true) + try Data(fakePiTerminalSource.utf8).write(to: sourceURL, options: .atomic) + try runPiFixtureCommand( + executableURL: URL(fileURLWithPath: "/usr/bin/clang"), + arguments: [sourceURL.path, "-O0", "-o", executableURL.path] + ) + try runPiFixtureCommand( + executableURL: URL(fileURLWithPath: "/usr/bin/codesign"), + arguments: ["--force", "--sign", "-", executableURL.path] + ) + + try Data(#"{"version":"0.80.2"}"#.utf8) + .write(to: binURL.appendingPathComponent("package.json"), options: .atomic) + try Data("{}\n".utf8).write(to: themeURL.appendingPathComponent("dark.json"), options: .atomic) + try Data("{}\n".utf8).write(to: themeURL.appendingPathComponent("light.json"), options: .atomic) + try Data("MIT\n".utf8).write(to: runtimeURL.appendingPathComponent("LICENSE"), options: .atomic) + try Data("Self-check fixture only.\n".utf8) + .write(to: runtimeURL.appendingPathComponent("THIRD_PARTY_NOTICES.md"), options: .atomic) + let manifest = #"{"schemaVersion":1,"piVersion":"0.80.2","sourceRepository":"self-check","sourceCommit":"0000000000000000000000000000000000000000","license":"MIT"}"# + try Data(manifest.utf8).write(to: runtimeURL.appendingPathComponent("manifest.json"), options: .atomic) + + let executableData = try Data(contentsOf: executableURL) + let hash = SHA256.hash(data: executableData).map { String(format: "%02x", $0) }.joined() + try Data("\(hash)\n".utf8).write(to: runtimeURL.appendingPathComponent("binary.sha256"), options: .atomic) + + return PiTerminalRuntimeFixture(rootURL: rootURL, executableURL: executableURL) +} + +private func runPiFixtureCommand(executableURL: URL, arguments: [String]) throws { + let process = Process() + let pipe = Pipe() + process.executableURL = executableURL + process.arguments = arguments + process.standardOutput = pipe + process.standardError = pipe + try process.run() + process.waitUntilExit() + guard process.terminationStatus == 0 else { + let detail = String(decoding: pipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self) + throw PiTerminalRuntimeSelfCheckError.failed( + "fixture command failed: \(executableURL.lastPathComponent) \(detail)" + ) + } +} + +private let fakePiTerminalSource = #""" +#include +#include +#include +#include +#include +#include +#include +#include + +static pid_t emitter_pid = -1; +static int cancel_mode = 0; + +static int json_value(const char *line, const char *key, char *output, size_t capacity) { + char pattern[64]; + snprintf(pattern, sizeof(pattern), "\"%s\":\"", key); + const char *start = strstr(line, pattern); + if (start == NULL) return 0; + start += strlen(pattern); + const char *end = strchr(start, '\"'); + if (end == NULL) return 0; + size_t length = (size_t)(end - start); + if (length + 1 > capacity) return 0; + memcpy(output, start, length); + output[length] = '\0'; + return 1; +} + +static void respond(const char *id, const char *command, const char *data) { + printf("{\"id\":\"%s\",\"type\":\"response\",\"command\":\"%s\",\"success\":true,\"data\":%s}\n", id, command, data); + fflush(stdout); +} + +static void stop_emitter(void) { + if (emitter_pid <= 0) return; + kill(emitter_pid, SIGTERM); + waitpid(emitter_pid, NULL, 0); + emitter_pid = -1; +} + +static void terminate_fixture(int signal_number) { + (void)signal_number; + if (emitter_pid > 0) kill(emitter_pid, SIGTERM); + _exit(0); +} + +static void emit_context(const char *revision) { + printf("{\"type\":\"tool_execution_end\",\"toolCallId\":\"ctx\",\"toolName\":\"weibei_context\",\"isError\":false,\"result\":{\"details\":{\"kind\":\"weibei_context\",\"contextRevision\":\"%s\"}}}\n", revision); + fflush(stdout); +} + +static void start_emitter(void) { + if (emitter_pid > 0) return; + char cwd[PATH_MAX]; + getcwd(cwd, sizeof(cwd)); + cancel_mode = strstr(cwd, "CancelMode") != NULL; + int error_mode = strstr(cwd, "ErrorMode") != NULL; + int thinking_mode = strstr(cwd, "ThinkingMode") != NULL; + emitter_pid = fork(); + if (emitter_pid != 0) return; + + if (error_mode) { + emit_context("error-test"); + for (int index = 0; index < 256; index++) { + printf("{\"type\":\"message_update\",\"assistantMessageEvent\":{\"type\":\"text_delta\",\"delta\":\"临时文本\"}}\n"); + } + printf("{\"type\":\"message_end\",\"message\":{\"role\":\"assistant\",\"stopReason\":\"error\",\"errorMessage\":\"真实终止错误\"}}\n"); + printf("{\"type\":\"agent_end\",\"messages\":[{\"role\":\"assistant\",\"content\":[],\"stopReason\":\"error\",\"diagnostics\":[{\"error\":{\"message\":\"真实终止错误\"}}]}]}\n"); + fflush(stdout); + _exit(0); + } + + if (thinking_mode) { + emit_context("thinking-test"); + for (int index = 0; index < 6; index++) { + if (index == 1 || index == 2) { + printf("{\"type\":\"tool_execution_update\",\"toolCallId\":\"tool-long\",\"toolName\":\"weibei_course_search\"}\n"); + } else if (index == 3) { + printf("{\"type\":\"auto_retry_start\",\"attempt\":2}\n"); + } else { + printf("{\"type\":\"message_update\",\"assistantMessageEvent\":{\"type\":\"thinking_delta\",\"delta\":\"核对中\"}}\n"); + } + fflush(stdout); + usleep(120000); + } + printf("{\"type\":\"agent_end\",\"messages\":[{\"role\":\"assistant\",\"content\":[{\"type\":\"text\",\"text\":\"[材料:测试材料] 思考完成\"}],\"stopReason\":\"stop\"}]}\n"); + fflush(stdout); + _exit(0); + } + + emit_context(cancel_mode ? "cancel-test" : "heartbeat-test"); + for (;;) { + printf("{\"type\":\"future_event\"}\n"); + fflush(stdout); + usleep(20000); + } +} + +int main(void) { + signal(SIGTERM, terminate_fixture); + setvbuf(stdout, NULL, _IOLBF, 0); + char *line = NULL; + size_t line_capacity = 0; + while (getline(&line, &line_capacity, stdin) >= 0) { + char id[128]; + char type[64]; + if (!json_value(line, "id", id, sizeof(id)) || !json_value(line, "type", type, sizeof(type))) continue; + if (strcmp(type, "get_state") == 0) { + respond(id, type, "{\"isStreaming\":false}"); + } else if (strcmp(type, "get_commands") == 0) { + respond(id, type, "{\"commands\":[{\"name\":\"skill:weibei-study-companion\"},{\"name\":\"skill:weibei-course-wayfinding\"},{\"name\":\"skill:weibei-close-reading\"},{\"name\":\"skill:weibei-note-making\"},{\"name\":\"skill:weibei-recall-practice\"},{\"name\":\"skill:weibei-interactive-study\"}]}"); + } else if (strcmp(type, "prompt") == 0) { + respond(id, type, "{}"); + start_emitter(); + } else if (strcmp(type, "abort") == 0) { + if (cancel_mode) continue; + stop_emitter(); + respond(id, type, "{}"); + } else { + respond(id, type, "{}"); + } + } + stop_emitter(); + free(line); + return 0; +} +"""# diff --git a/Sources/WeiBeiSelfCheck/main.swift b/Sources/WeiBeiSelfCheck/main.swift index 5f807a260..cbd13fd7a 100644 --- a/Sources/WeiBeiSelfCheck/main.swift +++ b/Sources/WeiBeiSelfCheck/main.swift @@ -12,6 +12,12 @@ func expect(_ condition: @autoclosure () -> Bool, _ message: String) { } } +if ProcessInfo.processInfo.environment["WEIBEI_PI_TERMINAL_SELF_CHECK_ONLY"] == "1" { + try await runPiTerminalRuntimeSelfChecks() + print("WeiBei PI terminal runtime self-check passed") + exit(0) +} + try runPiAgentSelfChecks() expect(EmptyWorkspaceDayPeriod(hour: 5) == .morning @@ -793,7 +799,7 @@ for _ in 0..<200 { blankPDFIndexResult?.isTruncated == false { break } - Thread.sleep(forTimeInterval: 0.05) + try? await Task.sleep(nanoseconds: 50_000_000) } expect( mixedIndexResult?.isTruncated == true @@ -906,7 +912,7 @@ for _ in 0..<200 { query: "SPLIT_NATIVE_LAYER_PAGE_1" )[mixedPDFItem.id] if splitFailureResult?.text?.contains("SPLIT_NATIVE_LAYER_PAGE_1") == true { break } - Thread.sleep(forTimeInterval: 0.05) + try? await Task.sleep(nanoseconds: 50_000_000) } expect( splitFailureResult?.text?.contains("SPLIT_NATIVE_LAYER_PAGE_1") == true