开源 企业版 高校版 私有云 模力方舟 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
framework.ts 9.64 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 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
import {
OUTPUT_FILE_TAG,
STATUS_TAG,
SUMMARY_TAG,
TASK_ID_TAG,
TASK_NOTIFICATION_TAG,
TASK_TYPE_TAG,
TOOL_USE_ID_TAG,
} from '../../constants/xml.js'
import type { AppState } from '../../state/AppState.js'
import {
isTerminalTaskStatus,
type TaskStatus,
type TaskType,
} from '../../Task.js'
import type { TaskState } from '../../tasks/types.js'
import { enqueuePendingNotification } from '../messageQueueManager.js'
import { enqueueSdkEvent } from '../sdkEventQueue.js'
import { getTaskOutputDelta, getTaskOutputPath } from './diskOutput.js'
// Standard polling interval for all tasks
export const POLL_INTERVAL_MS = 1000
// Duration to display killed tasks before eviction
export const STOPPED_DISPLAY_MS = 3_000
// Grace period for terminal local_agent tasks in the coordinator panel
export const PANEL_GRACE_MS = 30_000
// Attachment type for task status updates
export type TaskAttachment = {
type: 'task_status'
taskId: string
toolUseId?: string
taskType: TaskType
status: TaskStatus
description: string
deltaSummary: string | null // New output since last attachment
}
type SetAppState = (updater: (prev: AppState) => AppState) => void
/**
* Update a task's state in AppState.
* Helper function for task implementations.
* Generic to allow type-safe updates for specific task types.
*/
export function updateTaskState<T extends TaskState>(
taskId: string,
setAppState: SetAppState,
updater: (task: T) => T,
): void {
setAppState(prev => {
const task = prev.tasks?.[taskId] as T | undefined
if (!task) {
return prev
}
const updated = updater(task)
if (updated === task) {
// Updater returned the same reference (early-return no-op). Skip the
// spread so s.tasks subscribers don't re-render on unchanged state.
return prev
}
return {
...prev,
tasks: {
...prev.tasks,
[taskId]: updated,
},
}
})
}
/**
* Register a new task in AppState.
*/
export function registerTask(task: TaskState, setAppState: SetAppState): void {
let isReplacement = false
setAppState(prev => {
const existing = prev.tasks[task.id]
isReplacement = existing !== undefined
// Carry forward UI-held state on re-register (resumeAgentBackground
// replaces the task; user's retain shouldn't reset). startTime keeps
// the panel sort stable; messages + diskLoaded preserve the viewed
// transcript across the replace (the user's just-appended prompt lives
// in messages and isn't on disk yet).
const merged =
existing && 'retain' in existing
? {
...task,
retain: existing.retain,
startTime: existing.startTime,
messages: existing.messages,
diskLoaded: existing.diskLoaded,
pendingMessages: existing.pendingMessages,
}
: task
return { ...prev, tasks: { ...prev.tasks, [task.id]: merged } }
})
// Replacement (resume) — not a new start. Skip to avoid double-emit.
if (isReplacement) return
enqueueSdkEvent({
type: 'system',
subtype: 'task_started',
task_id: task.id,
tool_use_id: task.toolUseId,
description: task.description,
task_type: task.type,
workflow_name:
'workflowName' in task
? (task.workflowName as string | undefined)
: undefined,
prompt: 'prompt' in task ? (task.prompt as string) : undefined,
})
}
/**
* Eagerly evict a terminal task from AppState.
* The task must be in a terminal state (completed/failed/killed) with notified=true.
* This allows memory to be freed without waiting for the next query loop iteration.
* The lazy GC in generateTaskAttachments() remains as a safety net.
*/
export function evictTerminalTask(
taskId: string,
setAppState: SetAppState,
): void {
setAppState(prev => {
const task = prev.tasks?.[taskId]
if (!task) return prev
if (!isTerminalTaskStatus(task.status)) return prev
if (!task.notified) return prev
// Panel grace period — blocks eviction until deadline passes.
// 'retain' in task narrows to LocalAgentTaskState (the only type with
// that field); evictAfter is optional so 'evictAfter' in task would
// miss tasks that haven't had it set yet.
if ('retain' in task && (task.evictAfter ?? Infinity) > Date.now()) {
return prev
}
const { [taskId]: _, ...remainingTasks } = prev.tasks
return { ...prev, tasks: remainingTasks }
})
}
/**
* Get all running tasks.
*/
export function getRunningTasks(state: AppState): TaskState[] {
const tasks = state.tasks ?? {}
return Object.values(tasks).filter(task => task.status === 'running')
}
/**
* Generate attachments for tasks with new output or status changes.
* Called by the framework to create push notifications.
*/
export async function generateTaskAttachments(state: AppState): Promise<{
attachments: TaskAttachment[]
// Only the offset patch — NOT the full task. The task may transition to
// completed during getTaskOutputDelta's async disk read, and spreading the
// full stale snapshot would clobber that transition (zombifying the task).
updatedTaskOffsets: Record<string, number>
evictedTaskIds: string[]
}> {
const attachments: TaskAttachment[] = []
const updatedTaskOffsets: Record<string, number> = {}
const evictedTaskIds: string[] = []
const tasks = state.tasks ?? {}
for (const taskState of Object.values(tasks)) {
if (taskState.notified) {
switch (taskState.status) {
case 'completed':
case 'failed':
case 'killed':
// Evict terminal tasks — they've been consumed and can be GC'd
evictedTaskIds.push(taskState.id)
continue
case 'pending':
// Keep in map — hasn't run yet, but parent already knows about it
continue
case 'running':
// Fall through to running logic below
break
}
}
if (taskState.status === 'running') {
const delta = await getTaskOutputDelta(
taskState.id,
taskState.outputOffset,
)
if (delta.content) {
updatedTaskOffsets[taskState.id] = delta.newOffset
}
}
// Completed tasks are NOT notified here — each task type handles its own
// completion notification via enqueuePendingNotification(). Generating
// attachments here would race with those per-type callbacks, causing
// dual delivery (one inline attachment + one separate API turn).
}
return { attachments, updatedTaskOffsets, evictedTaskIds }
}
/**
* Apply the outputOffset patches and evictions from generateTaskAttachments.
* Merges patches against FRESH prev.tasks (not the stale pre-await snapshot),
* so concurrent status transitions aren't clobbered.
*/
export function applyTaskOffsetsAndEvictions(
setAppState: SetAppState,
updatedTaskOffsets: Record<string, number>,
evictedTaskIds: string[],
): void {
const offsetIds = Object.keys(updatedTaskOffsets)
if (offsetIds.length === 0 && evictedTaskIds.length === 0) {
return
}
setAppState(prev => {
let changed = false
const newTasks = { ...prev.tasks }
for (const id of offsetIds) {
const fresh = newTasks[id]
// Re-check status on fresh state — task may have completed during the
// await. If it's no longer running, the offset update is moot.
if (fresh?.status === 'running') {
newTasks[id] = { ...fresh, outputOffset: updatedTaskOffsets[id]! }
changed = true
}
}
for (const id of evictedTaskIds) {
const fresh = newTasks[id]
// Re-check terminal+notified on fresh state (TOCTOU: resume may have
// replaced the task during the generateTaskAttachments await)
if (!fresh || !isTerminalTaskStatus(fresh.status) || !fresh.notified) {
continue
}
if ('retain' in fresh && (fresh.evictAfter ?? Infinity) > Date.now()) {
continue
}
delete newTasks[id]
changed = true
}
return changed ? { ...prev, tasks: newTasks } : prev
})
}
/**
* Poll all running tasks and check for updates.
* This is the main polling loop called by the framework.
*/
export async function pollTasks(
getAppState: () => AppState,
setAppState: SetAppState,
): Promise<void> {
const state = getAppState()
const { attachments, updatedTaskOffsets, evictedTaskIds } =
await generateTaskAttachments(state)
applyTaskOffsetsAndEvictions(setAppState, updatedTaskOffsets, evictedTaskIds)
// Send notifications for completed tasks
for (const attachment of attachments) {
enqueueTaskNotification(attachment)
}
}
/**
* Enqueue a task notification to the message queue.
*/
function enqueueTaskNotification(attachment: TaskAttachment): void {
const statusText = getStatusText(attachment.status)
const outputPath = getTaskOutputPath(attachment.taskId)
const toolUseIdLine = attachment.toolUseId
? `\n<${TOOL_USE_ID_TAG}>${attachment.toolUseId}</${TOOL_USE_ID_TAG}>`
: ''
const message = `<${TASK_NOTIFICATION_TAG}>
<${TASK_ID_TAG}>${attachment.taskId}</${TASK_ID_TAG}>${toolUseIdLine}
<${TASK_TYPE_TAG}>${attachment.taskType}</${TASK_TYPE_TAG}>
<${OUTPUT_FILE_TAG}>${outputPath}</${OUTPUT_FILE_TAG}>
<${STATUS_TAG}>${attachment.status}</${STATUS_TAG}>
<${SUMMARY_TAG}>Task "${attachment.description}" ${statusText}</${SUMMARY_TAG}>
</${TASK_NOTIFICATION_TAG}>`
enqueuePendingNotification({ value: message, mode: 'task-notification' })
}
/**
* Get human-readable status text.
*/
function getStatusText(status: TaskStatus): string {
switch (status) {
case 'completed':
return 'completed successfully'
case 'failed':
return 'failed'
case 'killed':
return 'was stopped'
case 'running':
return 'is running'
case 'pending':
return 'is pending'
}
}
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 によって変換されたページ (->オリジナル) /