开源 企业版 高校版 私有云 模力方舟 AI 队友
代码拉取完成,页面将自动刷新
加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
已有帐号? 立即登录
文件
main
分支 (1)
标签 (1)
main
v0.1.0
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
项目仓库所选许可证以仓库主分支所使用许可证为准
main
分支 (1)
标签 (1)
main
v0.1.0
克隆/下载
克隆/下载
提示
下载代码请复制以下命令到终端执行
为确保你提交的代码身份被 Gitee 正确识别,请执行以下命令完成配置
初次使用 SSH 协议进行代码克隆、推送等操作时,需按下述提示完成 SSH 配置
1 生成 RSA 密钥
2 获取 RSA 公钥内容,并配置到 SSH公钥
在 Gitee 上使用 SVN,请访问 使用指南
使用 HTTPS 协议时,命令行会出现如下账号密码验证步骤。基于安全考虑,Gitee 建议 配置并使用私人令牌 替代登录密码进行克隆、推送等操作
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # 私人令牌
main
分支 (1)
标签 (1)
main
v0.1.0
remoteIO.ts 9.71 KB
一键复制 编辑 原始数据 按行查看 历史
sanbucat 提交于 2026年03月31日 17:08 +08:00 . v2.1.88 反编译源码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
import type { StdoutMessage } from 'src/entrypoints/sdk/controlTypes.js'
import { PassThrough } from 'stream'
import { URL } from 'url'
import { getSessionId } from '../bootstrap/state.js'
import { getPollIntervalConfig } from '../bridge/pollConfig.js'
import { registerCleanup } from '../utils/cleanupRegistry.js'
import { setCommandLifecycleListener } from '../utils/commandLifecycle.js'
import { isDebugMode, logForDebugging } from '../utils/debug.js'
import { logForDiagnosticsNoPII } from '../utils/diagLogs.js'
import { isEnvTruthy } from '../utils/envUtils.js'
import { errorMessage } from '../utils/errors.js'
import { gracefulShutdown } from '../utils/gracefulShutdown.js'
import { logError } from '../utils/log.js'
import { writeToStdout } from '../utils/process.js'
import { getSessionIngressAuthToken } from '../utils/sessionIngressAuth.js'
import {
setSessionMetadataChangedListener,
setSessionStateChangedListener,
} from '../utils/sessionState.js'
import {
setInternalEventReader,
setInternalEventWriter,
} from '../utils/sessionStorage.js'
import { ndjsonSafeStringify } from './ndjsonSafeStringify.js'
import { StructuredIO } from './structuredIO.js'
import { CCRClient, CCRInitError } from './transports/ccrClient.js'
import { SSETransport } from './transports/SSETransport.js'
import type { Transport } from './transports/Transport.js'
import { getTransportForUrl } from './transports/transportUtils.js'
/**
* Bidirectional streaming for SDK mode with session tracking
* Supports WebSocket transport
*/
export class RemoteIO extends StructuredIO {
private url: URL
private transport: Transport
private inputStream: PassThrough
private readonly isBridge: boolean = false
private readonly isDebug: boolean = false
private ccrClient: CCRClient | null = null
private keepAliveTimer: ReturnType<typeof setInterval> | null = null
constructor(
streamUrl: string,
initialPrompt?: AsyncIterable<string>,
replayUserMessages?: boolean,
) {
const inputStream = new PassThrough({ encoding: 'utf8' })
super(inputStream, replayUserMessages)
this.inputStream = inputStream
this.url = new URL(streamUrl)
// Prepare headers with session token if available
const headers: Record<string, string> = {}
const sessionToken = getSessionIngressAuthToken()
if (sessionToken) {
headers['Authorization'] = `Bearer ${sessionToken}`
} else {
logForDebugging('[remote-io] No session ingress token available', {
level: 'error',
})
}
// Add environment runner version if available (set by Environment Manager)
const erVersion = process.env.CLAUDE_CODE_ENVIRONMENT_RUNNER_VERSION
if (erVersion) {
headers['x-environment-runner-version'] = erVersion
}
// Provide a callback that re-reads the session token dynamically.
// When the parent process refreshes the token (via token file or env var),
// the transport can pick it up on reconnection.
const refreshHeaders = (): Record<string, string> => {
const h: Record<string, string> = {}
const freshToken = getSessionIngressAuthToken()
if (freshToken) {
h['Authorization'] = `Bearer ${freshToken}`
}
const freshErVersion = process.env.CLAUDE_CODE_ENVIRONMENT_RUNNER_VERSION
if (freshErVersion) {
h['x-environment-runner-version'] = freshErVersion
}
return h
}
// Get appropriate transport based on URL protocol
this.transport = getTransportForUrl(
this.url,
headers,
getSessionId(),
refreshHeaders,
)
// Set up data callback
this.isBridge = process.env.CLAUDE_CODE_ENVIRONMENT_KIND === 'bridge'
this.isDebug = isDebugMode()
this.transport.setOnData((data: string) => {
this.inputStream.write(data)
if (this.isBridge && this.isDebug) {
writeToStdout(data.endsWith('\n') ? data : data + '\n')
}
})
// Set up close callback to handle connection failures
this.transport.setOnClose(() => {
// End the input stream to trigger graceful shutdown
this.inputStream.end()
})
// Initialize CCR v2 client (heartbeats, epoch, state reporting, event writes).
// The CCRClient constructor wires the SSE received-ack handler
// synchronously, so new CCRClient() MUST run before transport.connect() —
// otherwise early SSE frames hit an unwired onEventCallback and their
// 'received' delivery acks are silently dropped.
if (isEnvTruthy(process.env.CLAUDE_CODE_USE_CCR_V2)) {
// CCR v2 is SSE+POST by definition. getTransportForUrl returns
// SSETransport under the same env var, but the two checks live in
// different files — assert the invariant so a future decoupling
// fails loudly here instead of confusingly inside CCRClient.
if (!(this.transport instanceof SSETransport)) {
throw new Error(
'CCR v2 requires SSETransport; check getTransportForUrl',
)
}
this.ccrClient = new CCRClient(this.transport, this.url)
const init = this.ccrClient.initialize()
this.restoredWorkerState = init.catch(() => null)
init.catch((error: unknown) => {
logForDiagnosticsNoPII('error', 'cli_worker_lifecycle_init_failed', {
reason: error instanceof CCRInitError ? error.reason : 'unknown',
})
logError(
new Error(`CCRClient initialization failed: ${errorMessage(error)}`),
)
void gracefulShutdown(1, 'other')
})
registerCleanup(async () => this.ccrClient?.close())
// Register internal event writer for transcript persistence.
// When set, sessionStorage writes transcript messages as CCR v2
// internal events instead of v1 Session Ingress.
setInternalEventWriter((eventType, payload, options) =>
this.ccrClient!.writeInternalEvent(eventType, payload, options),
)
// Register internal event readers for session resume.
// When set, hydrateFromCCRv2InternalEvents() can fetch foreground
// and subagent internal events to reconstruct conversation state.
setInternalEventReader(
() => this.ccrClient!.readInternalEvents(),
() => this.ccrClient!.readSubagentInternalEvents(),
)
const LIFECYCLE_TO_DELIVERY = {
started: 'processing',
completed: 'processed',
} as const
setCommandLifecycleListener((uuid, state) => {
this.ccrClient?.reportDelivery(uuid, LIFECYCLE_TO_DELIVERY[state])
})
setSessionStateChangedListener((state, details) => {
this.ccrClient?.reportState(state, details)
})
setSessionMetadataChangedListener(metadata => {
this.ccrClient?.reportMetadata(metadata)
})
}
// Start connection only after all callbacks are wired (setOnData above,
// setOnEvent inside new CCRClient() when CCR v2 is enabled).
void this.transport.connect()
// Push a silent keep_alive frame on a fixed interval so upstream
// proxies and the session-ingress layer don't GC an otherwise-idle
// remote control session. The keep_alive type is filtered before
// reaching any client UI (Query.ts drops it; structuredIO.ts drops it;
// web/iOS/Android never see it in their message loop). Interval comes
// from GrowthBook (tengu_bridge_poll_interval_config
// session_keepalive_interval_v2_ms, default 120s); 0 = disabled.
// Bridge-only: fixes Envoy idle timeout on bridge-topology sessions
// (#21931). byoc workers ran without this before #21931 and do not
// need it — different network path.
const keepAliveIntervalMs =
getPollIntervalConfig().session_keepalive_interval_v2_ms
if (this.isBridge && keepAliveIntervalMs > 0) {
this.keepAliveTimer = setInterval(() => {
logForDebugging('[remote-io] keep_alive sent')
void this.write({ type: 'keep_alive' }).catch(err => {
logForDebugging(
`[remote-io] keep_alive write failed: ${errorMessage(err)}`,
)
})
}, keepAliveIntervalMs)
this.keepAliveTimer.unref?.()
}
// Register for graceful shutdown cleanup
registerCleanup(async () => this.close())
// If initial prompt is provided, send it through the input stream
if (initialPrompt) {
// Convert the initial prompt to the input stream format.
// Chunks from stdin may already contain trailing newlines, so strip
// them before appending our own to avoid double-newline issues that
// cause structuredIO to parse empty lines. String() handles both
// string chunks and Buffer objects from process.stdin.
const stream = this.inputStream
void (async () => {
for await (const chunk of initialPrompt) {
stream.write(String(chunk).replace(/\n$/, '') + '\n')
}
})()
}
}
override flushInternalEvents(): Promise<void> {
return this.ccrClient?.flushInternalEvents() ?? Promise.resolve()
}
override get internalEventsPending(): number {
return this.ccrClient?.internalEventsPending ?? 0
}
/**
* Send output to the transport.
* In bridge mode, control_request messages are always echoed to stdout so the
* bridge parent can detect permission requests. Other messages are echoed only
* in debug mode.
*/
async write(message: StdoutMessage): Promise<void> {
if (this.ccrClient) {
await this.ccrClient.writeEvent(message)
} else {
await this.transport.write(message)
}
if (this.isBridge) {
if (message.type === 'control_request' || this.isDebug) {
writeToStdout(ndjsonSafeStringify(message) + '\n')
}
}
}
/**
* Clean up connections gracefully
*/
close(): void {
if (this.keepAliveTimer) {
clearInterval(this.keepAliveTimer)
this.keepAliveTimer = null
}
this.transport.close()
this.inputStream.end()
}
}
Loading...
举报
举报成功
我们将于2个工作日内通过站内信反馈结果给你!
请认真填写举报原因,尽可能描述详细。
请选择举报类型
取消
发送
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

发行版

暂无发行版

贡献者

全部

近期动态

不能加载更多了
编辑仓库简介
简介内容
主页
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/up/claude-code-source-code.git
git@gitee.com:up/claude-code-source-code.git
up
claude-code-source-code
claude-code-source-code
main
点此查找更多帮助

搜索帮助

评论
仓库举报
回到顶部
登录提示
该操作需登录 Gitee 帐号,请先登录后再操作。
立即登录
没有帐号,去注册

AltStyle によって変換されたページ (->オリジナル) /