zapagent 1.14.15 → 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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zapagent",
3
- "version": "1.14.15",
3
+ "version": "1.14.17",
4
4
  "packageManager": "bun@1.3.14",
5
5
  "author": "",
6
6
  "main": "src/index.tsx",
@@ -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", (e: AgentEvent) => {
336
- if (e.type !== "content_delta") return
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", (e: AgentEvent) => {
347
- if (e.type !== "content_final") return
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
@@ -67,17 +67,15 @@ export function startGoalBackgroundRunner(goal: GoalRecord): void {
67
67
  }
68
68
 
69
69
  /** The same command implementation is used by the TUI and the CLI. */
70
- export function goalCommand(args: string[], cwd: string, currentMode: import("./config.js").PermissionMode = "default", platform: NodeJS.Platform = process.platform, sessionId?: string, onForeground?: (goal: GoalRecord) => void): string {
70
+ export function goalCommand(args: string[], cwd: string, currentMode: import("./config.js").PermissionMode = "default", platform: NodeJS.Platform = process.platform, sessionId?: string, onForeground?: (goal: GoalRecord) => void, enforceSessionMode = false): string {
71
71
  const action = args[0] ?? ""
72
72
  if (!action || action === "help") return [
73
73
  "Usage: /goal <objective> [--background] [--artifact] [--strict] [--accept-edits | --permission-mode=MODE] [--check=bun|npm|pytest|go] [--install=npm] [--tokens=N] [--minutes=N] [--model-calls=N] [--tool-calls=N] | status [id] | list | pause [id] | resume [id] | cancel [id] | budget extend [id] --tokens=N --minutes=N",
74
74
  "Goals run in the current session by default. Use --background to detach, or /goal background to hand off at a safe boundary.",
75
75
  "Goals run until independent acceptance and delivery, with no default token, call or time limit. Use pause or cancel to interrupt.",
76
- "Goal execution is not yet supported on Windows; --check requires a VM backend with verified process sealing.",
77
- "Git Goal currently supports macOS repository roots with an existing commit and ordinary SHA-1 metadata; linked worktrees, alternates, shallow and SHA-256 repositories are unavailable.",
78
- "Git commits remain private to the Goal; delivery changes files only, not the source index or refs. The private index starts from HEAD and does not preserve staged/unstaged grouping.",
79
- "--install=npm uses package-lock v3, official npm registry tarballs and an offline VM install with lifecycle scripts disabled.",
80
- "The lockfile must exist before starting; changing package.json or package-lock.json during the Goal blocks it. Existing node_modules is never overwritten. Verifier workspaces are read-only.",
76
+ "Goals use the current workspace and ordinary tool permissions. --artifact explicitly selects the legacy isolated-artifact workflow.",
77
+ "Goal execution is not yet supported on Windows.",
78
+ "--check runs the requested test command through normal tool permissions. --install=npm requests ordinary dependency installation; it does not grant shell permission.",
81
79
  "--accept-edits authorizes file edits but does not authorize shell commands or artifact merges requiring confirmation.",
82
80
  ].join("\n")
83
81
  const control = ["list", "status", "watch", "pause", "cancel", "resume", "budget"].includes(action)
@@ -87,8 +85,8 @@ export function goalCommand(args: string[], cwd: string, currentMode: import("./
87
85
  const modeArgs = args.filter(arg => arg === "--permission-mode" || arg.startsWith("--permission-mode="))
88
86
  if (!control && (modeArgs.length > 1 || modeArgs.some(arg => !/^--permission-mode=(default|acceptEdits|bypassPermissions|plan)$/.test(arg)) || modeArgs.length > 0 && args.includes("--accept-edits"))) throw new Error("Invalid Goal permission mode")
89
87
  if (!control && (installArgs.length > 1 || installArgs.some(arg => arg !== "--install=npm"))) throw new Error("Invalid Goal dependency installation; use --install=npm")
90
- if (!control && installArgs.length && !machineCheckSupported(cwd)) throw new Error("Goal --install=npm requires a VM backend with verified process sealing.")
91
- if (!control && checkArgs.length && !machineCheckSupported(cwd)) throw new Error("Goal --check machine verification is currently unavailable: process-tree sealing cannot be verified.")
88
+ if (!control && args.includes("--artifact") && installArgs.length && !machineCheckSupported(cwd)) throw new Error("Goal --install=npm requires a VM backend with verified process sealing.")
89
+ if (!control && args.includes("--artifact") && checkArgs.length && !machineCheckSupported(cwd)) throw new Error("Goal --check machine verification is currently unavailable: process-tree sealing cannot be verified.")
92
90
  if (!control && (checkArgs.length > 1 || checkArgs.some(arg => !/^--check=(bun|npm|pytest|go)$/.test(arg)))) throw new Error("Invalid Goal machine check; use --check=bun, npm, pytest or go")
93
91
  const background = args.includes("--background")
94
92
  if (args.filter(arg => arg === "--background").length > 1 || args.some(arg => arg.startsWith("--background="))) throw new Error("Invalid Goal background flag")
@@ -107,6 +105,10 @@ export function goalCommand(args: string[], cwd: string, currentMode: import("./
107
105
  }
108
106
  if (limits.maxTokens !== undefined) limits.reservedTokens = Math.min(50_000, Math.floor(limits.maxTokens * 0.05))
109
107
  if ((!control || action === "resume") && !background && !onForeground) throw new Error("A foreground Goal launcher is required")
108
+ if (enforceSessionMode && !control && !background) {
109
+ const requested = args.includes("--accept-edits") ? "acceptEdits" : modeArgs[0]?.slice("--permission-mode=".length) ?? currentMode
110
+ if (requested !== currentMode) throw new Error("Goal uses the current session permission mode; change the session mode before starting a Goal")
111
+ }
110
112
  const launch = (goal: GoalRecord) => background ? startGoalBackgroundRunner(goal) : onForeground!(goal)
111
113
  const store = new GoalStore(goalDatabasePath(), { requireLedger: true })
112
114
  try {
@@ -126,7 +128,7 @@ export function goalCommand(args: string[], cwd: string, currentMode: import("./
126
128
  ...(goal.failure ? [`Failure: ${JSON.stringify(goal.failure)}`] : []),
127
129
  ...(goal.progress ? [`Progress: ${JSON.stringify(goal.progress)}`] : []),
128
130
  `Tasks: ${goal.tasks.filter(task => task.status === "passed").length}/${goal.tasks.length}`,
129
- ...(goal.dependencyInstall ? ["Dependencies: npm (official registry, package-lock v3, scripts disabled)"] : []),
131
+ ...(goal.dependencyInstall ? ["Dependencies: npm (normal tool permissions)"] : []),
130
132
  `Usage: ${budget.totals.modelCalls} model calls · ${budget.totals.toolCalls} tool calls · ${budget.totals.tokensUsed} tokens · ${budget.totals.unknownUsage} unknown usage · ${budget.totals.opaqueToolCalls} unmetered tool calls (${budget.limits.strict === false ? "observed" : "strict"})`,
131
133
  ...(goal.delivery ? [`Artifact: ${JSON.stringify(goal.delivery)}`] : []),
132
134
  `Log: ${join(goalHome(goal.id), "runner.log")}`,
@@ -152,7 +154,8 @@ export function goalCommand(args: string[], cwd: string, currentMode: import("./
152
154
  }
153
155
  if (action === "resume") {
154
156
  const goal = selectGoal(store, cwd, args[1], sessionId)
155
- if ((goal.machineCheck || goal.dependencyInstall) && !machineCheckSupported(cwd)) throw new Error("Goal VM execution is currently unavailable: process-tree sealing cannot be verified.")
157
+ if (goal.executionMode !== "session" && (goal.machineCheck || goal.dependencyInstall) && !machineCheckSupported(cwd)) throw new Error("Goal VM execution is currently unavailable: process-tree sealing cannot be verified.")
158
+ if (enforceSessionMode && !background && goal.executionMode === "session" && goal.permissionMode !== currentMode) throw new Error("Goal permission mode differs from the current session; restore its mode before resuming")
156
159
  const stopped = recoverStoppedOwner(store, goal)
157
160
  if (sessionId && stopped.sessionId === sessionId) store.pauseForInput(cwd, sessionId)
158
161
  launch(store.prepareResume(stopped.id))
@@ -165,7 +168,7 @@ export function goalCommand(args: string[], cwd: string, currentMode: import("./
165
168
  if (!objective) throw new Error("Goal objective is required")
166
169
  const machineCheck = checkArgs[0]?.slice("--check=".length) as "bun" | "npm" | "pytest" | "go" | undefined
167
170
  if (sessionId) store.pauseForInput(cwd, sessionId)
168
- const goal = store.create({ objective, cwd, sessionId, deadlineAt: limits.deadlineAt, deliveryPolicy, permissionMode, machineCheck, dependencyInstall: installArgs.length ? "npm" : undefined })
171
+ const goal = store.create({ executionMode: deliveryPolicy === "artifact" ? "isolated" : "session", objective, cwd, sessionId, deadlineAt: limits.deadlineAt, deliveryPolicy, permissionMode, machineCheck, dependencyInstall: installArgs.length ? "npm" : undefined })
169
172
  const ledger = new GoalBudgetLedger(goalDatabasePath())
170
173
  try {
171
174
  // Usage remains durable and shared across all phases and children; no
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!(event, context.operationId) } : {}),
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
+ }
@@ -1,3 +1,5 @@
1
+ import { GoalTurnHost } from "./goal-turn-host.js"
2
+ import type { GoalTurnExecutor } from "./goal-turn.js"
1
3
  import { GoalController } from "../zapsdk/goal/controller.js"
2
4
  import { GoalStore } from "../zapsdk/goal/store.js"
3
5
  import { LocalGoalHost } from "./goal-host.js"
@@ -5,6 +7,7 @@ import { goalDatabasePath } from "./goal-command.js"
5
7
 
6
8
  /** Shared controller entry for attached sessions and explicitly detached runners. */
7
9
  export interface GoalRunnerObserver {
10
+ runTurn?: GoalTurnExecutor
8
11
  signal?: AbortSignal
9
12
  onEvent?: (event: import("../zapsdk/agent/events.js").AgentEvent, operationId: string) => void
10
13
  onState?: (goal: import("../zapsdk/goal/contracts.js").GoalRecord) => void
@@ -32,7 +35,7 @@ export async function runGoalRunner(id: string, observer: GoalRunnerObserver = {
32
35
  try {
33
36
  const goal = store.get(id)
34
37
  if (!goal || goal.cwd !== process.cwd()) throw new Error("Goal does not belong to the current workspace")
35
- const controller = new GoalController(store, new LocalGoalHost(id, observer.onEvent), id)
38
+ const controller = new GoalController(store, (goal.executionMode === "session" ? new GoalTurnHost(id, observer.onEvent, observer.runTurn) : new LocalGoalHost(id, observer.onEvent)), id)
36
39
  if (goal.inFlight) {
37
40
  const reconciled = await controller.recover()
38
41
  if (reconciled.inFlight || reconciled.status === "blocked") {
@@ -3,13 +3,16 @@ 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 {
9
+ runTurn?: import("./goal-turn.js").GoalTurnExecutor
8
10
  permissionMode?: PermissionMode
9
11
  sessionId?: string
10
12
  signal?: AbortSignal
11
13
  onStart?: (goal: GoalRecord) => void
12
14
  onMessage: (text: string) => void
15
+ onResult?: (markdown: string) => void
13
16
  onState?: (goal: GoalRecord) => void
14
17
  onEvent?: (event: AgentEvent, scope: string) => void
15
18
  }
@@ -35,7 +38,7 @@ export async function executeGoalCommand(args: string[], cwd: string, options: G
35
38
  const message = goalCommand(args, cwd, options.permissionMode, process.platform, options.sessionId, goal => {
36
39
  if (attached.has(key)) throw new Error("A foreground Goal is already running in this session")
37
40
  foreground = goal
38
- })
41
+ }, !!options.runTurn)
39
42
  options.onMessage(message)
40
43
  if (!foreground) return 0
41
44
  const goal = foreground as GoalRecord
@@ -58,7 +61,7 @@ export async function executeGoalCommand(args: string[], cwd: string, options: G
58
61
  try {
59
62
  options.onStart?.(goal)
60
63
  const { runGoalRunner } = await import("./goal-runner.js")
61
- const code = await runGoalRunner(goal.id, { signal: options.signal, onState: options.onState,
64
+ const code = await runGoalRunner(goal.id, { runTurn: options.runTurn, signal: options.signal, onState: options.onState,
62
65
  onEvent: (event, operationId) => options.onEvent?.(event, `${goal.id}:${operationId}`),
63
66
  onOutcome: value => { outcome = value },
64
67
  })
@@ -69,7 +72,10 @@ export async function executeGoalCommand(args: string[], cwd: string, options: G
69
72
  }
70
73
  if (outcome) {
71
74
  options.onMessage(`Goal ${outcome.id} · ${outcome.status}${outcome.stopReason ? ` · ${outcome.stopReason}` : ""}`)
72
- if (outcome.delivery) options.onMessage(`Goal delivery: ${JSON.stringify(outcome.delivery)}`)
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)
73
79
  }
74
80
  return code
75
81
  } finally { attached.delete(key); settle() }