zapagent 1.14.16 → 1.14.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/agent/wireRunHandlers.ts +8 -4
- package/src/goal-host.ts +3 -1
- package/src/goal-output.ts +90 -0
- package/src/goal-session.ts +6 -1
- package/src/goal-turn-host.ts +3 -1
- package/src/hooks/useAgentRunner.ts +3 -0
- package/src/index.tsx +8 -4
package/package.json
CHANGED
|
@@ -53,6 +53,8 @@ export interface RunHandlersDeps {
|
|
|
53
53
|
currentConfig: AppConfig
|
|
54
54
|
controller: AbortController
|
|
55
55
|
preview: StreamingPreview
|
|
56
|
+
/** Optional display-only projection; persisted runtime events stay intact. */
|
|
57
|
+
presentContent?: (event: AgentEvent) => AgentEvent | undefined
|
|
56
58
|
|
|
57
59
|
setStatus: (s: string) => void
|
|
58
60
|
setOutputThroughput?: (sample: OutputThroughputSample | undefined) => void
|
|
@@ -332,8 +334,9 @@ export function createRunHandlers(deps: RunHandlersDeps): RunHandlers {
|
|
|
332
334
|
// as part of the next successful response.
|
|
333
335
|
deps.preview.onThinkingFinal(e.id)
|
|
334
336
|
})
|
|
335
|
-
agent.on("content_delta", (
|
|
336
|
-
|
|
337
|
+
agent.on("content_delta", (event: AgentEvent) => {
|
|
338
|
+
const e = deps.presentContent ? deps.presentContent(event) : event
|
|
339
|
+
if (e?.type !== "content_delta") return
|
|
337
340
|
if (e.kind === "text") {
|
|
338
341
|
deps.setStatus("writing")
|
|
339
342
|
deps.preview.onTextDelta(e.id, e.text)
|
|
@@ -343,8 +346,9 @@ export function createRunHandlers(deps: RunHandlersDeps): RunHandlers {
|
|
|
343
346
|
}
|
|
344
347
|
})
|
|
345
348
|
|
|
346
|
-
agent.on("content_final", (
|
|
347
|
-
|
|
349
|
+
agent.on("content_final", (event: AgentEvent) => {
|
|
350
|
+
const e = deps.presentContent ? deps.presentContent(event) : event
|
|
351
|
+
if (e?.type !== "content_final") return
|
|
348
352
|
switch (e.kind) {
|
|
349
353
|
case "text": {
|
|
350
354
|
// Flush every paragraph + the trailing in-flight paragraph as a
|
package/src/goal-host.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { createHash, randomUUID } from "node:crypto"
|
|
2
|
+
import { createGoalContentFilter } from "./goal-output.js"
|
|
2
3
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"
|
|
3
4
|
import { cp, lstat, rm } from "node:fs/promises"
|
|
4
5
|
import { join, relative, sep } from "node:path"
|
|
@@ -185,8 +186,9 @@ export class LocalGoalHost implements GoalHost {
|
|
|
185
186
|
}
|
|
186
187
|
private getWorkspace(): GoalWorkspace { if (!this.workspace) throw new Error("Goal workspace unavailable"); return this.workspace }
|
|
187
188
|
private phaseHooks(context: GoalOperationContext) {
|
|
189
|
+
const present = createGoalContentFilter(["planning", "verifying", "final_verifying"].includes(context.goal.phase ?? ""))
|
|
188
190
|
return {
|
|
189
|
-
...(this.onEvent ? { onEvent: (event: import("../zapsdk/agent/events.js").AgentEvent) => this.onEvent!(
|
|
191
|
+
...(this.onEvent ? { onEvent: (event: import("../zapsdk/agent/events.js").AgentEvent) => { const visible = present(event); if (visible) this.onEvent!(visible, context.operationId) } } : {}),
|
|
190
192
|
onSpawn: (pid: number, mayLaunchSealedProcess: boolean) => {
|
|
191
193
|
if (this.state?.phaseProcess) throw new Error("Previous Goal child process is unresolved")
|
|
192
194
|
this.state!.phaseProcess = { pid, operationId: context.operationId, requiresReceipt: mayLaunchSealedProcess }; this.persist()
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import type { AgentEvent } from "../zapsdk/agent/events.js"
|
|
2
|
+
import type { GoalRecord } from "../zapsdk/goal/contracts.js"
|
|
3
|
+
|
|
4
|
+
const dsmlPrefixes = ["||DSML||", "|DSML|", "||DSML||"].flatMap(marker => [`<${marker}`, `</${marker}`])
|
|
5
|
+
|
|
6
|
+
/** Presentation only: keep incomplete protocol tags out of streamed output,
|
|
7
|
+
* without buffering whole replies or stripping ordinary HTML/JSON/code. */
|
|
8
|
+
function dsmlStream() {
|
|
9
|
+
let pending = "", insideTag = false
|
|
10
|
+
return {
|
|
11
|
+
push(chunk: string): string {
|
|
12
|
+
const input = pending + chunk
|
|
13
|
+
pending = ""
|
|
14
|
+
let output = "", offset = 0
|
|
15
|
+
while (offset < input.length) {
|
|
16
|
+
if (insideTag) {
|
|
17
|
+
const end = input.indexOf(">", offset)
|
|
18
|
+
if (end < 0) return output
|
|
19
|
+
insideTag = false; offset = end + 1
|
|
20
|
+
continue
|
|
21
|
+
}
|
|
22
|
+
const start = input.indexOf("<", offset)
|
|
23
|
+
if (start < 0) return output + input.slice(offset)
|
|
24
|
+
output += input.slice(offset, start)
|
|
25
|
+
const tail = input.slice(start)
|
|
26
|
+
if (dsmlPrefixes.some(prefix => tail.startsWith(prefix))) {
|
|
27
|
+
insideTag = true; offset = start
|
|
28
|
+
} else if (dsmlPrefixes.some(prefix => prefix.startsWith(tail))) {
|
|
29
|
+
pending = tail
|
|
30
|
+
return output
|
|
31
|
+
} else {
|
|
32
|
+
output += "<"; offset = start + 1
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return output
|
|
36
|
+
},
|
|
37
|
+
finish(): string {
|
|
38
|
+
const tail = /^<\/?[||]/.test(pending) ? "" : pending
|
|
39
|
+
pending = ""; insideTag = false
|
|
40
|
+
return tail
|
|
41
|
+
},
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function stripGoalProtocolTags(text: string): string {
|
|
46
|
+
const stream = dsmlStream()
|
|
47
|
+
return stream.push(text) + stream.finish()
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Raw events still feed persistence and acceptance. Only their UI projection
|
|
51
|
+
* suppresses planner/verifier protocol prose; tool and lifecycle events remain. */
|
|
52
|
+
export function createGoalContentFilter(structured = false) {
|
|
53
|
+
const streams = new Map<string, ReturnType<typeof dsmlStream>>()
|
|
54
|
+
return (event: AgentEvent): AgentEvent | undefined => {
|
|
55
|
+
if ((event.type !== "content_delta" && event.type !== "content_final") || (event.kind !== "text" && event.kind !== "thinking")) return event
|
|
56
|
+
if (structured) return undefined
|
|
57
|
+
const key = JSON.stringify([event.path ?? [], event.kind, event.id])
|
|
58
|
+
if (event.type === "content_final") {
|
|
59
|
+
streams.delete(key)
|
|
60
|
+
return { ...event, text: stripGoalProtocolTags(event.text) }
|
|
61
|
+
}
|
|
62
|
+
let stream = streams.get(key)
|
|
63
|
+
if (!stream) { stream = dsmlStream(); streams.set(key, stream) }
|
|
64
|
+
const text = stream.push(event.text)
|
|
65
|
+
return text ? { ...event, text } : undefined
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function goalAcceptanceSummary(goal: GoalRecord): string | undefined {
|
|
70
|
+
const receipt = goal.finalReceipt ?? goal.tasks.find(task => task.receipt && task.receipt.status !== "passed")?.receipt
|
|
71
|
+
if (!receipt) return undefined
|
|
72
|
+
if (receipt.status === "passed") {
|
|
73
|
+
if (goal.status === "ready_for_delivery") return "Goal 验收通过,等待交付授权。"
|
|
74
|
+
return goal.status === "completed" ? "Goal 验收通过。" : "Goal 尚未完成最终验收和交付。"
|
|
75
|
+
}
|
|
76
|
+
if (receipt.status === "failed") return "Goal 验收未通过。"
|
|
77
|
+
if (receipt.status === "error") return "Goal 验收未完成:检查执行失败。"
|
|
78
|
+
return "Goal 验收尚未确认,需要补充信息或授权。"
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function goalDeliveryMarkdown(delivery: unknown): string | undefined {
|
|
82
|
+
if (!delivery || typeof delivery !== "object") return undefined
|
|
83
|
+
const value = delivery as { text?: unknown; path?: unknown }
|
|
84
|
+
if (typeof value.text === "string") {
|
|
85
|
+
const text = stripGoalProtocolTags(value.text)
|
|
86
|
+
return text.trim() ? text : undefined
|
|
87
|
+
}
|
|
88
|
+
if (typeof value.path === "string") return `Goal 产物目录:${value.path}`
|
|
89
|
+
return undefined
|
|
90
|
+
}
|
package/src/goal-session.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { GoalStore } from "../zapsdk/goal/store.js"
|
|
|
3
3
|
import type { GoalRecord } from "../zapsdk/goal/contracts.js"
|
|
4
4
|
import type { AgentEvent } from "../zapsdk/agent/events.js"
|
|
5
5
|
import type { PermissionMode } from "./config.js"
|
|
6
|
+
import { goalAcceptanceSummary, goalDeliveryMarkdown } from "./goal-output.js"
|
|
6
7
|
|
|
7
8
|
export interface GoalSessionOptions {
|
|
8
9
|
runTurn?: import("./goal-turn.js").GoalTurnExecutor
|
|
@@ -11,6 +12,7 @@ export interface GoalSessionOptions {
|
|
|
11
12
|
signal?: AbortSignal
|
|
12
13
|
onStart?: (goal: GoalRecord) => void
|
|
13
14
|
onMessage: (text: string) => void
|
|
15
|
+
onResult?: (markdown: string) => void
|
|
14
16
|
onState?: (goal: GoalRecord) => void
|
|
15
17
|
onEvent?: (event: AgentEvent, scope: string) => void
|
|
16
18
|
}
|
|
@@ -70,7 +72,10 @@ export async function executeGoalCommand(args: string[], cwd: string, options: G
|
|
|
70
72
|
}
|
|
71
73
|
if (outcome) {
|
|
72
74
|
options.onMessage(`Goal ${outcome.id} · ${outcome.status}${outcome.stopReason ? ` · ${outcome.stopReason}` : ""}`)
|
|
73
|
-
|
|
75
|
+
const acceptance = goalAcceptanceSummary(outcome)
|
|
76
|
+
if (acceptance) options.onMessage(acceptance)
|
|
77
|
+
const markdown = ["completed", "ready_for_delivery"].includes(outcome.status) ? goalDeliveryMarkdown(outcome.delivery) : undefined
|
|
78
|
+
if (markdown) (options.onResult ?? options.onMessage)(markdown)
|
|
74
79
|
}
|
|
75
80
|
return code
|
|
76
81
|
} finally { attached.delete(key); settle() }
|
package/src/goal-turn-host.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { z } from "zod"
|
|
2
|
+
import { createGoalContentFilter } from "./goal-output.js"
|
|
2
3
|
import { canonicalizeWithNearestExistingAncestorSync } from "../zapsdk/builtin-tools/filesystem.js"
|
|
3
4
|
import { createHash, randomUUID } from "node:crypto"
|
|
4
5
|
import { constants, existsSync, mkdirSync, readFileSync } from "node:fs"
|
|
@@ -207,7 +208,8 @@ export class GoalTurnHost implements GoalHost {
|
|
|
207
208
|
return { kind: "retry" as const }
|
|
208
209
|
}
|
|
209
210
|
private async turn(context: GoalOperationContext, role: GoalTurnInput["role"], prompt: string, observe?: (event: AgentEvent) => void): Promise<GoalTurnResult> {
|
|
210
|
-
const
|
|
211
|
+
const present = createGoalContentFilter(role === "planner" || role === "verifier")
|
|
212
|
+
const onEvent = (event: AgentEvent) => { observe?.(event); const visible = present(event); if (visible) this.onEvent?.(visible, context.operationId) }
|
|
211
213
|
const input: GoalTurnInput = { cwd: context.goal.cwd, goalId: context.goal.id, epoch: context.goal.ownerEpoch, ledgerPath: goalDatabasePath(),
|
|
212
214
|
role, prompt, permissionMode: context.goal.permissionMode, signal: context.signal, onEvent: this.executeTurn && ["worker", "repair"].includes(role) ? event => observe?.(event) : onEvent, sessionId: this.state!.sessionId }
|
|
213
215
|
if (this.executeTurn && ["worker", "repair"].includes(role)) {
|
|
@@ -2,6 +2,7 @@ import { goalTurnMeter, type GoalTurnInput } from "../goal-turn.js"
|
|
|
2
2
|
import { RetryProvider } from "../../zapsdk/core/retry.js"
|
|
3
3
|
import type { AgentOutcomeV1 } from "../../zapsdk/runtime/outcome.js"
|
|
4
4
|
import { executeGoalCommand } from "../goal-session.js"
|
|
5
|
+
import { createGoalContentFilter } from "../goal-output.js"
|
|
5
6
|
import { createGoalPresentation } from "../agent/goalPresentation.js"
|
|
6
7
|
import { AgentBudget } from "../../zapsdk/agent/budget.js"
|
|
7
8
|
import { RequestMeter } from "../../zapsdk/agent/request-meter.js"
|
|
@@ -726,6 +727,7 @@ export function useAgentRunner({
|
|
|
726
727
|
currentConfig,
|
|
727
728
|
controller,
|
|
728
729
|
preview: runPreview,
|
|
730
|
+
presentContent: invocation?.goalTurn ? createGoalContentFilter() : undefined,
|
|
729
731
|
setStatus, setStep, setActiveTool, setActiveToolBytes,
|
|
730
732
|
setProviderRequest, setOutputThroughput,
|
|
731
733
|
setContextTokens, setContextPending, setContextDiagnostics: recordContextDiagnostics,
|
|
@@ -994,6 +996,7 @@ export function useAgentRunner({
|
|
|
994
996
|
}
|
|
995
997
|
},
|
|
996
998
|
onMessage: text => addLog("system", text),
|
|
999
|
+
onResult: text => { presentation?.finish(); addLog("agent", text) },
|
|
997
1000
|
})
|
|
998
1001
|
} finally {
|
|
999
1002
|
if (presentation) {
|
package/src/index.tsx
CHANGED
|
@@ -115,7 +115,7 @@ if (args[0] === "goal") {
|
|
|
115
115
|
const [{ executeGoalCommand }, { loadAppConfig }, { getAppDataDir }] = await Promise.all([
|
|
116
116
|
import("./goal-session.js"), import("./config.js"), import("../zapsdk/utils/platform.js"),
|
|
117
117
|
])
|
|
118
|
-
const displayed = new
|
|
118
|
+
const displayed = new Map<string, string>()
|
|
119
119
|
let lastPhase = ""
|
|
120
120
|
try { process.exit(await executeGoalCommand(args.slice(1), process.cwd(), {
|
|
121
121
|
permissionMode: loadAppConfig(join(getAppDataDir(), "config.json")).permissionMode,
|
|
@@ -123,9 +123,13 @@ if (args[0] === "goal") {
|
|
|
123
123
|
onState: goal => { const phase = `${goal.status}/${goal.phase ?? "preparing"}`; if (phase !== lastPhase) { lastPhase = phase; process.stdout.write(`\nGoal ${phase} · ${goal.tasks.filter(t => t.status === "passed").length}/${goal.tasks.length} tasks\n`) } },
|
|
124
124
|
onEvent: (event, scope) => {
|
|
125
125
|
if ((event.type === "content_delta" || event.type === "content_final") && (event.kind === "text" || event.kind === "thinking")) {
|
|
126
|
-
const key =
|
|
127
|
-
if (event.type === "content_delta") { displayed.
|
|
128
|
-
else {
|
|
126
|
+
const key = JSON.stringify([scope, event.path ?? [], event.kind, event.id])
|
|
127
|
+
if (event.type === "content_delta") { displayed.set(key, (displayed.get(key) ?? "") + event.text); process.stdout.write(event.text) }
|
|
128
|
+
else {
|
|
129
|
+
const prior = displayed.get(key) ?? ""
|
|
130
|
+
if (event.text.startsWith(prior)) process.stdout.write(event.text.slice(prior.length))
|
|
131
|
+
displayed.delete(key); process.stdout.write("\n")
|
|
132
|
+
}
|
|
129
133
|
} else if (event.type === "content_final" && event.kind === "tool_call") process.stdout.write(`\n${event.path?.length ? "Child " : ""}Tool ${event.toolName}: ${JSON.stringify(event.arguments)}\n`)
|
|
130
134
|
else if (event.type === "content_final" && event.kind === "tool_result") process.stdout.write(`Tool ${event.toolName}: ${event.result.success ? "ok" : "failed"} ${event.result.output ?? event.result.error ?? ""}\n`)
|
|
131
135
|
else if (event.type === "error") process.stderr.write(event.error + "\n")
|